Skip to content

Fix #5 flat wizard exposure, drop AUTO from the gain list, and harden the native driver path - #13

Open
totoantibes wants to merge 21 commits into
dougforpres:masterfrom
totoantibes:fix/stability
Open

totoantibes wants to merge 21 commits into
dougforpres:masterfrom
totoantibes:fix/stability

Conversation

@totoantibes

@totoantibes totoantibes commented Aug 30, 2026 •

Copy link
Copy Markdown

Work from a season of real imaging on an ILCE-7S (13 sessions, ~3000 frames).
The headline result is that the driver-side cause of #5 is fixed, and the fix
is measured rather than asserted
(see the caveat on flat modes below); the
rest is hardening around the native driver, plus an honest account of what is
still broken.

Please note before reading the diff

This branch starts by applying #11 (@christian-photo) and #10 (@shurkanTwo),
with their commits and authorship intact. That is not my work and is not being
re-submitted as mine - it is here because everything after it builds on it. If
you would rather merge those two first, I am happy to rebase and reopen.

I also tried to extract the #5 fix as a standalone PR against master and
could not do it honestly: it depends on the call-serialisation rework, so every
commit conflicts. More to the point, a re-split branch would not be the thing
that actually ran for 3000 frames. I would rather give you the artifact that
was tested than a tidier one that was not.


Fixes #5 - flat wizard does not change exposure after the first attempt

Shutter speed is a Range property, so the driver cannot assign it; it steps
toward the target. If the first step has no effect,
NudgePropertyAndWait gives up after one ~2s stall and the capture starts at
the old speed - while SetPropertyValue still returns ERROR_SUCCESS. Back
to back exposures hit this constantly, because the camera ignores the step for
a moment after handing over the previous frame. From the driver log, asked to
go from 0.5s down to 0.0078s, every frame was taken at 1s:

17:29:43.569 Property xd20d is set to x000a000a, nudging x00000001 toward x0005000a
17:29:45.691 Shutter time is x000a000a (1.000000 s), we wanted (0.501090 s)

Several frames at an identical speed is exactly what breaks the wizard: NINA
changes the exposure, sees the signal not move, calls the camera response
non-linear and stops converging.

The plugin now reads the shutter speed back and re-issues the change until it
takes, bounded by a 12s budget.

Measured over the 13 sessions: 193 shutter changes needed a re-issue and got
one, 192 of them settling in exactly 2 extra attempts.
Every one of those is
a frame that would otherwise have been exposed at the wrong speed.

The match tolerance, and getting it wrong twice

Deciding "did the camera take it" needs a tolerance, and it has to sit above
the widest half-step in the ladder and below the narrowest whole step.

It was x1.25 first - nearly a whole step - which accepted requests that should
have moved the shutter and reproduced the plateau. I tightened it to x1.13 on
the assumption that Sony steps in uniform third-stops (x1.26), giving a x1.122
half-step.

That assumption is wrong, and it is worth flagging for anyone else working in
here.
Harvested from 201 shutter readbacks, the real ladder on this body has
adjacent steps of x1.20, x1.25, x1.28 and x1.3333 - the wide ones being
1/60 to 1/80, 1/30 to 1/40, and 0.6s to 0.8s. A request landing midway across a
x1.3333 gap sits x1.1547 from the nearer step, so x1.13 guarantees that a
camera resting on the closest speed it owns is judged a failure. Four frames
were logged Exposure time was not applied while the correct value was already
set, all four inside x1.3333 gaps.

Now x1.16: above the widest real half-step (x1.1547), below the narrowest whole
step (x1.20). With it correct, sitting on the nearest step always matches, so
the error branch is left reporting only a camera genuinely stuck away from
target - what it was written for.

This constant changed the same day this PR was opened and has no field time
yet.
The 193-retry result above is from the x1.13 build; x1.16 only widens
what counts as already-correct, so it cannot reintroduce the plateau, but I am
flagging it rather than implying it has a season behind it.

Which flat mode this was confirmed in

Worth stating precisely, so nobody tests this and concludes it did not work.
The clean converging pass was obtained with the Flat Wizard in dynamic
exposure mode
. In NINA's Sky Flat mode the targeting still went astray
even with this fix in place, and I had to switch away from it to get a good
run.

Sky Flat predicts how the sky is changing and adjusts ahead of the measurement,
so it depends on more than the shutter speed arriving correctly. This PR only
makes the requested exposure actually reach the camera - which is the
driver-side half of #5, and the half that was demonstrably broken. Whatever is
left in the Sky Flat path is upstream of that and I have not characterised it,
so I am not claiming it here.

Fixes the gain list offering values that are not gains

ISO_AUTO (0x00FFFFFF) and the multi-frame-NR floor (0x01000000) were
being exposed as selectable gains. Sorting the list put AUTO at the top as
GainMax, and the flat wizard would drive to it and abort. Both are filtered
out, and _gains is now the single source for Gains / GainMin / GainMax
rather than three lists that could disagree. AUTO ISO has no use in an astro
sequence, so nothing is lost by removing it.

Recovers a stuck capture instead of refusing the rest of the session

If a capture was left in flight, every subsequent start was refused with
TaskCanceledException and no log line, so a bias sequence would run to
completion having silently taken zero frames; the only way out was a
disconnect/reconnect. The busy path now logs, throws SonyException rather
than a cancellation, and after two consecutive refusals issues a cancel to
clear the stuck capture. Least field-tested change here.

Hardening around the native driver (relates to #4)

  • Every call into SonyMTPCamera.dll goes through one serialisation point, so
    two threads can no longer be inside the driver at once.
  • Native calls are bounded by a watchdog (30s general, 60s open/capture)
    instead of hanging the UI thread indefinitely.
  • Repeated failures mark the camera lost rather than continuing to drive a dead
    handle, and the user is told on screen how to recover (power-cycle) instead
    of the session failing silently.
  • GetCaptureStatus is a one-shot - the first COMPLETE call fetches the image
    and resets status. An earlier attempt here to defer the copy broke stills
    entirely (live view worked, no stills); it is reverted, and the frame is now
    copied inline exactly once. Noting it because the API shape is not obvious
    and it is an easy mistake to repeat.
  • A wedged driver can be retried rather than locking out the remainder of the
    session.

USB disconnect detection - opt-in, default off

Registers for CM_Register_Notification on GUID_DEVINTERFACE_WPD, so a
removal is noticed from the OS rather than by a call failing, and the camera is
reopened when it returns.

It is off by default and I recommend it stays that way. It is paired with
driver-side changes in dougforpres/SonyCamera (against workerThread), and
even with both, removal is not reliably survivable. Three of the 13
sessions still ended abnormally within ~2s of a removal, with the camera
idle, not mid-capture. I could not obtain a faulting module for those, so I
cannot say where the remaining failure is.

Enabled, it demonstrably survives removal, a 2.5 minute absence and
reconnection - so it is useful, but it is a mitigation and I did not want it on
by default on that evidence.


Verification summary

  • Built Release clean. The NU1701 restore warnings are pre-existing and
    untouched.
  • 13 sessions, ~3000 frames, on an ILCE-7S with no lens (straight into a
    Newtonian focuser), so the lens paths are unexercised by this testing.
  • Flat panel wizard does not change the camera exp length after the first attempt #5 fix: 193 measured retries, 0 unexplained exposure failures after the
    tolerance correction.
  • Not verified: the x1.16 constant in the field; stuck-capture recovery beyond
    the case that prompted it; anything lens-related; any camera other than the
    ILCE-7S.

One thing that is not a code change but may be worth documenting

The registry default of Bits Per Pixel = 14 produces the wrong scale for this
body. NINA's percentage targets are computed as raw ~= pct * 2^(2b-16), so at
b=14 a 70% target asks for about 17% of full well and the flat wizard chases a
value it cannot reach. Setting it to 15 made targets and measured ADU agree
and the wizard converge. I have not worked out whether that is right for other
Sony bodies, so I have not changed a default - but it cost a lot of nights and
it is not documented anywhere I could find.

christian-photo and others added 21 commits August 22, 2026 15:39
FocuserDriver.HasSetupDialog threw NotImplementedException from a
property getter, and TempComp's setter did the same. Both are queried
by NINA on the IDevice instance, so throwing there breaks callers that
only wanted to know whether a setup dialog exists.

Co-authored-by: christian-photo <[email protected]>
Adds an "Enable native cancel" plugin setting (default off), serializes
capture start/cancel/status behind a lock, refuses to start a new
exposure while the camera reports busy, and treats an abort as a soft
cancel when native CancelCapture is disabled.

Co-authored-by: shurkanTwo <[email protected]>
The crash behind dougforpres#4 is an access violation raised inside the native
driver (SonyMTPCamera.dll, or PortableDeviceApi.dll underneath it).
Managed code cannot catch that, so it takes the whole NINA process with
it. PR dougforpres#10 removed one trigger by not calling native CancelCapture by
default; this closes the rest of the window.

The plugin was reaching the driver from four places at once: the capture
task (start/cancel/status/download), NINA's camera update timer (battery
and gain), NINA's focuser update timer (position and limit - the focuser
shares the camera's device handle), and the UI thread setting gain. Any
of those could be in flight when the camera was closed, which frees
memory the other thread is still reading.

- SonyDriver is now the single funnel and holds one lock across every
  native call, including the 25MB image copy out of the driver's buffer
  in GetCaptureStatus.
- CloseCamera invalidates the handle under that lock, and calls against
  a stale handle are refused rather than passed to the driver. Closing
  twice is now a no-op instead of a second free.
- Three consecutive failures on the calls that always talk to the device
  (capture, live view, focus) close the handle once and mark the camera
  lost, so an unplugged camera stops being polled. Property reads do not
  count towards that - bodies legitimately refuse individual properties.
- Connected reports false once the handle is gone, so NINA stops driving
  it. That check is lock-free so it cannot stall the UI behind a
  download.
- Polled reads (battery, gain, focus position, focus limit) give up
  after 500ms and report the last known value instead of queueing.

Also folded in, all found while tracing this path:

- The minimum-driver-version check built its version array as
  {Major, Minor, Private, Build}, so 1.0.0.36 compared as 1.0.36.0 and
  passed the 1.0.1.17 minimum. It then failed at delegate setup with
  "Unable to locate method GetSupportedDeviceCount". (dougforpres#2)
- StartCapture discarded the result of fSetExposureTime, so a rejected
  shutter speed produced a frame at the previous exposure with no
  indication - which is exactly the flat wizard symptom in dougforpres#5.
- DownloadExposure could return the previous frame after a cancelled or
  failed exposure, because the driver only refreshes its buffer on
  completion.
- A throwing SetAttachedLens/SetFocusPosition left the focuser stuck
  reporting IsMoving; the focuser also never raised PropertyChanged.
- Dropped the unresolvable ReachFramework reference (MSB3245/MSB3243 on
  every build); the build is now warning-clean.
- Do not issue a native cancel once the camera has moved to "reading" or
  "processing": that is the interleaving the log analysis singled out,
  where cancelling releases the buffer GetImage is still filling. The
  frame is seconds away, so let it land and soft-cancel instead.
- Log capture status transitions (not every poll) with the managed
  thread id and a readable state name, which is what makes a NINA log
  line up against the driver's own log after a wedge or a crash.
- Do not clear the cached camera when ignoring a close for a handle that
  is no longer the open one; it may belong to a device that is still
  open.
Robert's 2026-08-21 session log shows the failure that actually costs a
night, and it is not the access violation from dougforpres#4:

  23:59:15  exposure starts, capture status stays at CREATED
  00:00:05  NINA's own 50s timeout fires, exposure fails
  00:00:05  CameraVM logs "Starting Exposure" for the next frame...
            ...and WaitUntilExposureIsReady is never reached
  02:10 and 02:22  the camera drops off USB and re-enumerates
  02:59:07  OutOfMemoryException, then UCEERR_RENDERTHREADFAILURE

StartExposure went into the driver and did not come back. The imaging
thread was gone for two hours fifty-four minutes with nothing logged,
and the process then died. Nothing in the plugin put a bound on any
native call.

- Every call now runs on a worker thread with a 30s watchdog (60s to
  open a camera). A blocked P/Invoke cannot be aborted, so the worker is
  abandoned and the driver is marked wedged so nothing follows it in.
  The caller gets its thread back, which is the point: NINA fails the
  exposure, logs it and tells the user instead of going quiet.
- A wedged driver reports the camera as disconnected, so the sequencer
  stops trying to expose through it.
- CloseCamera gives up after 5s and cleans up locally rather than
  freezing the UI behind a stuck call - disconnecting is the user's way
  out and must not join the queue.

Separately, on the memory side: GetCaptureStatus copied the completed
~25MB frame into a fresh array on every read that saw STATUS_COMPLETE.
Status is polled at 10Hz during a capture and read again on the next
exposure's preflight, so the same frame was copied several times per
exposure, each one onto the large object heap, which is not compacted.
The copy now happens once, in DownloadLastImage, when NINA asks for it.
Still a fresh array each time on purpose - NINA saves asynchronously, so
a shared buffer would let the next capture overwrite an image that is
still being written to disk.

This is a contributing factor to the OOM, not a proven cause; the log
has no memory instrumentation to confirm where the 7.75GB went.
Deploying the previous build to the imaging PC gave live view but no
stills. The driver log says exactly why:

  16:52:34.083  Set capture status to: 4
  16:52:34.145  Camera::GetCaptureStatus() - Capture Complete
  16:52:34.164  In:: Image::GetImageData
  16:52:34.171  Set capture status to: 3
  16:52:34.177  Camera::GetCaptureStatus() - Capture Cancelled

The first call that observes COMPLETE fetches the frame and then the
driver resets its own status to CANCELLED. I had moved the copy out to
download time, which re-reads the status - by then 3 - so the download
threw. Live view goes through GetPreviewImage and was unaffected.

The copy is back where it was, now with that log quoted in the code so
it does not get optimised away again. My reasoning for moving it was
also wrong: because only one caller can ever see COMPLETE, the frame was
never copied more than once per capture, so there was no redundant
large-object-heap churn to remove. That part of the previous commit
message is retracted; one ~12-25MB allocation per frame is inherent,
since NINA saves asynchronously and a shared buffer would be overwritten
by the next capture.

Kept from the rework:

- Taking the frame clears it, so a cancelled or failed exposure cannot be
  served the previous image. Ownership of "is there a frame" now sits in
  the driver layer that did the copy, rather than being inferred from the
  status this class happened to observe.
- Leftovers are discarded when an exposure starts - after the preflight
  status reads, since a read that sees a stale COMPLETE takes that frame
  as a side effect.

Also narrowed the exposure-time check added for dougforpres#5. SetExposureTime
returns ERROR_NOT_SUPPORTED when the camera has no learnt exposure-time
list, and in that case the driver cannot drive the shutter at all and
the body's own setting is used - which is how those cameras have always
worked. Throwing there would have broken them, so it now warns. Its
valueOut parameter is never populated by the driver, so the log line
that read it back is gone.
From Robert 2026-08-22 17:06 log:

  FlatWizardVM.StartFlatMagic - SequenceEntityFailedValidationException:
  Invalid Gain. The Gain has to be set between 50 and 128000 but is set
  to 0

Gains presents AUTO (0xffffff) to NINA as 0, but GainMin took the
minimum of the *raw* ISO options, where AUTO is a huge number - so the
reported minimum was the lowest real ISO and the one value the dropdown
offered for AUTO fell outside the advertised range. The flat wizard
validates before it starts, so it failed without taking a frame.

GainMax had the mirror-image bug: Last() rather than the maximum, so an
option list with AUTO at the end would have reported 16777215.

Gains, GainMin and GainMax now all derive from one mapped list built at
connect time, so they cannot disagree. The range is logged on connect.

Also log the shutter speed the camera was actually set to alongside the
one that was requested. A camera only has discrete shutter speeds, so
the driver picks the nearest and reports success; when a search like the
flat wizard bisection narrows below the gap between adjacent speeds,
every further step produces an identical exposure and it cannot
converge. That is the suspected mechanism behind dougforpres#5 and until now only
the requested value appeared in the log, so the two were
indistinguishable. Info level so it lands in a default NINA log.
)

Shutter speed on these bodies is a Range property: the driver cannot
assign it, only step the camera one click at a time toward the target.
When the first step has no effect it concludes the camera will not move
and starts the capture at the old speed anyway.

That happens whenever exposures are taken back to back - the camera
ignores the step for a moment after handing over the previous frame.
Robert 2026-08-22 17:29 driver log, mid sky-flat search:

  17:29:17.844  nudging x00000001 toward x000a000a   (12 steps, 10.7s)
  17:29:28.560  Shutter time is x000a000a (1.000000 s), we wanted 1.0 s   OK

  17:29:43.569  nudging x00000001 toward x0005000a   (1 step, no movement)
  17:29:45.691  Shutter time is x000a000a (1.000000 s), we wanted 0.501090 s

Every subsequent frame - 0.5, 0.25, 0.125, 0.063, 0.031, 0.016, 0.0078s
- was exposed at 1s. The measured ADU was identical to five decimal
places across a 128x range, which is what stops the flat wizard search
from ever converging. It works by hand in the imaging tab only because
there are pauses between frames.

The root cause is in SonyMTPCamera.dll, whose 1.0.1.x source is not
public, so this is a workaround rather than a fix: after setting the
exposure the plugin reads shutter speed (0xd20d) back, decodes it, and
re-issues the change until the camera is within a quarter-stop of what
was asked for - or gives up after 12s and says so at ERROR level instead
of silently shooting at the wrong speed. Re-issuing works because each
call steps again, and once the camera is responsive the driver walks all
the way to the target.

Quantisation is real too but secondary: 1.00072, 1.00145 and 1.00217s
all resolve to the same 1s code with no step attempted, so a bisection
that narrows below one third-stop cannot converge either. The tolerance
accounts for that rather than fighting it.

StartCapture gets a 60s watchdog rather than 30s, since it now owns the
settle loop. valueOut is not populated by 1.0.1.21 either, so the
readback goes through GetSinglePropertyValue instead.
Robert 2026-08-22 17:56 session, ILCE-7S, driver 1.0.1.21:

  21 captures, 17 needed the settle retry, 17/17 reached the requested
  exposure (typically 2 extra attempts over 3-5s, worst 7.7s)
  0 "not applied" errors, 0 watchdog trips, 0 SonyExceptions
  Sky flat search converged: "Found exposure time at 0.0426s"

The measured ADU now tracks the exposure (1s->65459, 0.5s->62134,
0.25s->19070, 0.097s->17016, 0.049s->9636, 0.024s->5940) instead of
sitting frozen across a 128x range, which is what stopped the search
converging before.

One frame needed three stalled attempts before the camera moved, so
raising the no-progress limit from 3 to 5 was load-bearing; the driver
log confirms a single shutter press per frame, so the retry is not
double-exposing.

The session also exercised an abort mid-capture - the scenario behind dougforpres#4
- and NINA survived it cleanly.
AUTO is not a usable setting in any astro scenario: the camera picks its
own sensitivity per frame, so measured signal stops being a function of
exposure time. Robert 2026-08-22 18:00 sky flat ran entirely at gain 0
(AUTO) and NINA reported "camera response determined to be non-linear",
with the same applied 0.25s exposure reading 19070, 19513, 19488 and
then 38931 ADU. The driver log shows one shutter press per frame, so
that spread is the camera changing ISO, not a capture problem.

Worth noting this was self-inflicted: making the gain range consistent
in the previous commit is what let AUTO be selected at all - NINA had
been rejecting it. Removing it from the option list is the right answer
rather than leaving a value that is valid but never correct.

- AUTO (0x00ffffff) is filtered out of the ISO options, alongside the
  Multi Frame NR block that was already excluded. Both now have named
  constants instead of a bare magic comparison.
- If the camera is physically on AUTO, Gain reports -1 (unknown) rather
  than inventing a number, and says so once in the log and in a
  notification.
Robert overnight session 2026-08-22/23, dawn sky flats. Requested vs
what the camera was actually left at:

  0.009156 -> 0.01     ADU 29306
  0.010237 -> 0.01     ADU 29325   (unchanged)
  0.011439 -> 0.01     ADU 29334   (unchanged, nearest step was 0.0125)
  0.012777 -> 0.0125   ADU 35621
  0.011754 -> 0.0125   ADU 35637   (unchanged)
  0.010807 -> 0.0125   ADU 35661   (unchanged, nearest step was 0.01)

The x1.25 tolerance was nearly a whole third-stop, so requests that
should have moved the shutter were accepted as already-good. Three
consecutive frames of an exposure search were taken at an identical
speed, and NINA reads "changed the exposure, signal did not move" as a
non-linear camera response - it gave up with "sky is too bright" while
asking for longer exposures each time.

Tolerance is now x1.13, just above the x1.122 worst case for a request
landing midway between two third-stop steps.

That alone would make a camera with coarser steps burn the whole retry
budget and then log an ERROR for what is really the closest it can do,
so the loop now separates the two cases: if the shutter moved and then
settled, that is the nearest achievable and it is reported at Info with
the value that will actually be used. ERROR is reserved for a camera
that never moved at all, which is the original dougforpres#5 fault.

Rest of that session was clean: 864 captures, 863 completions, 60
successful settle retries, and no guard events at all - no circuit
breaker trips, no watchdog trips, no SonyExceptions, no OOM.
2026-08-23 08:51 crash. Camera connected at 08:30:29 and never
disconnected in NINA; last capture 08:42:29, so from then on the only
thing touching it was NINA polling battery and gain every ~2s.

  08:50:59.4307  USB Device disconnected ... ILCE-7S
  08:51:00.0349  New USB device detected ... ILCE-7S
  <log ends, no shutdown marker>

The guard contributed nothing, for two reasons worth separating:

1. Property reads were excluded from the circuit breaker outright, to
   avoid mistaking a body that refuses one property for an unplugged
   camera. But while idle those polls are the ONLY calls being made, so
   an idle disconnect had nothing that could ever trip it. Now a
   property that has already been seen working counts towards loss when
   it starts failing; one that has never worked still does not.
2. The polled-read failure was logged at Debug, which NINA's default
   level discards, so even the evidence was invisible. Now Warning.

Neither would have saved this particular crash, and the log says why:
zero failed native calls, zero exceptions, nothing logged by the plugin
at all between the device vanishing and the process ending. No call ever
returned an error for the breaker to count - the fault was immediate.
With the driver log off it cannot be established whether it happened in
a call the plugin made or on the driver's own PnP event thread, where
the plugin is not in the path at all and no managed-side guard can help.

Also worth recording: the device came back 0.6s after it went, with the
same PnP id. That is a bus re-enumeration, not an unplug, and it is a
repeat - the same signature appears twice in the 2026-08-21 session
(02:10:11/02:10:12 and 02:22:11/02:22:11).
The camera's USB socket is physically fragile on this rig and slewing
tugs the cable, so a transient drop is a normal operating condition
rather than a fault to prevent. Every occurrence so far has been a
re-enumeration, not an unplug - the device returns in 0.2 to 1.0s under
the same PnP id:

  21 Aug  02:10:11.5 -> 02:10:12.6   (1.0s)
  21 Aug  02:22:11.2 -> 02:22:11.4   (0.2s)
  23 Aug  08:50:59.4 -> 08:51:00.0   (0.6s)

So the goal is to survive and recover, not to detect after the fact.

- DeviceWatcher subscribes to CM_Register_Notification for the WPD
  device interface and matches the symbolic link against the opened
  device id. No new dependencies, no window, no message pump.
- On removal the door shuts immediately: volatile flags only, no lock
  and nothing native, so no thread can hand the driver a device that is
  not there. The device object is deliberately left unclosed - calling
  into the driver about hardware that just vanished is the thing being
  avoided - and is tidied up on the way back in.
- On return the camera is reopened, after letting the MTP stack settle,
  up to three times. Skipped entirely if the user disconnected on
  purpose.

This narrows the exposure window from up to two seconds of blind polling
down to milliseconds. It cannot close it: an access violation raised
inside SonyMTPCamera.dll ends the process before any managed code runs,
and if the fault happens on the driver's own PnP event thread the plugin
is not even in the call path.
2026-08-23 15:34 the camera would not connect. The log says why:

  15:18:28  Found 1 Sony Cameras
  15:34:35  Disconnected Camera            (user clicks connect)
  15:35:35  Sony: the driver did not return from 'open camera ...' within 60s
  15:36:25  Cannot enumerate cameras: the Sony driver stopped responding
            earlier in this session
  15:36:25  Found 0 Sony Cameras

The driver hung inside OpenCamera and never came back. Before the
watchdog that would have hung NINA's connect task indefinitely, which is
the 21 Aug failure. It was caught in 60s instead, and the wedged state
then latched as designed - correctly, because the thread is still stuck
inside the DLL.

What was wrong was the user experience: the only symptom on screen was
the camera silently vanishing from the equipment list, which looks like
the plugin broke rather than the driver hanging. Now it says so with a
notification.

The advice was also incomplete. Restarting NINA alone often is not
enough - the driver hangs on open because the camera is still holding a
session from a run that ended badly, and only a power cycle clears that.
Both the log and the message now say to power-cycle the camera as well.

Note for the record that the device watcher added in the previous commit
was not involved: it is registered at the end of OpenCamera, which never
completed, and the log contains no "watching for removal" line at all.
Registering it inside OpenCamera meant it sat inside the 60s watchdog,
and its only log line prints after CM_Register_Notification returns. So
when a connect stalled at 15:34 and no "watching for removal" appeared,
the log could not distinguish "the driver hung before we got there" from
"the registration itself hung". I claimed the former; the log does not
actually support that, and a component that is not load-bearing should
never have been able to muddy the diagnosis - or delay a connect - in
the first place.

The watcher now starts on its own thread after the camera is open. It is
a nicety; the camera works without it. Also logs immediately before the
registration call, so a block there is unambiguous next time.

Evidence the camera itself was the problem, from the 22:06 session after
a power cycle:

  22:07:27.049  Disconnected Camera     (connect flow begins)
  22:07:28.046  gain range logged       (OpenCamera returned)

A healthy open takes about a second. At 15:34 it passed 60. The rollback
build cannot account for that difference - it differs only in code that
runs once the device is already open.
Two connect failures now sit against the watcher build and one success
against the build without it - including a power cycle that did not help
on the watcher build but did on the rollback. My earlier reasoning that
the watcher could not affect OpenDevice does not survive that.

There is a mechanism I dismissed too readily: the driver registers its
own WPD device-event notification (its log shows the registration cookie
it later unregisters), and a CM_Register_Notification from the plugin
may contend with it inside the PnP subsystem.

So it is now a plugin setting, default off, described in the options
panel as experimental with that history stated. Everything else - the
serialization, watchdog, circuit breaker, exposure settle, gain fix -
is unaffected and stays on.

Combined with the previous commit moving registration off the connect
path, the worst case with it enabled should now be that it does not
work, rather than that the camera will not open.
The 2026-08-23 15:17 session, read end to end:

  15:35:35  watchdog fired, driver hung on open, wedge latched
  15:39:54  USB removed  \
  15:40:17  USB inserted /  camera power-cycled
            refused: wedge latched
  20:28     power-cycled again
            refused: wedge latched
  21:56     power-cycled again
            refused: wedge latched

Three power cycles over six hours, every attempt refused by a flag set
at the first failure. There was no way back except restarting NINA, and
nothing said so - the camera simply vanished from the equipment list.
The session that finally worked at 22:06 did so because it was a fresh
process, not because of the DLL it was running. The device watcher I
suspected on that evidence was not involved.

Rescanning for equipment, or connecting, now clears the wedge and tries
again, up to three times per session; a successful open restores the
budget. The stuck thread is still stuck and that cannot be fixed, so a
retry may simply hang again - but it is bounded by the watchdog, and one
more stuck thread is a much better trade than an evening of a camera
that refuses to appear. When the retries are gone the message says to
restart NINA, which it never did before.
Robert 2026-08-25 17:41, a 31-frame bias run that took no frames:

  17:41:47.8690  Starting Exposure 0.000125s
  17:41:47.8702  skipping cancel (start exposure reset)
  17:41:47.8704  skipping cancel (abort request)
  17:41:47.8704  AbortExposure requested; letting capture finish
  17:41:47.8708  Starting ... next TakeExposure

All 31 iterations went by in under a tenth of a second, and the log then
recorded "LoopCondition finished. Iterations: 31 / 31" and "Advanced
Sequence finished". Nothing was captured. The camera had to be
disconnected and reconnected before a bias run would work.

Three faults, all in the cancel-guard logic as applied:

A stuck capture status had no way to clear. The original code cancelled
before every exposure, with the comment that this resets the status.
Making that conditional on native cancel - off by default - stopped the
crashes but removed the only way out: a camera that never finished a
capture refused every subsequent start, forever. The cancel is back, but
only when the same busy status has been refused twice with nothing of
ours running. That is a last resort on a camera that is already stuck,
not something on the path of every exposure.

Refusing with TaskCanceledException told NINA the user had cancelled, so
rather than failing one frame it unwound the whole sequence - and
WaitUntilExposureIsReady registers AbortExposure on the token, which
then fires immediately for every remaining iteration. Hence 31 aborts in
a millisecond. It is a SonyException now, so the instruction fails and
error behaviour applies.

And the refusal was invisible: Notification.ShowWarning with no Logger
call, so the only trace was a toast on screen while the log showed a
sequence completing normally. A guard that rejects work has to say so
in the log - this one cost hours of looking in the wrong place.
…lure

The match tolerance assumed a uniform third-stop ladder (x1.26), so it was
set to x1.13 - just above the x1.122 half-step that implies. The ladder is
not uniform. Measured over 201 shutter readbacks on an ILCE-7S, adjacent
steps are x1.20, x1.25, x1.28 and x1.3333; the widest gaps are 1/60 to
1/80, 1/30 to 1/40 and 0.6s to 0.8s.

A request landing midway across a x1.3333 gap sits x1.1547 from the nearer
step, which x1.13 rejects. The camera is then on the closest speed it has
and correctly refuses to move, but because it never stepped during the call
it fell through to the "never moved off" branch and was logged as an error
saying the exposure was not applied - when the right value was already set.
Four frames across the recorded sessions hit this, every one of them inside
a x1.3333 gap, and in three of the four the camera was exactly on its
nearest available speed.

x1.16 clears the widest real half-step (x1.1547) and stays below the
narrowest whole step (x1.20), so a camera that genuinely should have moved
one click is still rejected. With the tolerance correct, being on the
nearest step always matches, and the error branch is left reporting only a
camera that is genuinely stuck away from the target - which is what it was
written for.
@shurkanTwo

Copy link
Copy Markdown
Contributor

@totoantibes As far as I know the author of NINASonyCameraPlugin @dougforpres does not get/read any GitHub notifications.
To get this and the other PR's merged you might want to give him a nudge via email :)
You can find his contact details on his website: https://retro.kiwi/

@shurkanTwo

shurkanTwo commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Hi @totoantibes, Sony Camera Plugin 1.0.0.5 — combined community maintenance release is available in my fork while we await a reply from @dougforpres about shared maintenance. @dougforpres remains the original author; original contributor commits, credit and MPL-2.0 are preserved.

Your #14 native image/metadata buffer cleanup is included, and selected #13 work is adapted with credit to you: nearest learned-shutter verification/retries, numeric/Bulb transitions, manual ISO filtering, DLL version checking, native-call serialization/timeouts, the qualifying native-error guard and focuser fixes. The newer #10 capture controller is retained. The full #13 PR is not merged: USB auto-reconnect, retrying still-running timed-out workers and forced cancellation after busy starts remain deferred. Complete Sky Flat behavior and native crash elimination are not claimed fixed. Decisions and issue coverage are in the review record.

Manual installation and rollback are documented. Close NINA and replace the existing plugin DLL; use one copy only. NINA's plugin manager still points to the upstream release source.

The separate experimental native device-removal candidate is not included.

Windows CI and all 123 automated tests pass for the combined source. Physical Sony camera/USB behavior and the complete popup UI report remain unverified. Please report camera/NINA/native-driver versions and results in the fork's issue tracker.

shurkanTwo added a commit to shurkanTwo/NINASonyCameraPlugin that referenced this pull request Oct 17, 2026
Preserve aborts through blocked start preflight, verify the nearest learned
shutter step, retry unchanged Bulb mode, and stop native access after three
qualifying consecutive device errors. Exercise the production native wrappers
in portable regression tests and update manual installation and review notes.

Restore Robert Hasson's repeated-failure protection from upstream PR dougforpres#13
with restart-only recovery and exclusions for unsupported properties.

Co-authored-by: Robert Hasson <[email protected]>
alexkirkp added a commit to alexkirkp/NINASonyCameraPlugin that referenced this pull request Nov 12, 2026
Chose to keep AUTO selectable (gain 0 maps to 0xFFFFFF on write, including the post-reconnect replay) rather than follow upstream PR dougforpres#13, which hides it. GainMin/GainMax now use the smallest/largest real ISO whatever the list order. No test project exists; verified by build only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flat panel wizard does not change the camera exp length after the first attempt

3 participants