Skip to content

Survive USB disconnects: fix crashes, hangs and races on device removal - #19

Open
riversn wants to merge 2 commits into
dougforpres:workerThreadfrom
riversn:fix/usb-disconnect-recovery
Open

riversn wants to merge 2 commits into
dougforpres:workerThreadfrom
riversn:fix/usb-disconnect-recovery

Conversation

@riversn

@riversn riversn commented Oct 22, 2026 •

Copy link
Copy Markdown

When a Sony camera is unplugged during a session, or drops off USB on its own, the driver currently crashes or freezes the host application. I hit this with an ILCE-7M3 in N.I.N.A. 3.2 (crash dump: AV at SonyMTPCamera.dll+0x234B7 on the WPD event thread, 1.0.1.21). While fixing it I found a chain of related problems on the removal and recovery paths. This PR fixes them so the host can close and reopen the camera after a drop and carry on.

Base: workerThread @ 21f469f (1.0.1.21).

Commits

  1. Add the missing x64 libusbK import library. .gitignore excludes x64/, so libusbK\x64\libusbk.lib was never committed and Release|x64 doesn't link. It's generated from the x86 export list (libusbK.def), with a .gitignore exception for that folder.
  2. Survive USB disconnects. The commit message lists every fix and its root cause. In summary:

Crashes

  • DeviceEventHandler::OnEvent released an uninitialised IPortableDevicePropVariantCollection* when an event carries no MTP parameters (e.g. Device Removed). This is the original crash.
  • The event handler was deleted while WPD still held references, and kept a raw Camera* after close. It's now reference counted, explicitly (un)registered with a per-instance cookie, and inert after unregistering, and the camera drains in-flight callbacks before deletion.
  • Exported functions used a null Camera* for stale or already-closed handles (a host calling CloseDevice twice). They now return ERROR_INVALID_HANDLE, and closes are serialised.
  • CameraTask::Start created its completion semaphore already signalled, so Cancel() never waited, and StartCapture/CancelCapture deleted tasks the worker was still running (use-after-free in CameraTask::Step).
  • Image-ready events replaced m_downloadAndProcessImageTask without a lock.

Hangs

  • downloadImage looped forever when GetImage failed, blocking the worker so CloseDevice never returned.
  • StartCapture's previous-photo wait could never exit. while (WORD s = x->GetUINT16() != 0) assigns the comparison, and the loop re-read a stale settings copy.
  • CreateCamera registered a camera whose open failed (still unplugged) under handle 0xFFFFFFFF, which isn't INVALID_HANDLE_VALUE on x64, so OpenDevice then waited forever initialising it.

Detection and stability

  • WPD only reports Device Removed on the next device I/O, which can be the end of a long exposure. Removal is now also watched via CM_Register_Notification, and pending captures fail immediately.
  • MTP transactions are serialised per device. Two threads interleaving transfers (a pre-capture discard and an event-driven download) made the camera drop off USB.
  • Image-ready events are ignored from the start of StartCapture until the shutter is released. Fetching a photo while an ILCE-7M3 is processing a shot resets its USB.

Camera behaviour worth knowing (ILCE-7M3)

  • After a mid-exposure unplug, the photo buffer status stays 0x0001 (processing) until the camera is power-cycled, while photos are still taken and delivered normally. The wait for it is now short, and skipped once it's seen stuck.
  • In Continuous drive modes, a shutter hold longer than about 90–100 ms (normal USB timing jitter) produces a second photo. Single Shooting avoids that; worth mentioning to users.

Testing

  • ILCE-7M3, N.I.N.A. 3.2.0.9001, Windows 10 x64.
  • Repeated manual unplug/replug during short and 30 s exposures: no crash or hang, and the host reconnects.
  • A natural drop after about 2¼ h was recovered automatically, which also exposed the last race fixed here.
  • Then a 7.7-hour run: 7,790 exposures, 0 disconnects, 0 failed frames, one photo per shutter press.
  • Built Release|x64 with the v145 toolset (project settings unchanged).

Relation to other open PRs

The x64 configurations link libusbK\x64\libusbk.lib, but the repo only has
the x86 libusbK.lib: .gitignore excludes every x64/ folder, so the x64 copy
was never committed and Release|x64 fails to link (LNK1181).

Generate it from the x86 library's export list (libusbK.def, 107 undecorated
exports; libusbK.dll exports the same names on both architectures) with
"lib /def:libusbK.def /machine:x64 /out:x64\libusbk.lib", and add a
.gitignore exception for that folder.
Unplugging the camera (or it dropping off USB on its own) during a session
crashed or froze the host (seen with N.I.N.A.). Fixes, by area:

Crashes
- DeviceEventHandler::OnEvent released an uninitialised
  IPortableDevicePropVariantCollection pointer when an event has no MTP
  parameters (e.g. Device Removed): AV on the WPD callback thread.
- The event handler was deleted while WPD still held references, and kept a
  raw Camera* after close. It is now reference counted, registered/unregistered
  explicitly (per-instance cookie instead of a global), ignores events once
  unregistered, and the camera waits for in-flight callbacks before deletion.
- Exported functions used a null Camera* for stale or already-closed handles
  (double CloseDevice). They now return ERROR_INVALID_HANDLE, and closes are
  serialised.
- CameraTask::Start created its completion semaphore already signalled, so
  Cancel() never waited and StartCapture/CancelCapture deleted tasks the worker
  was still running (use-after-free in CameraTask::Step). The semaphore now
  starts unsignalled, tasks are deleted only after the worker finishes them,
  and are waited for outside m_hBusyMutex.
- Image-ready events replaced m_downloadAndProcessImageTask without a lock;
  duplicate notifications are now ignored while a download exists.

Hangs
- downloadImage looped forever when GetImage failed (imageReady was never
  updated), blocking the worker so CloseDevice never returned. Now limited to
  5 attempts, and the capture is reported as failed.
- StartCapture's previous-photo wait was endless: "WORD x = a != 0" assigns
  the comparison, and the loop re-read a stale settings copy. It now re-reads
  the live status with a timeout and then proceeds.
- CreateCamera registered a camera whose open failed (still unplugged) under
  handle 0xFFFFFFFF, which is not INVALID_HANDLE_VALUE on x64; OpenDevice then
  initialised it and waited forever. Failed opens are no longer registered.
- After a mid-exposure unplug an ILCE-7M3 reports photo buffer status 0x0001
  (processing) indefinitely while still shooting normally; the wait for it is
  short and is skipped once seen stuck.

Disconnect detection
- WPD only reports Device Removed on the next device I/O (possibly the end of a
  long exposure). Removal is also watched with CM_Register_Notification on the
  device interface, so it is seen as soon as the cable is pulled.
- On removal the current capture is reported as failed at once, and starts,
  downloads and exposure waits stop immediately instead of timing out.

Camera stability
- Two threads could interleave MTP transfers (StartCapture discarding a
  waiting photo and a worker download), which made the camera drop off USB.
  MTP transactions are now serialised per device.
- Image-ready events are ignored from the start of StartCapture until the
  shutter is released: fetching a photo while the camera processes a shot
  resets an ILCE-7M3's USB.
- Camera::GetImage leaked ObjectInfo on failure; OpenDeviceEx's exception path
  removed the wrong camera entry.

Tested on an ILCE-7M3 with N.I.N.A. 3.2: manual and natural USB drops recover
without crashing, and a 7.7-hour run (7,790 exposures) had no disconnects.
@riversn riversn changed the title Fix/usb disconnect recovery Survive USB disconnects: fix crashes, hangs and races on device removal Oct 22, 2026
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.

1 participant