camera.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import contextlib
  4. import logging
  5. import os
  6. import subprocess
  7. import sys
  8. import time
  9. import uuid
  10. import zlib
  11. from collections.abc import AsyncGenerator
  12. from fastapi import APIRouter, Depends, HTTPException, Request
  13. from fastapi.responses import Response, StreamingResponse
  14. from sqlalchemy import select
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from backend.app.core import database
  17. from backend.app.core.auth import (
  18. RequireCameraStreamTokenIfAuthEnabled,
  19. RequirePermissionIfAuthEnabled,
  20. create_camera_stream_token,
  21. )
  22. from backend.app.core.database import get_db
  23. from backend.app.core.permissions import Permission
  24. from backend.app.models.printer import Printer
  25. from backend.app.models.user import User
  26. from backend.app.services.camera import (
  27. capture_camera_frame,
  28. close_tls_proxy,
  29. create_tls_proxy,
  30. generate_chamber_image_stream,
  31. get_camera_port,
  32. get_ffmpeg_path,
  33. is_chamber_image_model,
  34. read_next_chamber_frame,
  35. rtsp_socket_timeout_flag,
  36. test_camera_connection,
  37. )
  38. from backend.app.services.camera_fanout import (
  39. MjpegBroadcaster,
  40. get_or_create_broadcaster,
  41. get_subscriber_count,
  42. iter_subscriber,
  43. shutdown_broadcaster,
  44. )
  45. from backend.app.services.camera_light import camera_light
  46. from backend.app.services.camera_profiles import get_camera_profile
  47. from backend.app.utils.ffmpeg_output import summarize_ffmpeg_stderr
  48. logger = logging.getLogger(__name__)
  49. router = APIRouter(prefix="/printers", tags=["camera"])
  50. # Grace period for a SIGTERMed ffmpeg to shut down before we SIGKILL it. Only
  51. # reachable when ffmpeg genuinely ignores SIGTERM: _terminate_ffmpeg drains the
  52. # pipes first, and a drained ffmpeg exits in ~0.15s.
  53. _FFMPEG_TERM_TIMEOUT = 2.0
  54. # Upper bound on waiting for a SIGKILLed ffmpeg to be reaped (#2580).
  55. #
  56. # The original diagnosis — "a killed ffmpeg stuck in uninterruptible I/O on a
  57. # dead RTSP socket" — was wrong, and this bound was capping a deadlock of our
  58. # own making rather than waiting out a stuck process. A process that survives
  59. # SIGKILL would have to be in uninterruptible sleep (state D); the ffmpeg seen
  60. # doing this was in state S, and its returncode was already set to -9 while
  61. # wait() was still blocked. The real cause was undrained pipes (see
  62. # _terminate_ffmpeg), which made this timeout fire on *every* camera close.
  63. #
  64. # Kept as a backstop now that the cause is fixed: it should no longer be
  65. # reachable, and if it ever is, abandoning the wait is still safe because
  66. # cleanup_orphaned_streams' /proc scan reaps any Bambu ffmpeg not attached to
  67. # an active stream on its next pass.
  68. _FFMPEG_KILL_TIMEOUT = 2.0
  69. # How long an RTSP stream may keep emitting byte-identical JPEGs before the
  70. # ffmpeg behind it is restarted (#3218). A dead upstream can leave ffmpeg
  71. # repeating its last frame indefinitely: measured on a P2S, ~29 fps of one
  72. # frame for two hours with no socket to the printer left at all, while every
  73. # check that counts frames saw a healthy stream. A live camera practically
  74. # never repeats a frame byte for byte -- sensor noise changes every one (2262
  75. # of 2262 distinct on an idle X1C chamber, #3189) -- so a run this long means
  76. # the picture is frozen.
  77. _RTSP_FROZEN_SECONDS = 20.0
  78. # "Practically never" is not never: a dark, idle chamber can encode to the same
  79. # frame every time. When the first frame after such a restart is the frozen one
  80. # again, the camera really is showing that picture, and the stream only
  81. # re-checks at this much longer interval until the picture changes -- so a
  82. # still scene costs one reconnect every few minutes instead of every 20 s, and a
  83. # real freeze on it is still recovered.
  84. _RTSP_STILL_RECHECK_SECONDS = 300.0
  85. # Track active ffmpeg processes for cleanup
  86. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  87. # Track active chamber image connections for cleanup
  88. _active_chamber_streams: dict[str, tuple] = {}
  89. # Store last frame for each printer (for photo capture from active stream)
  90. _last_frames: dict[int, bytes] = {}
  91. # Track last frame timestamp for each printer (for stall detection)
  92. _last_frame_times: dict[int, float] = {}
  93. # Track stream start times for each printer
  94. _stream_start_times: dict[int, float] = {}
  95. # Track active external camera streams by printer ID
  96. _active_external_streams: set[int] = set()
  97. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  98. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  99. _spawned_ffmpeg_pids: dict[int, float] = {}
  100. # Track disconnect events per stream_id — allows stop endpoint and cleanup
  101. # to signal generators to stop reconnecting instead of just killing the process
  102. _disconnect_events: dict[str, asyncio.Event] = {}
  103. # Track last frame time per stream_id (not just per printer_id) for stale detection
  104. _stream_last_frame_times: dict[str, float] = {}
  105. # How much of a streaming ffmpeg's stderr to retain: enough for the input
  106. # analysis plus a burst of errors, capped so a long-running stream can't grow it.
  107. _FFMPEG_STDERR_TAIL_BYTES = 16384
  108. # Live stderr collectors by pid — see _FfmpegStderrTail. Present means "this
  109. # process's stderr already has a reader; do not open a second one".
  110. _stderr_tails: dict[int, "_FfmpegStderrTail"] = {}
  111. def get_buffered_frame(printer_id: int) -> bytes | None:
  112. """Get the last buffered frame for a printer from an active stream.
  113. Returns the JPEG frame data if available, or None if no active stream.
  114. """
  115. return _last_frames.get(printer_id)
  116. def is_stream_active(printer_id: int) -> bool:
  117. """Return True iff a fan-out camera stream is currently registered for this printer.
  118. Snapshot callers (Obico polling, manual /camera/snapshot) MUST NOT open a
  119. second concurrent RTSP/chamber-image socket while a viewer is attached:
  120. most Bambu firmwares allow only one camera connection, so the competing
  121. socket either kicks the live viewer off or gets refused itself, and the
  122. resulting reconnect storm tears down the fan-out broadcaster (see #1348).
  123. Callers should consult this BEFORE trying to open a fresh socket and skip
  124. the capture cycle when it returns True — even if try_get_active_buffered_frame
  125. returns None (the stream may be running but the first frame hasn't landed
  126. in the buffer yet, or the upstream is mid-reconnect).
  127. """
  128. return any(k.startswith(f"{printer_id}-") for k in _active_streams) or any(
  129. k.startswith(f"{printer_id}-") for k in _active_chamber_streams
  130. )
  131. def try_get_active_buffered_frame(printer_id: int) -> bytes | None:
  132. """Return a buffered frame iff a stream is currently running for this printer.
  133. Snapshot callers (Obico polling, manual /camera/snapshot) tap the fan-out
  134. broadcaster's running upstream instead of opening a second concurrent
  135. RTSP/chamber-image socket. Critical for printers that allow only one
  136. camera connection (e.g. X2D firmware 01.01.00.00; see #1271).
  137. Returns None when no broadcaster is active for this printer, so callers
  138. fall through to their existing fresh-socket path unchanged.
  139. NB: returning None does NOT mean "safe to open a fresh socket" — it also
  140. fires when the stream is registered but no frame has been buffered yet
  141. (startup race, mid-reconnect). Callers that must avoid competing sockets
  142. should consult is_stream_active() first; see #1348.
  143. """
  144. if not is_stream_active(printer_id):
  145. return None
  146. return _last_frames.get(printer_id)
  147. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  148. """Get printer by ID or raise 404."""
  149. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  150. printer = result.scalar_one_or_none()
  151. if not printer:
  152. raise HTTPException(status_code=404, detail="Printer not found")
  153. return printer
  154. async def generate_chamber_mjpeg_stream(
  155. ip_address: str,
  156. access_code: str,
  157. model: str | None,
  158. fps: int = 5,
  159. stream_id: str | None = None,
  160. disconnect_event: asyncio.Event | None = None,
  161. printer_id: int | None = None,
  162. ) -> AsyncGenerator[bytes, None]:
  163. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  164. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  165. """
  166. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  167. # Register disconnect event so stop endpoint can signal us
  168. if stream_id and disconnect_event:
  169. _disconnect_events[stream_id] = disconnect_event
  170. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  171. if connection is None:
  172. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  173. yield (
  174. b"--frame\r\n"
  175. b"Content-Type: text/plain\r\n\r\n"
  176. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  177. )
  178. return
  179. reader, writer = connection
  180. # Track active connection for cleanup
  181. if stream_id:
  182. _active_chamber_streams[stream_id] = (reader, writer)
  183. try:
  184. frame_interval = 1.0 / fps if fps > 0 else 0.2
  185. last_frame_time = 0.0
  186. while True:
  187. # Check if client disconnected
  188. if disconnect_event and disconnect_event.is_set():
  189. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  190. break
  191. # Read next frame
  192. frame = await read_next_chamber_frame(reader, timeout=30.0)
  193. if frame is None:
  194. logger.warning("Chamber image stream ended for %s", stream_id)
  195. break
  196. # Save frame to buffer for photo capture and track timestamp
  197. if printer_id is not None:
  198. _last_frames[printer_id] = frame
  199. _last_frame_times[printer_id] = time.time()
  200. # Rate limiting - skip frames if needed to maintain target FPS
  201. current_time = asyncio.get_event_loop().time()
  202. if current_time - last_frame_time < frame_interval:
  203. continue
  204. last_frame_time = current_time
  205. # Yield frame in MJPEG format
  206. yield (
  207. b"--frame\r\n"
  208. b"Content-Type: image/jpeg\r\n"
  209. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  210. b"\r\n" + frame + b"\r\n"
  211. )
  212. except asyncio.CancelledError:
  213. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  214. except GeneratorExit:
  215. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  216. except Exception as e:
  217. logger.exception("Chamber image stream error: %s", e)
  218. finally:
  219. # Remove from active streams and disconnect events
  220. if stream_id:
  221. _active_chamber_streams.pop(stream_id, None)
  222. _disconnect_events.pop(stream_id, None)
  223. _stream_last_frame_times.pop(stream_id, None)
  224. # Clean up frame buffer and timestamps
  225. _release_printer_frame_state(printer_id)
  226. # Close the connection
  227. try:
  228. writer.close()
  229. await writer.wait_closed()
  230. except OSError:
  231. pass # Connection already closed or broken; cleanup is best-effort
  232. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  233. def _new_fanout_stream_id(printer_id: int) -> str:
  234. """Registry key for one fan-out stream INSTANCE, not for the printer.
  235. A plain ``f"{printer_id}-fanout"`` meant every successive stream for a
  236. printer shared one key, so a departing generator's cleanup removed the entry
  237. its successor had just registered. The external-camera path already carries a
  238. per-instance suffix for exactly this reason (#2675); this gives the fan-out
  239. path the same property.
  240. The ``f"{printer_id}-"`` prefix is load-bearing — ``is_stream_active``,
  241. ``stop_camera_stream`` and ``/camera/status`` all find a printer's streams by
  242. scanning for it — so the suffix goes on the end.
  243. """
  244. return f"{printer_id}-fanout-{uuid.uuid4().hex[:8]}"
  245. def live_frame_for_capture(printer_id: int) -> tuple[bool, bytes | None]:
  246. """Should a one-shot capture stand down for the live view, and to what frame?
  247. Returns ``(defer, frame)``. ``defer`` True means DO NOT open a capture of
  248. your own: use ``frame`` when it isn't None, and otherwise skip this attempt
  249. rather than competing.
  250. Both camera kinds allow exactly one reader — Bambu firmware permits one
  251. connection, and a USB camera permits one V4L2 handle — so a capture that
  252. races the live view doesn't degrade, it fails outright. #2707 measured 0 of
  253. 87 and 0 of 105 layer-timelapse captures on prints watched throughout, and
  254. finish photos going out with no image attached.
  255. Skipping when the buffer is momentarily empty (stream starting, mid-
  256. reconnect) rather than falling through to a capture is the #1348 rule:
  257. opening a competing handle kicks the viewer off, which is a worse outcome
  258. than missing one frame.
  259. """
  260. if not is_stream_active(printer_id):
  261. return False, None
  262. return True, _last_frames.get(printer_id)
  263. def _release_printer_frame_state(printer_id: int | None) -> None:
  264. """Drop a printer's buffered frame and timings — unless a stream still owns them.
  265. These three dicts are keyed by printer, not by stream, so a departing
  266. generator must not clear them while a newer stream for the same printer is
  267. running. That used to happen routinely: stream ids were per-printer, so a
  268. predecessor's cleanup wiped its successor's state, leaving
  269. ``is_stream_active()`` False with a viewer attached (which is exactly what
  270. the #1348 / #1271 guards read before deciding whether it is safe to open a
  271. second camera connection), the janitor free to reap the live ffmpeg as an
  272. orphan, and snapshots without a frame to reuse.
  273. Call this AFTER removing the departing stream's own key, so the check
  274. reports on other streams rather than on the caller.
  275. """
  276. if printer_id is None or is_stream_active(printer_id):
  277. return
  278. _last_frames.pop(printer_id, None)
  279. _last_frame_times.pop(printer_id, None)
  280. _stream_start_times.pop(printer_id, None)
  281. async def _drain_pipe(reader) -> None:
  282. """Read a subprocess pipe to EOF and discard, so it can never block.
  283. Best-effort by design: any read failure means we cannot drain further, and
  284. the caller is tearing the process down regardless.
  285. """
  286. if reader is None:
  287. return
  288. try:
  289. while await reader.read(65536):
  290. pass
  291. except asyncio.CancelledError:
  292. raise
  293. except Exception: # noqa: BLE001 — teardown must not fail on a dying pipe
  294. return
  295. async def _terminate_ffmpeg(process: asyncio.subprocess.Process, stream_id: str | None = None) -> None:
  296. """Terminate an ffmpeg process gracefully, then kill if needed.
  297. Drains stdout/stderr throughout, which is load-bearing rather than hygiene.
  298. ffmpeg is spawned with both as pipes, and every caller of this has already
  299. stopped reading stdout — so by the time we get here ffmpeg is typically
  300. blocked in write() on a full 64 KiB pipe. Two things then go wrong:
  301. * SIGTERM cannot be acted on. ffmpeg's handler only sets a flag that its
  302. main loop polls, and a loop blocked in write() never reaches the check,
  303. so the whole grace period is dead time.
  304. * SIGKILL does kill it, but wait() cannot observe that. asyncio resolves
  305. Process.wait()'s waiter through BaseSubprocessTransport._try_finish(),
  306. which requires every pipe transport to report disconnected; paused,
  307. unread pipes never reach EOF, so wait() blocks with returncode already
  308. set. That is what made the "did not exit within Ns of SIGKILL" error
  309. fire on every single camera close, and unbounded it was the 12-hour
  310. hang in #2580.
  311. Draining fixes both: SIGTERM becomes actionable and the exit observable.
  312. Measured on an H2D: 4.0s of dead time per close before, ~0.15s after —
  313. which matters because the printer allows exactly one camera connection,
  314. so every one of those seconds was a connection nobody could use.
  315. Discarding what we drain is deliberate. The stream loop already reads
  316. stderr on its error paths (_read_ffmpeg_stderr), and it does so before
  317. calling this, so nothing diagnostic is lost.
  318. """
  319. if process.returncode is not None:
  320. _spawned_ffmpeg_pids.pop(process.pid, None)
  321. return # Already dead
  322. drainers = [asyncio.create_task(_drain_pipe(process.stdout))]
  323. # A streaming ffmpeg's stderr already has a reader (_FfmpegStderrTail), and
  324. # it keeps draining right through teardown, which is all we need here. Adding
  325. # a second reader would race it — asyncio rejects concurrent reads on one
  326. # StreamReader — so only drain stderr when nobody else owns it.
  327. if process.pid not in _stderr_tails:
  328. drainers.append(asyncio.create_task(_drain_pipe(process.stderr)))
  329. try:
  330. process.terminate()
  331. try:
  332. await asyncio.wait_for(process.wait(), timeout=_FFMPEG_TERM_TIMEOUT)
  333. except TimeoutError:
  334. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  335. process.kill()
  336. try:
  337. await asyncio.wait_for(process.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  338. except TimeoutError:
  339. # Do NOT keep waiting (#2580): the caller is the stream
  340. # generator, and blocking here pins the fan-out pump forever.
  341. # The orphan janitor reaps the process later. With the pipes
  342. # drained this should be unreachable — see _FFMPEG_KILL_TIMEOUT.
  343. logger.error(
  344. "ffmpeg did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  345. _FFMPEG_KILL_TIMEOUT,
  346. stream_id,
  347. )
  348. except ProcessLookupError:
  349. pass # Already dead
  350. except OSError as e:
  351. logger.warning("Error terminating ffmpeg: %s", e)
  352. finally:
  353. for drainer in drainers:
  354. drainer.cancel()
  355. await asyncio.gather(*drainers, return_exceptions=True)
  356. _spawned_ffmpeg_pids.pop(process.pid, None)
  357. # The banner-stripping summariser moved to backend.app.utils.ffmpeg_output so
  358. # the seven other places that log ffmpeg stderr could stop truncating it from
  359. # the front (#2968). Imported under the private name this module has always
  360. # used: _FfmpegStderrTail and the tests both reach for it by that name.
  361. _summarize_ffmpeg_stderr = summarize_ffmpeg_stderr
  362. class _FfmpegStderrTail:
  363. """Owns a long-lived ffmpeg's stderr: drains it continuously, keeps the tail.
  364. Reading stderr only when something has already gone wrong leaves a pipe
  365. nobody reads for the whole life of the stream. ffmpeg writes its banner, the
  366. input analysis and then a progress line at a steady rate, so a 64 KiB pipe
  367. fills eventually and ffmpeg blocks writing to it — at which point it stops
  368. producing frames, the stream's own read timeout fires, and the log says
  369. "RTSP read timeout" with no hint that we starved it ourselves.
  370. How long that takes is unmeasured and may be a long time: one H2D upstream
  371. ran 21m36s continuously without stalling, so this is a bounded resource
  372. being treated as unbounded rather than an observed failure. Draining removes
  373. the ceiling either way, and the tail is *better* diagnostic material than
  374. the old on-demand read: it holds ffmpeg's most recent output at the moment
  375. things went wrong, where reading the buffered pipe returned whatever was
  376. printed first (usually the startup banner, which the summariser then strips).
  377. Registers itself in ``_stderr_tails`` so the two other readers of this pipe
  378. can defer to it — asyncio raises if two coroutines read one StreamReader
  379. concurrently. See ``_read_ffmpeg_stderr`` and ``_terminate_ffmpeg``.
  380. """
  381. def __init__(self, process: asyncio.subprocess.Process) -> None:
  382. self._process = process
  383. self._buffer = bytearray()
  384. self._task: asyncio.Task | None = None
  385. if process.stderr is None:
  386. return
  387. self._task = asyncio.create_task(self._pump())
  388. _stderr_tails[process.pid] = self
  389. async def _pump(self) -> None:
  390. reader = self._process.stderr
  391. try:
  392. while True:
  393. chunk = await reader.read(8192)
  394. if not chunk:
  395. return # EOF — ffmpeg has exited
  396. self._buffer.extend(chunk)
  397. excess = len(self._buffer) - _FFMPEG_STDERR_TAIL_BYTES
  398. if excess > 0:
  399. del self._buffer[:excess]
  400. except asyncio.CancelledError:
  401. raise
  402. except Exception: # noqa: BLE001 — a broken pipe just ends the tail
  403. return
  404. def text(self) -> str | None:
  405. """The retained tail, summarised. None when nothing was captured.
  406. Goes through _summarize_ffmpeg_stderr like every other stderr log in
  407. this module: ffmpeg echoes its input URL, which carries the access code.
  408. """
  409. if not self._buffer:
  410. return None
  411. return _summarize_ffmpeg_stderr(self._buffer.decode(errors="replace")) or None
  412. async def aclose(self) -> None:
  413. """Stop draining and release ownership of the pipe. Idempotent.
  414. Awaits the cancelled pump rather than firing and forgetting, so the task
  415. is finished before the caller moves on — an abandoned pending task
  416. becomes an "unraisable exception" warning at an arbitrary later point,
  417. usually during interpreter or loop teardown.
  418. """
  419. task, self._task = self._task, None
  420. if _stderr_tails.get(self._process.pid) is self:
  421. del _stderr_tails[self._process.pid]
  422. if task is None:
  423. return
  424. task.cancel()
  425. with contextlib.suppress(asyncio.CancelledError):
  426. await task
  427. async def _read_ffmpeg_stderr(process: asyncio.subprocess.Process) -> str | None:
  428. """Read whatever ffmpeg has written to stderr so far (best-effort).
  429. ffmpeg's stderr must be drained *incrementally*. A stalled-but-still-alive
  430. ffmpeg — the typical P2S RTSP failure, where it connects but never produces
  431. a frame — never closes stderr, so a plain ``stderr.read()`` (read-to-EOF)
  432. blocks until the wait_for timeout and returns nothing, discarding the
  433. banner + stream-analysis lines ffmpeg already printed. Reading in bounded
  434. chunks returns the buffered output promptly whether or not ffmpeg has
  435. exited. Returns the content with ffmpeg's boilerplate banner stripped.
  436. When a _FfmpegStderrTail owns this process's stderr — every streaming
  437. ffmpeg — its retained tail is returned instead. Reading the pipe here as
  438. well would race that collector, and asyncio refuses two concurrent readers
  439. on one StreamReader outright.
  440. """
  441. if not process:
  442. return None
  443. tail = _stderr_tails.get(getattr(process, "pid", None))
  444. if tail is not None:
  445. return tail.text()
  446. if not process.stderr:
  447. return None
  448. chunks: list[bytes] = []
  449. total = 0
  450. cap = 65536
  451. try:
  452. while total < cap:
  453. chunk = await asyncio.wait_for(process.stderr.read(8192), timeout=2.0)
  454. if not chunk:
  455. break # EOF — ffmpeg has exited
  456. chunks.append(chunk)
  457. total += len(chunk)
  458. except Exception:
  459. # Timed out waiting for more data — ffmpeg is alive but quiet now.
  460. # Fall through and return whatever it already printed.
  461. pass
  462. if not chunks:
  463. return None
  464. return _summarize_ffmpeg_stderr(b"".join(chunks).decode(errors="replace")) or None
  465. async def generate_rtsp_mjpeg_stream(
  466. ip_address: str,
  467. access_code: str,
  468. model: str | None,
  469. fps: int = 10,
  470. stream_id: str | None = None,
  471. disconnect_event: asyncio.Event | None = None,
  472. printer_id: int | None = None,
  473. ) -> AsyncGenerator[bytes, None]:
  474. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  475. This is for X1/H2/P2 models that support RTSP streaming.
  476. Auto-reconnects when the printer drops the RTSP session (common on P2S).
  477. Per-model knobs (probesize, analyzeduration, reconnect cadence) come from
  478. :func:`camera_profiles.get_camera_profile` so quirky firmwares can be
  479. handled by adding a profile entry rather than tuning a global constant.
  480. """
  481. ffmpeg = get_ffmpeg_path()
  482. if not ffmpeg:
  483. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  484. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  485. return
  486. profile = get_camera_profile(model)
  487. port = get_camera_port(model)
  488. # Use a local TLS proxy so Python's OpenSSL handles TLS instead of
  489. # ffmpeg's GnuTLS. This fixes P2S (and potentially other models)
  490. # dropping the RTSP session after a few seconds due to GnuTLS's
  491. # hardened Debian defaults rejecting TLS renegotiation.
  492. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  493. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  494. # ffmpeg command to output MJPEG stream to stdout
  495. cmd = [
  496. ffmpeg,
  497. "-rtsp_transport",
  498. "tcp",
  499. "-rtsp_flags",
  500. "prefer_tcp",
  501. # Socket I/O timeout name varies by ffmpeg version (#1504); see
  502. # rtsp_socket_timeout_flag(). The 30s value is microseconds for
  503. # both names.
  504. f"-{rtsp_socket_timeout_flag()}",
  505. "30000000",
  506. "-buffer_size",
  507. "1024000", # 1MB buffer
  508. "-max_delay",
  509. "500000", # 0.5 seconds max delay
  510. "-probesize",
  511. str(profile.probesize),
  512. "-analyzeduration",
  513. str(profile.analyzeduration),
  514. "-fflags",
  515. "nobuffer", # Reduce internal buffering
  516. "-flags",
  517. "low_delay", # Minimize decode latency
  518. *profile.extra_ffmpeg_input_args,
  519. "-i",
  520. camera_url,
  521. "-f",
  522. "mjpeg",
  523. "-q:v",
  524. "5",
  525. "-r",
  526. str(fps),
  527. "-an", # No audio
  528. "-", # Output to stdout
  529. ]
  530. # Register disconnect event so stop endpoint can signal us
  531. if stream_id and disconnect_event:
  532. _disconnect_events[stream_id] = disconnect_event
  533. logger.info(
  534. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s, probesize=%s, analyzeduration=%s)",
  535. ip_address,
  536. stream_id,
  537. model,
  538. fps,
  539. profile.probesize,
  540. profile.analyzeduration,
  541. )
  542. # Log the full argv so a support bundle shows the actual ffmpeg flags
  543. # (probesize, analyzeduration, transport, ...). Only camera_url carries a
  544. # secret (the access code), so redact just that one element.
  545. _redacted_cmd = ["rtsp://<redacted>/streaming/live/1" if a == camera_url else a for a in cmd]
  546. logger.debug("ffmpeg command: %s", " ".join(_redacted_cmd))
  547. # On Windows, spawn ffmpeg in its own process group so that
  548. # terminate() doesn't broadcast CTRL_C_EVENT to uvicorn (#605).
  549. spawn_kwargs: dict = {}
  550. if sys.platform == "win32":
  551. spawn_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  552. jpeg_start = b"\xff\xd8"
  553. jpeg_end = b"\xff\xd9"
  554. reconnect_count = 0
  555. process = None
  556. stderr_tail: _FfmpegStderrTail | None = None
  557. got_any_frames = False
  558. # Across sessions (#3218): the frame a session froze on, and whether the
  559. # next session showed the very same picture -- a still scene, not a
  560. # frozen ffmpeg.
  561. frozen_crc: int | None = None
  562. still_scene = False
  563. try:
  564. while reconnect_count <= profile.rtsp_reconnect_max:
  565. # Check for client disconnect before (re)connecting
  566. if disconnect_event and disconnect_event.is_set():
  567. break
  568. if reconnect_count > 0:
  569. logger.info(
  570. "RTSP reconnecting (%d/%d) for %s (stream_id=%s)",
  571. reconnect_count,
  572. profile.rtsp_reconnect_max,
  573. ip_address,
  574. stream_id,
  575. )
  576. # Fast after a session that delivered frames (reconnect_count
  577. # is 1 then), backing off while the printer keeps refusing.
  578. await asyncio.sleep(
  579. min(
  580. profile.rtsp_reconnect_delay * 2 ** (reconnect_count - 1),
  581. profile.rtsp_reconnect_backoff_max,
  582. )
  583. )
  584. if disconnect_event and disconnect_event.is_set():
  585. break
  586. # Spawn ffmpeg
  587. process = await asyncio.create_subprocess_exec(
  588. *cmd,
  589. stdout=asyncio.subprocess.PIPE,
  590. stderr=asyncio.subprocess.PIPE,
  591. **spawn_kwargs,
  592. )
  593. if stream_id:
  594. _active_streams[stream_id] = process
  595. import time as _time
  596. _spawned_ffmpeg_pids[process.pid] = _time.time()
  597. # Brief check for immediate startup failures
  598. await asyncio.sleep(0.1)
  599. if process.returncode is not None:
  600. stderr = await process.stderr.read()
  601. stderr_text = _summarize_ffmpeg_stderr(stderr.decode(errors="replace"))
  602. logger.error("ffmpeg failed immediately (attempt %d): %s", reconnect_count + 1, stderr_text)
  603. _spawned_ffmpeg_pids.pop(process.pid, None)
  604. if not got_any_frames and reconnect_count == 0:
  605. # First attempt failed immediately — camera is likely unreachable
  606. yield (
  607. b"--frame\r\n"
  608. b"Content-Type: text/plain\r\n\r\n"
  609. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  610. )
  611. return
  612. reconnect_count += 1
  613. continue
  614. # Take ownership of stderr for the life of this process. Started
  615. # only after the immediate-failure check above, which reads the pipe
  616. # directly (correct there: the process is already dead, so
  617. # read-to-EOF returns at once and cannot be raced by a collector).
  618. # Nothing is lost by starting late — the banner ffmpeg printed in the
  619. # meantime is still sitting in the pipe.
  620. stderr_tail = _FfmpegStderrTail(process)
  621. # Read JPEG frames from ffmpeg stdout
  622. buffer = b""
  623. stream_ended = False
  624. client_gone = False
  625. session_got_frames = False
  626. # A frame that differs from the one before, not any frame, is what
  627. # shows the picture is live: ffmpeg can repeat its last one
  628. # forever (#3218).
  629. last_frame_crc: int | None = None
  630. last_change = time.time()
  631. identical_frames = 0
  632. frozen = False
  633. while True:
  634. if disconnect_event and disconnect_event.is_set():
  635. client_gone = True
  636. break
  637. try:
  638. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  639. if not chunk:
  640. # ffmpeg exited — log stderr and break to reconnect
  641. stderr_text = await _read_ffmpeg_stderr(process)
  642. if stderr_text:
  643. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  644. logger.warning("RTSP stream ended for %s (stream_id=%s), will reconnect", ip_address, stream_id)
  645. stream_ended = True
  646. break
  647. buffer += chunk
  648. # Extract complete JPEG frames from buffer
  649. while True:
  650. start_idx = buffer.find(jpeg_start)
  651. if start_idx == -1:
  652. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  653. break
  654. if start_idx > 0:
  655. buffer = buffer[start_idx:]
  656. end_idx = buffer.find(jpeg_end, 2)
  657. if end_idx == -1:
  658. break
  659. frame = buffer[: end_idx + 2]
  660. buffer = buffer[end_idx + 2 :]
  661. got_any_frames = True
  662. session_got_frames = True
  663. now = time.time()
  664. frame_crc = zlib.crc32(frame)
  665. if last_frame_crc is None:
  666. # First frame of this session. The same frame the
  667. # last session froze on means the camera really
  668. # shows that picture (see _RTSP_STILL_RECHECK_SECONDS).
  669. still_scene = frozen_crc is not None and frame_crc == frozen_crc
  670. if still_scene:
  671. logger.info(
  672. "RTSP picture unchanged after restart for %s (stream_id=%s): "
  673. "treating it as a still scene, re-checking every %.0fs",
  674. ip_address,
  675. stream_id,
  676. _RTSP_STILL_RECHECK_SECONDS,
  677. )
  678. last_frame_crc = frame_crc
  679. last_change = now
  680. elif frame_crc != last_frame_crc:
  681. last_frame_crc = frame_crc
  682. last_change = now
  683. identical_frames = 0
  684. # The picture moves: back to the normal check.
  685. still_scene = False
  686. frozen_crc = None
  687. else:
  688. identical_frames += 1
  689. if printer_id is not None:
  690. _last_frames[printer_id] = frame
  691. _last_frame_times[printer_id] = now
  692. if stream_id:
  693. _stream_last_frame_times[stream_id] = now
  694. yield (
  695. b"--frame\r\n"
  696. b"Content-Type: image/jpeg\r\n"
  697. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  698. b"\r\n" + frame + b"\r\n"
  699. )
  700. if now - last_change > (_RTSP_STILL_RECHECK_SECONDS if still_scene else _RTSP_FROZEN_SECONDS):
  701. frozen = True
  702. frozen_crc = last_frame_crc
  703. break
  704. if frozen:
  705. if still_scene:
  706. logger.info(
  707. "RTSP still-scene re-check for %s (stream_id=%s), restarting ffmpeg",
  708. ip_address,
  709. stream_id,
  710. )
  711. else:
  712. stderr_text = await _read_ffmpeg_stderr(process)
  713. if stderr_text:
  714. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  715. logger.warning(
  716. "RTSP output frozen for %s (stream_id=%s): %d identical frames over %.0fs, "
  717. "restarting ffmpeg",
  718. ip_address,
  719. stream_id,
  720. identical_frames,
  721. time.time() - last_change,
  722. )
  723. stream_ended = True
  724. break
  725. except TimeoutError:
  726. stderr_text = await _read_ffmpeg_stderr(process)
  727. if stderr_text:
  728. logger.warning("ffmpeg stderr on timeout: %s", stderr_text)
  729. logger.warning("RTSP read timeout for %s (stream_id=%s)", ip_address, stream_id)
  730. stream_ended = True
  731. break
  732. except asyncio.CancelledError:
  733. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  734. client_gone = True
  735. break
  736. except GeneratorExit:
  737. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  738. client_gone = True
  739. break
  740. # Clean up this ffmpeg process before reconnecting or exiting
  741. await _terminate_ffmpeg(process, stream_id)
  742. # Released after teardown, not before: _terminate_ffmpeg deliberately
  743. # leaves stderr to this collector, which has to keep draining while
  744. # the process is stopped or wait() can't observe the exit.
  745. if stderr_tail is not None:
  746. await stderr_tail.aclose()
  747. stderr_tail = None
  748. process = None
  749. if client_gone:
  750. break
  751. # Check if stream was explicitly stopped (e.g., by stop endpoint)
  752. if stream_id and stream_id not in _active_streams:
  753. logger.info("Stream %s removed from active streams, stopping reconnect", stream_id)
  754. break
  755. if stream_ended:
  756. # The budget is for failures in a row. A session that
  757. # delivered video was a success, however it ended -- a stock
  758. # X1C ends every session after about a minute, which under a
  759. # lifetime count stopped the live view for good after half an
  760. # hour.
  761. if session_got_frames:
  762. reconnect_count = 0
  763. reconnect_count += 1
  764. continue
  765. # Normal exit (shouldn't reach here, but be safe)
  766. break
  767. if reconnect_count > profile.rtsp_reconnect_max:
  768. logger.error(
  769. "RTSP max consecutive reconnects (%d) reached for %s (stream_id=%s)",
  770. profile.rtsp_reconnect_max,
  771. ip_address,
  772. stream_id,
  773. )
  774. except FileNotFoundError:
  775. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  776. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  777. except asyncio.CancelledError:
  778. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  779. except GeneratorExit:
  780. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  781. except Exception as e:
  782. logger.exception("Camera stream error: %s", e)
  783. finally:
  784. # Remove from active streams and disconnect events
  785. if stream_id:
  786. _active_streams.pop(stream_id, None)
  787. _disconnect_events.pop(stream_id, None)
  788. _stream_last_frame_times.pop(stream_id, None)
  789. # Clean up frame buffer and timestamps
  790. _release_printer_frame_state(printer_id)
  791. if process:
  792. await _terminate_ffmpeg(process, stream_id)
  793. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  794. # Same order as in the loop: terminate first, then release stderr.
  795. if stderr_tail is not None:
  796. await stderr_tail.aclose()
  797. # Shut down the TLS proxy
  798. await close_tls_proxy(proxy_server)
  799. @router.post("/camera/stream-token")
  800. async def create_stream_token(
  801. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  802. ):
  803. """Create a reusable token for camera stream/snapshot access.
  804. Returns a token valid for 60 minutes that can be appended as ?token=xxx
  805. to camera stream/snapshot URLs loaded via <img> tags.
  806. """
  807. return {"token": await create_camera_stream_token()}
  808. @router.get("/{printer_id}/camera/stream")
  809. async def camera_stream(
  810. printer_id: int,
  811. request: Request,
  812. fps: int = 10,
  813. _: None = RequireCameraStreamTokenIfAuthEnabled,
  814. ):
  815. """Stream live video from printer camera as MJPEG.
  816. This endpoint returns a multipart MJPEG stream that can be used directly
  817. in an <img> tag or video player.
  818. Requires a stream token query param (?token=xxx) when auth is enabled.
  819. Uses external camera if configured, otherwise uses built-in camera:
  820. - External: MJPEG, RTSP, or HTTP snapshot
  821. - A1/P1: Chamber image protocol (port 6000)
  822. - X1/H2/P2: RTSP via ffmpeg (port 322)
  823. Args:
  824. printer_id: Printer ID
  825. fps: Target frames per second (default: 10, max: 30)
  826. """
  827. # Fetch the printer in a short-lived session so the pooled DB connection is
  828. # released BEFORE we start streaming. A live MJPEG stream runs for as long
  829. # as the browser tab stays open (potentially hours); holding the
  830. # Depends(get_db) session across it pinned one pooled connection per open
  831. # camera tab per printer — a top contributor to pool exhaustion on large
  832. # farms (issue #2572). expire_on_commit=False keeps the printer's already-
  833. # loaded columns readable after the session closes, and everything below
  834. # reads only scalar attributes (model, ip_address, access_code,
  835. # external_camera_*) — no lazy loads.
  836. #
  837. # Reference async_session via the module (not a top-level import binding) so
  838. # the session maker is looked up at call time — that keeps it in sync with
  839. # reinitialize_database() and lets the test harness's patch of
  840. # backend.app.core.database.async_session take effect here.
  841. async with database.async_session() as db:
  842. printer = await get_printer_or_404(printer_id, db)
  843. # Check for external camera first
  844. if printer.external_camera_enabled and printer.external_camera_url:
  845. # NB: no `import time` / `import uuid` here, and don't reintroduce them.
  846. # A local import anywhere in this function makes the name function-local
  847. # for the WHOLE function, so the RTSP/chamber path below — which never
  848. # executes this branch — would raise UnboundLocalError on any printer
  849. # without an external camera. Both are imported at module level.
  850. from backend.app.services.external_camera import generate_mjpeg_stream
  851. # Limit external camera FPS to reduce browser load
  852. fps = min(max(fps, 1), 15)
  853. logger.info(
  854. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  855. )
  856. # Register the stream into the SAME registries the RTSP/chamber paths use
  857. # (#2675) so `/camera/stop` and cleanup_orphaned_streams can find and kill
  858. # a leaked ffmpeg holding a USB device open. Before this, external streams
  859. # only tracked _active_external_streams and were structurally invisible to
  860. # both the stop endpoint and the janitor. The stream_id keeps the
  861. # `{printer_id}-` prefix both scanners key on, plus a unique suffix so two
  862. # concurrent viewers of one printer don't clobber each other's entry.
  863. stream_id = f"{printer_id}-ext-{uuid.uuid4().hex[:8]}"
  864. stop_event = asyncio.Event()
  865. _disconnect_events[stream_id] = stop_event
  866. # Track stream start
  867. _stream_start_times[printer_id] = time.time()
  868. _active_external_streams.add(printer_id)
  869. # Mutable holder so the wrapper's finally can unregister whatever process
  870. # is currently registered (the RTSP path may respawn across reconnects).
  871. current_proc: dict[str, asyncio.subprocess.Process] = {}
  872. def _register_external_process(proc: asyncio.subprocess.Process) -> None:
  873. prev = current_proc.get("proc")
  874. if prev is not None and prev.pid != proc.pid:
  875. _spawned_ffmpeg_pids.pop(prev.pid, None)
  876. current_proc["proc"] = proc
  877. _active_streams[stream_id] = proc
  878. _spawned_ffmpeg_pids[proc.pid] = time.time()
  879. _stream_last_frame_times[stream_id] = time.time()
  880. def _publish_external_frame(frame: bytes) -> None:
  881. """Make the live frame reusable by one-shot consumers (#2707).
  882. Only the built-in camera paths populated _last_frames, so every
  883. external-camera consumer — layer timelapse, finish photo, Obico,
  884. plate check — found an empty buffer and opened its own handle on a
  885. device that allows exactly one reader, which simply failed while a
  886. viewer was attached. Raw frame, not the multipart-wrapped chunk the
  887. generator yields, because that is what those consumers expect.
  888. """
  889. _last_frames[printer_id] = frame
  890. async def external_stream_wrapper():
  891. """Wrap external stream to track start/stop and update frame times."""
  892. try:
  893. # Chamber light while the viewer watches (#1655).
  894. async with camera_light(printer, wait=False):
  895. async for frame in generate_mjpeg_stream(
  896. printer.external_camera_url,
  897. printer.external_camera_type,
  898. fps,
  899. on_process=_register_external_process,
  900. on_frame=_publish_external_frame,
  901. stop_event=stop_event,
  902. ):
  903. # generate_mjpeg_stream already handles rate limiting;
  904. # track frame times (per-printer + per-stream) for stall detection
  905. now = time.time()
  906. _last_frame_times[printer_id] = now
  907. _stream_last_frame_times[stream_id] = now
  908. yield frame
  909. finally:
  910. # Best-effort unregister. If an abrupt disconnect skips this
  911. # finally, the registry entries persist — which is exactly what
  912. # lets the stop endpoint / janitor reap the leaked process.
  913. stop_event.set()
  914. proc = current_proc.get("proc")
  915. if proc is not None:
  916. _spawned_ffmpeg_pids.pop(proc.pid, None)
  917. _active_streams.pop(stream_id, None)
  918. _disconnect_events.pop(stream_id, None)
  919. _stream_last_frame_times.pop(stream_id, None)
  920. _active_external_streams.discard(printer_id)
  921. # Now that this path publishes a buffered frame, it has to
  922. # retract it too — ownership-checked, so a concurrent viewer of
  923. # the same printer keeps its own. Also clears the per-printer
  924. # timings this path used to leave behind.
  925. _release_printer_frame_state(printer_id)
  926. logger.info("External camera stream ended for printer %s", printer_id)
  927. return StreamingResponse(
  928. external_stream_wrapper(),
  929. media_type="multipart/x-mixed-replace; boundary=frame",
  930. headers={
  931. "Cache-Control": "no-cache, no-store, must-revalidate",
  932. "Pragma": "no-cache",
  933. "Expires": "0",
  934. },
  935. )
  936. # Validate FPS - A1/P1 models max out at ~5 FPS
  937. if is_chamber_image_model(printer.model):
  938. fps = min(max(fps, 1), 5)
  939. else:
  940. fps = min(max(fps, 1), 30)
  941. # Choose the appropriate stream generator based on model
  942. if is_chamber_image_model(printer.model):
  943. stream_generator = generate_chamber_mjpeg_stream
  944. logger.info("Using chamber image protocol for %s", printer.model)
  945. else:
  946. stream_generator = generate_rtsp_mjpeg_stream
  947. logger.info("Using RTSP protocol for %s", printer.model)
  948. # Track stream start time. Set only if absent so the value reflects when
  949. # the SHARED upstream first started streaming, not when each new viewer
  950. # attached — otherwise /camera/status would report stream_uptime jumping
  951. # backward whenever a second viewer joins. The upstream generator's
  952. # finally clears this entry when the upstream actually ends.
  953. _stream_start_times.setdefault(printer_id, time.time())
  954. # Fan-out broadcaster (#1089): one upstream connection per printer, shared
  955. # across all viewers. Most Bambu printers only allow a single concurrent
  956. # camera connection, so opening the same printer in two tabs would
  957. # otherwise kick the first viewer off. The broadcaster owns the single
  958. # upstream and the per-viewer disconnect handling.
  959. #
  960. # Note: the upstream's fps is fixed by the first viewer who creates the
  961. # broadcaster. Concurrent viewers share that rate; new viewers after
  962. # teardown create a fresh broadcaster at their requested fps.
  963. fanout_key = f"printer-{printer_id}"
  964. upstream_stream_id = _new_fanout_stream_id(printer_id)
  965. def _factory(disconnect_event: asyncio.Event):
  966. # Re-bind locals into the closure so the async generator below sees
  967. # them — disconnect_event is owned by the broadcaster and signalled
  968. # when the last subscriber leaves (after the grace window).
  969. return stream_generator(
  970. ip_address=printer.ip_address,
  971. access_code=printer.access_code,
  972. model=printer.model,
  973. fps=fps,
  974. stream_id=upstream_stream_id,
  975. disconnect_event=disconnect_event,
  976. printer_id=printer_id,
  977. )
  978. # Subscribe with a one-shot retry to close a tiny race: the grace-window
  979. # teardown can flip the broadcaster to `stopped=True` between the registry
  980. # lookup and our subscribe call. The retry forces the registry to mint a
  981. # fresh broadcaster (since the now-stopped one is replaced), and the second
  982. # subscribe is guaranteed to land on it before any teardown can fire.
  983. broadcaster: MjpegBroadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  984. try:
  985. queue = await broadcaster.subscribe()
  986. except RuntimeError:
  987. broadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  988. queue = await broadcaster.subscribe()
  989. logger.info(
  990. "Camera viewer attached to %s (subscribers=%d)",
  991. fanout_key,
  992. broadcaster.subscriber_count,
  993. )
  994. async def _is_disconnected() -> bool:
  995. try:
  996. return await request.is_disconnected()
  997. except Exception:
  998. # Older starlette/uvicorn can raise during teardown — treat that
  999. # as "client gone" so the subscriber cleanly unsubscribes.
  1000. return True
  1001. def _log_detach(remaining: int) -> None:
  1002. logger.info("Camera viewer detached from %s (subscribers=%d)", fanout_key, remaining)
  1003. async def _generate():
  1004. # Chamber light while this viewer watches (#1655). Held per viewer, so
  1005. # it goes off once the last one leaves.
  1006. async with camera_light(printer, wait=False):
  1007. async for chunk in iter_subscriber(
  1008. broadcaster,
  1009. queue,
  1010. is_disconnected=_is_disconnected,
  1011. on_unsubscribe=_log_detach,
  1012. ):
  1013. yield chunk
  1014. return StreamingResponse(
  1015. _generate(),
  1016. media_type="multipart/x-mixed-replace; boundary=frame",
  1017. headers={
  1018. "Cache-Control": "no-cache, no-store, must-revalidate",
  1019. "Pragma": "no-cache",
  1020. "Expires": "0",
  1021. },
  1022. )
  1023. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  1024. async def stop_camera_stream(
  1025. printer_id: int,
  1026. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1027. ):
  1028. """Stop active camera streams for a printer.
  1029. Called by the frontend on viewer unmount (cam-wall tile, embedded viewer,
  1030. popup window). Accepts both GET and POST (POST for sendBeacon compatibility).
  1031. Reference-count guard: every viewer of a printer subscribes to the same
  1032. fan-out broadcaster, so a force-shutdown triggered by ONE leaving viewer
  1033. used to kill the others' streams (cam-wall tile froze when a user opened
  1034. then closed the embedded viewer). If any subscriber is still attached,
  1035. skip the force-teardown — the broadcaster's natural grace-shutdown (5 s
  1036. after subscribers drop to 0) handles cleanup when the leaving viewer's
  1037. HTTP connection actually closes.
  1038. """
  1039. broadcaster_key = f"printer-{printer_id}"
  1040. remaining_subscribers = get_subscriber_count(broadcaster_key)
  1041. if remaining_subscribers >= 1:
  1042. logger.info(
  1043. "Skipping force-shutdown for printer %s: %d subscriber(s) still attached; "
  1044. "natural cleanup will tear down when last viewer disconnects",
  1045. printer_id,
  1046. remaining_subscribers,
  1047. )
  1048. return {"stopped": 0, "skipped": True}
  1049. stopped = 0
  1050. # Tear down the fan-out broadcaster first (#1089). This cleanly notifies
  1051. # all subscribed viewers and asks the upstream generator to stop
  1052. # reconnecting before we fall back to forcefully killing the process below.
  1053. if await shutdown_broadcaster(broadcaster_key):
  1054. logger.info("Shut down camera fan-out broadcaster for printer %s", printer_id)
  1055. # Stop ffmpeg/RTSP streams
  1056. to_remove = []
  1057. for stream_id, process in list(_active_streams.items()):
  1058. if stream_id.startswith(f"{printer_id}-"):
  1059. to_remove.append(stream_id)
  1060. # Signal the generator to stop reconnecting BEFORE killing the process
  1061. event = _disconnect_events.get(stream_id)
  1062. if event:
  1063. event.set()
  1064. if process.returncode is None:
  1065. # Shared helper, not an inline copy: it bounds the post-kill
  1066. # wait (#2580) — a killed-but-unreaped ffmpeg used to hang this
  1067. # request forever, exactly when the user hit Stop to recover a
  1068. # stuck stream.
  1069. await _terminate_ffmpeg(process, stream_id)
  1070. stopped += 1
  1071. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  1072. _spawned_ffmpeg_pids.pop(process.pid, None)
  1073. for stream_id in to_remove:
  1074. _active_streams.pop(stream_id, None)
  1075. _disconnect_events.pop(stream_id, None)
  1076. _stream_last_frame_times.pop(stream_id, None)
  1077. # Stop chamber image streams
  1078. to_remove_chamber = []
  1079. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  1080. if stream_id.startswith(f"{printer_id}-"):
  1081. to_remove_chamber.append(stream_id)
  1082. # Signal the generator to stop
  1083. event = _disconnect_events.get(stream_id)
  1084. if event:
  1085. event.set()
  1086. try:
  1087. writer.close()
  1088. stopped += 1
  1089. logger.info("Closed chamber image connection for stream %s", stream_id)
  1090. except OSError as e:
  1091. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  1092. for stream_id in to_remove_chamber:
  1093. _active_chamber_streams.pop(stream_id, None)
  1094. _disconnect_events.pop(stream_id, None)
  1095. _stream_last_frame_times.pop(stream_id, None)
  1096. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  1097. return {"stopped": stopped}
  1098. @router.get("/{printer_id}/camera/snapshot")
  1099. async def camera_snapshot(
  1100. printer_id: int,
  1101. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1102. ):
  1103. """Capture a single frame from the printer camera.
  1104. Returns a JPEG image.
  1105. Requires a stream token query param (?token=xxx) when auth is enabled.
  1106. """
  1107. # Fetch the printer in a short-lived session and release the pooled DB
  1108. # connection BEFORE the camera capture below (up to 15s, longer under a
  1109. # saturated FTP/camera pool). Holding a Depends(get_db) session across the
  1110. # grab pinned one connection per snapshot — and the cam wall polls this
  1111. # per tile every 8s — so overlapping captures could pile up connections on
  1112. # a large farm (issue #2572, sibling of the camera_stream fix). Everything
  1113. # below reads only already-loaded scalar columns (expire_on_commit=False).
  1114. async with database.async_session() as db:
  1115. printer = await get_printer_or_404(printer_id, db)
  1116. # Chamber light for the picture (#1655). Home Assistant and other
  1117. # automations take their pictures here.
  1118. async with camera_light(printer):
  1119. return await _snapshot_response(printer_id, printer)
  1120. async def _snapshot_response(printer_id: int, printer: Printer) -> Response:
  1121. """The capture behind ``camera_snapshot``."""
  1122. import tempfile
  1123. from pathlib import Path
  1124. # Check for external camera first
  1125. if printer.external_camera_enabled and printer.external_camera_url:
  1126. from backend.app.services.external_camera import capture_frame
  1127. frame_data = await capture_frame(
  1128. printer.external_camera_url,
  1129. printer.external_camera_type,
  1130. timeout=15,
  1131. snapshot_url=printer.external_camera_snapshot_url,
  1132. )
  1133. if not frame_data:
  1134. raise HTTPException(
  1135. status_code=503,
  1136. detail="Failed to capture frame from external camera.",
  1137. )
  1138. return Response(
  1139. content=frame_data,
  1140. media_type="image/jpeg",
  1141. headers={
  1142. "Cache-Control": "no-cache, no-store, must-revalidate",
  1143. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  1144. },
  1145. )
  1146. # Reuse the fan-out broadcaster's buffered frame when a viewer is already
  1147. # watching — avoids opening a second concurrent RTSP socket on printers
  1148. # that allow only one camera connection (e.g. X2D firmware 01.01.00.00;
  1149. # see #1271). Buffered frame is <1s old while a viewer is connected.
  1150. buffered = try_get_active_buffered_frame(printer_id)
  1151. if buffered:
  1152. return Response(
  1153. content=buffered,
  1154. media_type="image/jpeg",
  1155. headers={
  1156. "Cache-Control": "no-cache, no-store, must-revalidate",
  1157. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  1158. },
  1159. )
  1160. # Create temporary file for the snapshot (0600 so only the app user can read it)
  1161. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  1162. os.close(fd)
  1163. temp_path = Path(tmp_name)
  1164. temp_path.chmod(0o600)
  1165. try:
  1166. success = await capture_camera_frame(
  1167. ip_address=printer.ip_address,
  1168. access_code=printer.access_code,
  1169. model=printer.model,
  1170. output_path=temp_path,
  1171. timeout=15,
  1172. )
  1173. if not success:
  1174. raise HTTPException(
  1175. status_code=503,
  1176. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  1177. )
  1178. # Read and return the image
  1179. with open(temp_path, "rb") as f:
  1180. image_data = f.read()
  1181. return Response(
  1182. content=image_data,
  1183. media_type="image/jpeg",
  1184. headers={
  1185. "Cache-Control": "no-cache, no-store, must-revalidate",
  1186. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  1187. },
  1188. )
  1189. finally:
  1190. # Clean up temp file
  1191. if temp_path.exists():
  1192. temp_path.unlink()
  1193. @router.get("/{printer_id}/camera/test")
  1194. async def test_camera(
  1195. printer_id: int,
  1196. db: AsyncSession = Depends(get_db),
  1197. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1198. ):
  1199. """Test camera connection for a printer.
  1200. Returns success status and any error message.
  1201. """
  1202. printer = await get_printer_or_404(printer_id, db)
  1203. result = await test_camera_connection(
  1204. ip_address=printer.ip_address,
  1205. access_code=printer.access_code,
  1206. model=printer.model,
  1207. )
  1208. return result
  1209. @router.post("/{printer_id}/camera/diagnose")
  1210. async def diagnose_camera_route(
  1211. printer_id: int,
  1212. db: AsyncSession = Depends(get_db),
  1213. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1214. ):
  1215. """Run staged diagnostics for a printer's camera path.
  1216. Returns a structured result the frontend renders inline so users can
  1217. self-diagnose "connection lost" before opening a ticket. See
  1218. ``camera_diagnose`` for stage details and the live-stream shortcut.
  1219. """
  1220. import time
  1221. from backend.app.services.camera_diagnose import diagnose_camera
  1222. printer = await get_printer_or_404(printer_id, db)
  1223. # Look up live-stream evidence so the diagnostic can short-circuit
  1224. # instead of fighting a viewer for the printer's single camera slot.
  1225. has_live = is_stream_active(printer_id)
  1226. last_ts = _last_frame_times.get(printer_id) if has_live else None
  1227. live_age = (time.time() - last_ts) if (has_live and last_ts) else None
  1228. result = await diagnose_camera(
  1229. ip_address=printer.ip_address,
  1230. access_code=printer.access_code,
  1231. model=printer.model,
  1232. printer_id=printer_id,
  1233. has_live_stream=has_live,
  1234. live_frame_age_seconds=live_age,
  1235. )
  1236. return result.to_dict()
  1237. @router.get("/{printer_id}/camera/status")
  1238. async def camera_status(
  1239. printer_id: int,
  1240. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1241. ):
  1242. """Get the status of an active camera stream.
  1243. Returns whether a stream is active and when the last frame was received.
  1244. Used by the frontend to detect stalled streams and auto-reconnect.
  1245. """
  1246. import time
  1247. # Check if there's an active stream for this printer
  1248. has_active_stream = False
  1249. # Check external camera streams
  1250. if printer_id in _active_external_streams:
  1251. has_active_stream = True
  1252. # Check ffmpeg/RTSP streams
  1253. if not has_active_stream:
  1254. for stream_id in _active_streams:
  1255. if stream_id.startswith(f"{printer_id}-"):
  1256. process = _active_streams[stream_id]
  1257. if process.returncode is None:
  1258. has_active_stream = True
  1259. break
  1260. # Check chamber image streams
  1261. if not has_active_stream:
  1262. for stream_id in _active_chamber_streams:
  1263. if stream_id.startswith(f"{printer_id}-"):
  1264. has_active_stream = True
  1265. break
  1266. # Get timing information
  1267. current_time = time.time()
  1268. last_frame_time = _last_frame_times.get(printer_id)
  1269. stream_start_time = _stream_start_times.get(printer_id)
  1270. # Calculate seconds since last frame
  1271. seconds_since_frame = None
  1272. if last_frame_time is not None:
  1273. seconds_since_frame = current_time - last_frame_time
  1274. # Calculate stream uptime
  1275. stream_uptime = None
  1276. if stream_start_time is not None:
  1277. stream_uptime = current_time - stream_start_time
  1278. return {
  1279. "active": has_active_stream,
  1280. "has_frames": printer_id in _last_frames,
  1281. "seconds_since_frame": seconds_since_frame,
  1282. "stream_uptime": stream_uptime,
  1283. # Consider stalled if no frame for more than 10 seconds after stream started
  1284. "stalled": (
  1285. has_active_stream
  1286. and stream_uptime is not None
  1287. and stream_uptime > 5 # Give 5 seconds for stream to start
  1288. and (seconds_since_frame is None or seconds_since_frame > 10)
  1289. ),
  1290. }
  1291. @router.post("/{printer_id}/camera/external/test")
  1292. async def test_external_camera(
  1293. printer_id: int,
  1294. url: str,
  1295. camera_type: str,
  1296. db: AsyncSession = Depends(get_db),
  1297. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1298. ):
  1299. """Test external camera connection.
  1300. Args:
  1301. printer_id: Printer ID (for authorization)
  1302. url: Camera URL or USB device path to test
  1303. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  1304. Returns:
  1305. Dict with {success: bool, error?: str, resolution?: str}
  1306. """
  1307. # Verify printer exists (for authorization)
  1308. await get_printer_or_404(printer_id, db)
  1309. from backend.app.services.external_camera import test_connection
  1310. return await test_connection(url, camera_type)
  1311. @router.get("/{printer_id}/camera/check-plate")
  1312. async def check_plate_empty(
  1313. printer_id: int,
  1314. plate_type: str | None = None,
  1315. use_external: bool | None = None,
  1316. include_debug_image: bool = False,
  1317. db: AsyncSession = Depends(get_db),
  1318. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1319. ):
  1320. """Check if the build plate is empty using camera vision.
  1321. Uses calibration-based difference detection - compares current frame
  1322. to a reference image of the empty plate.
  1323. IMPORTANT: Chamber light must be ON for reliable detection.
  1324. Args:
  1325. printer_id: Printer ID
  1326. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  1327. use_external: If True, prefer external camera over built-in. When omitted
  1328. (None), defaults to the printer's external_camera_enabled setting —
  1329. mirroring the runtime auto-check at print start (main.py). Without
  1330. this default the UI's manual check would always use the built-in
  1331. camera, mismatching the reference saved during calibration (#1359).
  1332. include_debug_image: If True, return URL to annotated debug image
  1333. Returns:
  1334. Dict with detection results:
  1335. - is_empty: bool - Whether plate appears empty
  1336. - confidence: float - Confidence level (0.0 to 1.0)
  1337. - difference_percent: float - How different from calibration reference
  1338. - message: str - Human-readable result message
  1339. - needs_calibration: bool - True if calibration is required
  1340. - light_warning: bool - True if chamber light is off
  1341. """
  1342. from backend.app.services.plate_detection import (
  1343. check_plate_empty as do_check,
  1344. is_plate_detection_available,
  1345. )
  1346. from backend.app.services.printer_manager import printer_manager
  1347. # Check printer exists first (before OpenCV check)
  1348. printer = await get_printer_or_404(printer_id, db)
  1349. if use_external is None:
  1350. use_external = bool(
  1351. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1352. )
  1353. if not is_plate_detection_available():
  1354. raise HTTPException(
  1355. status_code=503,
  1356. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1357. )
  1358. # Check chamber light status
  1359. light_warning = False
  1360. state = printer_manager.get_status(printer_id)
  1361. if state and not state.chamber_light:
  1362. light_warning = True
  1363. from backend.app.services.plate_detection import PlateDetector
  1364. # Build ROI tuple from printer settings if available
  1365. roi = None
  1366. if all(
  1367. [
  1368. printer.plate_detection_roi_x is not None,
  1369. printer.plate_detection_roi_y is not None,
  1370. printer.plate_detection_roi_w is not None,
  1371. printer.plate_detection_roi_h is not None,
  1372. ]
  1373. ):
  1374. roi = (
  1375. printer.plate_detection_roi_x,
  1376. printer.plate_detection_roi_y,
  1377. printer.plate_detection_roi_w,
  1378. printer.plate_detection_roi_h,
  1379. )
  1380. result = await do_check(
  1381. printer_id=printer.id,
  1382. ip_address=printer.ip_address,
  1383. access_code=printer.access_code,
  1384. model=printer.model,
  1385. plate_type=plate_type,
  1386. include_debug_image=include_debug_image,
  1387. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1388. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1389. use_external=use_external,
  1390. roi=roi,
  1391. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1392. )
  1393. # Get reference count for the response
  1394. detector = PlateDetector()
  1395. ref_count = detector.get_calibration_count(printer.id)
  1396. response = result.to_dict()
  1397. response["light_warning"] = light_warning
  1398. response["reference_count"] = ref_count
  1399. response["max_references"] = detector.MAX_REFERENCES
  1400. # Include current ROI in response
  1401. if roi:
  1402. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  1403. else:
  1404. # Return default ROI
  1405. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  1406. # If debug image requested and available, encode as base64 data URL
  1407. if include_debug_image and result.debug_image:
  1408. import base64
  1409. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  1410. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  1411. return response
  1412. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  1413. async def calibrate_plate_detection(
  1414. printer_id: int,
  1415. label: str | None = None,
  1416. use_external: bool | None = None,
  1417. db: AsyncSession = Depends(get_db),
  1418. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1419. ):
  1420. """Calibrate plate detection by capturing a reference image of the empty plate.
  1421. The plate MUST be empty when calling this endpoint. The captured image
  1422. will be used as the reference for future detection comparisons.
  1423. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  1424. is automatically removed.
  1425. IMPORTANT: Chamber light should be ON for calibration.
  1426. Args:
  1427. printer_id: Printer ID
  1428. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  1429. use_external: If True, prefer external camera over built-in. When omitted
  1430. (None), defaults to the printer's external_camera_enabled setting so
  1431. calibration captures from the same source the runtime auto-check
  1432. uses at print start (#1359).
  1433. Returns:
  1434. Dict with:
  1435. - success: bool - Whether calibration succeeded
  1436. - message: str - Status message
  1437. - index: int - The reference slot used (0-4)
  1438. """
  1439. from backend.app.services.plate_detection import (
  1440. calibrate_plate,
  1441. is_plate_detection_available,
  1442. )
  1443. from backend.app.services.printer_manager import printer_manager
  1444. # Check printer exists first (before OpenCV check)
  1445. printer = await get_printer_or_404(printer_id, db)
  1446. if use_external is None:
  1447. use_external = bool(
  1448. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1449. )
  1450. if not is_plate_detection_available():
  1451. raise HTTPException(
  1452. status_code=503,
  1453. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1454. )
  1455. # Check chamber light - warn but don't block
  1456. state = printer_manager.get_status(printer_id)
  1457. light_warning = state and not state.chamber_light
  1458. success, message, index = await calibrate_plate(
  1459. printer_id=printer.id,
  1460. ip_address=printer.ip_address,
  1461. access_code=printer.access_code,
  1462. model=printer.model,
  1463. label=label,
  1464. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1465. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1466. use_external=use_external,
  1467. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1468. )
  1469. if light_warning and success:
  1470. message += " (Warning: Chamber light was off)"
  1471. return {"success": success, "message": message, "index": index}
  1472. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  1473. async def delete_plate_calibration(
  1474. printer_id: int,
  1475. plate_type: str | None = None,
  1476. db: AsyncSession = Depends(get_db),
  1477. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1478. ):
  1479. """Delete the plate detection calibration for a printer and plate type.
  1480. Args:
  1481. printer_id: Printer ID
  1482. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  1483. Returns:
  1484. Dict with:
  1485. - success: bool - Whether deletion succeeded
  1486. - message: str - Status message
  1487. """
  1488. from backend.app.services.plate_detection import (
  1489. delete_calibration,
  1490. is_plate_detection_available,
  1491. )
  1492. # Verify printer exists first (before OpenCV check)
  1493. await get_printer_or_404(printer_id, db)
  1494. if not is_plate_detection_available():
  1495. raise HTTPException(
  1496. status_code=503,
  1497. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1498. )
  1499. deleted = delete_calibration(printer_id, plate_type)
  1500. plate_msg = f" for '{plate_type}'" if plate_type else ""
  1501. return {
  1502. "success": deleted,
  1503. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  1504. }
  1505. @router.get("/{printer_id}/camera/plate-detection/status")
  1506. async def get_plate_detection_status(
  1507. printer_id: int,
  1508. plate_type: str | None = None,
  1509. db: AsyncSession = Depends(get_db),
  1510. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1511. ):
  1512. """Check plate detection status for a printer and plate type.
  1513. Returns:
  1514. Dict with:
  1515. - available: bool - Whether OpenCV is installed
  1516. - calibrated: bool - Whether printer has calibration for this plate type
  1517. - plate_type: str - The plate type queried
  1518. - chamber_light: bool - Whether chamber light is on
  1519. - message: str - Status message
  1520. """
  1521. from backend.app.services.plate_detection import (
  1522. get_calibration_status,
  1523. is_plate_detection_available,
  1524. )
  1525. from backend.app.services.printer_manager import printer_manager
  1526. # Verify printer exists first (before OpenCV check)
  1527. await get_printer_or_404(printer_id, db)
  1528. if not is_plate_detection_available():
  1529. return {
  1530. "available": False,
  1531. "calibrated": False,
  1532. "plate_type": plate_type,
  1533. "chamber_light": False,
  1534. "message": "OpenCV not installed",
  1535. }
  1536. # Get chamber light status
  1537. state = printer_manager.get_status(printer_id)
  1538. chamber_light = state.chamber_light if state else False
  1539. status = get_calibration_status(printer_id, plate_type)
  1540. status["chamber_light"] = chamber_light
  1541. return status
  1542. @router.get("/{printer_id}/camera/plate-detection/references")
  1543. async def get_plate_references(
  1544. printer_id: int,
  1545. db: AsyncSession = Depends(get_db),
  1546. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1547. ):
  1548. """Get all calibration references for a printer with metadata.
  1549. Returns list of references with index, label, timestamp, and thumbnail URL.
  1550. """
  1551. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1552. # Verify printer exists first (before OpenCV check)
  1553. await get_printer_or_404(printer_id, db)
  1554. if not is_plate_detection_available():
  1555. raise HTTPException(503, "Plate detection not available")
  1556. detector = PlateDetector()
  1557. references = detector.get_references(printer_id)
  1558. # Add thumbnail URLs
  1559. for ref in references:
  1560. ref["thumbnail_url"] = (
  1561. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  1562. )
  1563. return {
  1564. "references": references,
  1565. "max_references": detector.MAX_REFERENCES,
  1566. }
  1567. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  1568. async def get_reference_thumbnail(
  1569. printer_id: int,
  1570. index: int,
  1571. db: AsyncSession = Depends(get_db),
  1572. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1573. ):
  1574. """Get thumbnail image for a calibration reference.
  1575. Requires a stream token query param (?token=xxx) when auth is enabled.
  1576. """
  1577. from fastapi.responses import Response
  1578. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1579. # Verify printer exists first (before OpenCV check)
  1580. await get_printer_or_404(printer_id, db)
  1581. if not is_plate_detection_available():
  1582. raise HTTPException(503, "Plate detection not available")
  1583. detector = PlateDetector()
  1584. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  1585. if thumbnail is None:
  1586. raise HTTPException(404, "Reference not found")
  1587. return Response(content=thumbnail, media_type="image/jpeg")
  1588. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  1589. async def update_reference_label(
  1590. printer_id: int,
  1591. index: int,
  1592. label: str,
  1593. db: AsyncSession = Depends(get_db),
  1594. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1595. ):
  1596. """Update the label for a calibration reference."""
  1597. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1598. # Verify printer exists first (before OpenCV check)
  1599. await get_printer_or_404(printer_id, db)
  1600. if not is_plate_detection_available():
  1601. raise HTTPException(503, "Plate detection not available")
  1602. detector = PlateDetector()
  1603. success = detector.update_reference_label(printer_id, index, label)
  1604. if not success:
  1605. raise HTTPException(404, "Reference not found")
  1606. return {"success": True, "index": index, "label": label}
  1607. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  1608. async def delete_reference(
  1609. printer_id: int,
  1610. index: int,
  1611. db: AsyncSession = Depends(get_db),
  1612. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1613. ):
  1614. """Delete a specific calibration reference."""
  1615. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1616. # Verify printer exists first (before OpenCV check)
  1617. await get_printer_or_404(printer_id, db)
  1618. if not is_plate_detection_available():
  1619. raise HTTPException(503, "Plate detection not available")
  1620. detector = PlateDetector()
  1621. success = detector.delete_reference(printer_id, index)
  1622. if not success:
  1623. raise HTTPException(404, "Reference not found")
  1624. return {"success": True, "message": "Reference deleted"}
  1625. def _scan_bambu_ffmpeg_pids() -> list[int]:
  1626. """Scan /proc for ffmpeg processes that are ours.
  1627. Two shapes are matched, both unambiguously Bambuddy's:
  1628. - Bambu RTSP: no other software connects to ``rtsp(s)://bblp:``.
  1629. - External USB (V4L2): an ffmpeg spawned with ``-f v4l2`` is our USB camera
  1630. stream (#2675). Only orphans are killed — the caller excludes PIDs still in
  1631. ``_active_streams``, so a live USB stream (now registered there) is spared.
  1632. This catches orphans that survive app restarts and are not in any tracking dict.
  1633. """
  1634. import os
  1635. pids = []
  1636. try:
  1637. for entry in os.listdir("/proc"):
  1638. if not entry.isdigit():
  1639. continue
  1640. try:
  1641. with open(f"/proc/{entry}/cmdline", "rb") as f:
  1642. cmdline = f.read()
  1643. if b"ffmpeg" not in cmdline:
  1644. continue
  1645. # Match both rtsp:// (via TLS proxy) and rtsps:// (direct), plus
  1646. # the `-f v4l2` input flag our USB camera command always carries.
  1647. if b"rtsp://bblp:" in cmdline or b"rtsps://bblp:" in cmdline or b"v4l2" in cmdline:
  1648. pids.append(int(entry))
  1649. except (OSError, PermissionError, ValueError):
  1650. continue
  1651. except OSError:
  1652. pass
  1653. return pids
  1654. async def cleanup_orphaned_streams():
  1655. """Clean up orphaned ffmpeg processes and stale stream entries.
  1656. Called periodically from the background task loop in main.py.
  1657. Three-layer cleanup:
  1658. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  1659. from previous app sessions. This is the nuclear safety net.
  1660. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  1661. that were removed from _active_streams but not killed.
  1662. 3. _active_streams — kills stale entries with no recent frames.
  1663. """
  1664. import os
  1665. import signal
  1666. import time
  1667. cleaned = 0
  1668. now = time.time()
  1669. # Collect PIDs that are legitimately in-use (active stream, process alive)
  1670. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  1671. # Also exclude PIDs from one-shot snapshot captures (Obico detection, finish photos, etc.)
  1672. from backend.app.services.camera import _active_capture_pids
  1673. active_pids |= _active_capture_pids
  1674. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  1675. # Any ffmpeg with rtsp(s)://bblp: that is NOT in an active stream is orphaned.
  1676. for pid in _scan_bambu_ffmpeg_pids():
  1677. if pid in active_pids:
  1678. continue
  1679. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  1680. try:
  1681. os.kill(pid, signal.SIGKILL)
  1682. except (ProcessLookupError, OSError):
  1683. pass
  1684. _spawned_ffmpeg_pids.pop(pid, None)
  1685. cleaned += 1
  1686. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1687. for pid in list(_spawned_ffmpeg_pids):
  1688. try:
  1689. os.kill(pid, 0) # existence check
  1690. except (ProcessLookupError, OSError):
  1691. _spawned_ffmpeg_pids.pop(pid, None)
  1692. # 3. Clean up _active_streams entries with dead processes
  1693. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1694. for sid in dead_streams:
  1695. proc = _active_streams.pop(sid, None)
  1696. if proc:
  1697. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1698. cleaned += 1
  1699. # 4. Kill stale active streams (alive but no frames for >30s)
  1700. # Uses per-stream timestamps to avoid false "fresh" readings from newer streams
  1701. for sid, proc in list(_active_streams.items()):
  1702. if proc.returncode is not None:
  1703. continue
  1704. # Per-stream frame time is authoritative; fall back to per-printer
  1705. stream_last_frame = _stream_last_frame_times.get(sid)
  1706. if stream_last_frame is None:
  1707. try:
  1708. printer_id = int(sid.split("-", 1)[0])
  1709. except (ValueError, IndexError):
  1710. continue
  1711. stream_last_frame = _last_frame_times.get(printer_id)
  1712. spawn_time = _spawned_ffmpeg_pids.get(proc.pid, now)
  1713. if stream_last_frame is None:
  1714. stream_last_frame = spawn_time
  1715. if now - spawn_time > 60 and now - stream_last_frame > 30:
  1716. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - stream_last_frame)
  1717. # Signal the generator to stop reconnecting
  1718. event = _disconnect_events.get(sid)
  1719. if event:
  1720. event.set()
  1721. try:
  1722. proc.kill()
  1723. # Bounded (#2580): an unreaped SIGKILLed ffmpeg must not hang
  1724. # the periodic cleanup loop — this janitor is the safety net
  1725. # that recovers stalled streams, so it can least afford to
  1726. # block. The /proc scan above retries the kill next pass.
  1727. await asyncio.wait_for(proc.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  1728. except (ProcessLookupError, OSError):
  1729. pass
  1730. except TimeoutError:
  1731. logger.error(
  1732. "ffmpeg (pid=%d) did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  1733. proc.pid,
  1734. _FFMPEG_KILL_TIMEOUT,
  1735. sid,
  1736. )
  1737. _active_streams.pop(sid, None)
  1738. _disconnect_events.pop(sid, None)
  1739. _stream_last_frame_times.pop(sid, None)
  1740. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1741. cleaned += 1
  1742. # 4. Clean stale chamber stream entries
  1743. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1744. for sid in dead_chamber:
  1745. _active_chamber_streams.pop(sid, None)
  1746. cleaned += 1
  1747. if cleaned:
  1748. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)