camera.py 88 KB

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