camera.py 83 KB

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