camera.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import logging
  4. import os
  5. import subprocess
  6. import sys
  7. from collections.abc import AsyncGenerator
  8. from fastapi import APIRouter, Depends, HTTPException, Request
  9. from fastapi.responses import Response, StreamingResponse
  10. from sqlalchemy import select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.auth import (
  13. RequireCameraStreamTokenIfAuthEnabled,
  14. RequirePermissionIfAuthEnabled,
  15. create_camera_stream_token,
  16. )
  17. from backend.app.core.database import get_db
  18. from backend.app.core.permissions import Permission
  19. from backend.app.models.printer import Printer
  20. from backend.app.models.user import User
  21. from backend.app.services.camera import (
  22. capture_camera_frame,
  23. create_tls_proxy,
  24. generate_chamber_image_stream,
  25. get_camera_port,
  26. get_ffmpeg_path,
  27. is_chamber_image_model,
  28. read_next_chamber_frame,
  29. test_camera_connection,
  30. )
  31. from backend.app.services.camera_fanout import (
  32. MjpegBroadcaster,
  33. get_or_create_broadcaster,
  34. iter_subscriber,
  35. shutdown_broadcaster,
  36. )
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/printers", tags=["camera"])
  39. # Track active ffmpeg processes for cleanup
  40. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  41. # Track active chamber image connections for cleanup
  42. _active_chamber_streams: dict[str, tuple] = {}
  43. # Store last frame for each printer (for photo capture from active stream)
  44. _last_frames: dict[int, bytes] = {}
  45. # Track last frame timestamp for each printer (for stall detection)
  46. _last_frame_times: dict[int, float] = {}
  47. # Track stream start times for each printer
  48. _stream_start_times: dict[int, float] = {}
  49. # Track active external camera streams by printer ID
  50. _active_external_streams: set[int] = set()
  51. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  52. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  53. _spawned_ffmpeg_pids: dict[int, float] = {}
  54. # Track disconnect events per stream_id — allows stop endpoint and cleanup
  55. # to signal generators to stop reconnecting instead of just killing the process
  56. _disconnect_events: dict[str, asyncio.Event] = {}
  57. # Track last frame time per stream_id (not just per printer_id) for stale detection
  58. _stream_last_frame_times: dict[str, float] = {}
  59. def get_buffered_frame(printer_id: int) -> bytes | None:
  60. """Get the last buffered frame for a printer from an active stream.
  61. Returns the JPEG frame data if available, or None if no active stream.
  62. """
  63. return _last_frames.get(printer_id)
  64. def is_stream_active(printer_id: int) -> bool:
  65. """Return True iff a fan-out camera stream is currently registered for this printer.
  66. Snapshot callers (Obico polling, manual /camera/snapshot) MUST NOT open a
  67. second concurrent RTSP/chamber-image socket while a viewer is attached:
  68. most Bambu firmwares allow only one camera connection, so the competing
  69. socket either kicks the live viewer off or gets refused itself, and the
  70. resulting reconnect storm tears down the fan-out broadcaster (see #1348).
  71. Callers should consult this BEFORE trying to open a fresh socket and skip
  72. the capture cycle when it returns True — even if try_get_active_buffered_frame
  73. returns None (the stream may be running but the first frame hasn't landed
  74. in the buffer yet, or the upstream is mid-reconnect).
  75. """
  76. return any(k.startswith(f"{printer_id}-") for k in _active_streams) or any(
  77. k.startswith(f"{printer_id}-") for k in _active_chamber_streams
  78. )
  79. def try_get_active_buffered_frame(printer_id: int) -> bytes | None:
  80. """Return a buffered frame iff a stream is currently running for this printer.
  81. Snapshot callers (Obico polling, manual /camera/snapshot) tap the fan-out
  82. broadcaster's running upstream instead of opening a second concurrent
  83. RTSP/chamber-image socket. Critical for printers that allow only one
  84. camera connection (e.g. X2D firmware 01.01.00.00; see #1271).
  85. Returns None when no broadcaster is active for this printer, so callers
  86. fall through to their existing fresh-socket path unchanged.
  87. NB: returning None does NOT mean "safe to open a fresh socket" — it also
  88. fires when the stream is registered but no frame has been buffered yet
  89. (startup race, mid-reconnect). Callers that must avoid competing sockets
  90. should consult is_stream_active() first; see #1348.
  91. """
  92. if not is_stream_active(printer_id):
  93. return None
  94. return _last_frames.get(printer_id)
  95. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  96. """Get printer by ID or raise 404."""
  97. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  98. printer = result.scalar_one_or_none()
  99. if not printer:
  100. raise HTTPException(status_code=404, detail="Printer not found")
  101. return printer
  102. async def generate_chamber_mjpeg_stream(
  103. ip_address: str,
  104. access_code: str,
  105. model: str | None,
  106. fps: int = 5,
  107. stream_id: str | None = None,
  108. disconnect_event: asyncio.Event | None = None,
  109. printer_id: int | None = None,
  110. ) -> AsyncGenerator[bytes, None]:
  111. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  112. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  113. """
  114. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  115. # Register disconnect event so stop endpoint can signal us
  116. if stream_id and disconnect_event:
  117. _disconnect_events[stream_id] = disconnect_event
  118. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  119. if connection is None:
  120. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  121. yield (
  122. b"--frame\r\n"
  123. b"Content-Type: text/plain\r\n\r\n"
  124. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  125. )
  126. return
  127. reader, writer = connection
  128. # Track active connection for cleanup
  129. if stream_id:
  130. _active_chamber_streams[stream_id] = (reader, writer)
  131. try:
  132. frame_interval = 1.0 / fps if fps > 0 else 0.2
  133. last_frame_time = 0.0
  134. while True:
  135. # Check if client disconnected
  136. if disconnect_event and disconnect_event.is_set():
  137. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  138. break
  139. # Read next frame
  140. frame = await read_next_chamber_frame(reader, timeout=30.0)
  141. if frame is None:
  142. logger.warning("Chamber image stream ended for %s", stream_id)
  143. break
  144. # Save frame to buffer for photo capture and track timestamp
  145. if printer_id is not None:
  146. import time
  147. _last_frames[printer_id] = frame
  148. _last_frame_times[printer_id] = time.time()
  149. # Rate limiting - skip frames if needed to maintain target FPS
  150. current_time = asyncio.get_event_loop().time()
  151. if current_time - last_frame_time < frame_interval:
  152. continue
  153. last_frame_time = current_time
  154. # Yield frame in MJPEG format
  155. yield (
  156. b"--frame\r\n"
  157. b"Content-Type: image/jpeg\r\n"
  158. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  159. b"\r\n" + frame + b"\r\n"
  160. )
  161. except asyncio.CancelledError:
  162. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  163. except GeneratorExit:
  164. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  165. except Exception as e:
  166. logger.exception("Chamber image stream error: %s", e)
  167. finally:
  168. # Remove from active streams and disconnect events
  169. if stream_id:
  170. _active_chamber_streams.pop(stream_id, None)
  171. _disconnect_events.pop(stream_id, None)
  172. _stream_last_frame_times.pop(stream_id, None)
  173. # Clean up frame buffer and timestamps
  174. if printer_id is not None:
  175. _last_frames.pop(printer_id, None)
  176. _last_frame_times.pop(printer_id, None)
  177. _stream_start_times.pop(printer_id, None)
  178. # Close the connection
  179. try:
  180. writer.close()
  181. await writer.wait_closed()
  182. except OSError:
  183. pass # Connection already closed or broken; cleanup is best-effort
  184. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  185. async def _terminate_ffmpeg(process: asyncio.subprocess.Process, stream_id: str | None = None) -> None:
  186. """Terminate an ffmpeg process gracefully, then kill if needed."""
  187. if process.returncode is not None:
  188. return # Already dead
  189. try:
  190. process.terminate()
  191. try:
  192. await asyncio.wait_for(process.wait(), timeout=2.0)
  193. except TimeoutError:
  194. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  195. process.kill()
  196. await process.wait()
  197. except ProcessLookupError:
  198. pass # Already dead
  199. except OSError as e:
  200. logger.warning("Error terminating ffmpeg: %s", e)
  201. _spawned_ffmpeg_pids.pop(process.pid, None)
  202. def _summarize_ffmpeg_stderr(text: str | None) -> str:
  203. """Strip ffmpeg's boilerplate banner and keep only actionable lines.
  204. ffmpeg prints ~20 lines of version/build/configuration/lib headers before
  205. any actual error message. Logging the full banner on every retry floods
  206. the log (hundreds of lines per failed stream). This filter drops the
  207. banner and caps output at the last 10 meaningful lines.
  208. """
  209. if not text:
  210. return ""
  211. banner_prefixes = (
  212. "ffmpeg version ",
  213. " built with ",
  214. " configuration:",
  215. " libavutil ",
  216. " libavcodec ",
  217. " libavformat ",
  218. " libavdevice ",
  219. " libavfilter ",
  220. " libswscale ",
  221. " libswresample ",
  222. " libpostproc ",
  223. )
  224. meaningful = [ln for ln in text.splitlines() if ln.strip() and not ln.startswith(banner_prefixes)]
  225. return "\n".join(meaningful[-10:])
  226. async def _read_ffmpeg_stderr(process: asyncio.subprocess.Process) -> str | None:
  227. """Read ffmpeg stderr for diagnostics (best-effort, non-blocking).
  228. Returns the stderr content with ffmpeg's boilerplate banner stripped,
  229. so log output stays focused on the actual error.
  230. """
  231. if not process or not process.stderr:
  232. return None
  233. try:
  234. data = await asyncio.wait_for(process.stderr.read(), timeout=2.0)
  235. if not data:
  236. return None
  237. return _summarize_ffmpeg_stderr(data.decode(errors="replace")) or None
  238. except (TimeoutError, Exception):
  239. return None
  240. # Max consecutive RTSP reconnections before giving up.
  241. # Some printer firmwares (notably P2S) drop RTSP sessions after a few seconds,
  242. # so we transparently respawn ffmpeg to keep the MJPEG stream alive.
  243. _RTSP_MAX_RECONNECTS = 30
  244. _RTSP_RECONNECT_DELAY = 0.2 # seconds between respawns
  245. async def generate_rtsp_mjpeg_stream(
  246. ip_address: str,
  247. access_code: str,
  248. model: str | None,
  249. fps: int = 10,
  250. stream_id: str | None = None,
  251. disconnect_event: asyncio.Event | None = None,
  252. printer_id: int | None = None,
  253. ) -> AsyncGenerator[bytes, None]:
  254. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  255. This is for X1/H2/P2 models that support RTSP streaming.
  256. Auto-reconnects when the printer drops the RTSP session (common on P2S).
  257. """
  258. ffmpeg = get_ffmpeg_path()
  259. if not ffmpeg:
  260. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  261. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  262. return
  263. port = get_camera_port(model)
  264. # Use a local TLS proxy so Python's OpenSSL handles TLS instead of
  265. # ffmpeg's GnuTLS. This fixes P2S (and potentially other models)
  266. # dropping the RTSP session after a few seconds due to GnuTLS's
  267. # hardened Debian defaults rejecting TLS renegotiation.
  268. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  269. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  270. # ffmpeg command to output MJPEG stream to stdout
  271. cmd = [
  272. ffmpeg,
  273. "-rtsp_transport",
  274. "tcp",
  275. "-rtsp_flags",
  276. "prefer_tcp",
  277. "-timeout",
  278. "30000000", # 30 seconds in microseconds
  279. "-buffer_size",
  280. "1024000", # 1MB buffer
  281. "-max_delay",
  282. "500000", # 0.5 seconds max delay
  283. "-probesize",
  284. "32", # Minimal probing for faster startup
  285. "-analyzeduration",
  286. "0", # Skip format analysis for faster startup
  287. "-fflags",
  288. "nobuffer", # Reduce internal buffering
  289. "-flags",
  290. "low_delay", # Minimize decode latency
  291. "-i",
  292. camera_url,
  293. "-f",
  294. "mjpeg",
  295. "-q:v",
  296. "5",
  297. "-r",
  298. str(fps),
  299. "-an", # No audio
  300. "-", # Output to stdout
  301. ]
  302. # Register disconnect event so stop endpoint can signal us
  303. if stream_id and disconnect_event:
  304. _disconnect_events[stream_id] = disconnect_event
  305. logger.info(
  306. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s)", ip_address, stream_id, model, fps
  307. )
  308. logger.debug("ffmpeg command: %s ... (url hidden)", ffmpeg)
  309. # On Windows, spawn ffmpeg in its own process group so that
  310. # terminate() doesn't broadcast CTRL_C_EVENT to uvicorn (#605).
  311. spawn_kwargs: dict = {}
  312. if sys.platform == "win32":
  313. spawn_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  314. jpeg_start = b"\xff\xd8"
  315. jpeg_end = b"\xff\xd9"
  316. reconnect_count = 0
  317. process = None
  318. got_any_frames = False
  319. try:
  320. while reconnect_count <= _RTSP_MAX_RECONNECTS:
  321. # Check for client disconnect before (re)connecting
  322. if disconnect_event and disconnect_event.is_set():
  323. break
  324. if reconnect_count > 0:
  325. logger.info(
  326. "RTSP reconnecting (%d/%d) for %s (stream_id=%s)",
  327. reconnect_count,
  328. _RTSP_MAX_RECONNECTS,
  329. ip_address,
  330. stream_id,
  331. )
  332. await asyncio.sleep(_RTSP_RECONNECT_DELAY)
  333. if disconnect_event and disconnect_event.is_set():
  334. break
  335. # Spawn ffmpeg
  336. process = await asyncio.create_subprocess_exec(
  337. *cmd,
  338. stdout=asyncio.subprocess.PIPE,
  339. stderr=asyncio.subprocess.PIPE,
  340. **spawn_kwargs,
  341. )
  342. if stream_id:
  343. _active_streams[stream_id] = process
  344. import time as _time
  345. _spawned_ffmpeg_pids[process.pid] = _time.time()
  346. # Brief check for immediate startup failures
  347. await asyncio.sleep(0.1)
  348. if process.returncode is not None:
  349. stderr = await process.stderr.read()
  350. stderr_text = _summarize_ffmpeg_stderr(stderr.decode(errors="replace"))
  351. logger.error("ffmpeg failed immediately (attempt %d): %s", reconnect_count + 1, stderr_text)
  352. _spawned_ffmpeg_pids.pop(process.pid, None)
  353. if not got_any_frames and reconnect_count == 0:
  354. # First attempt failed immediately — camera is likely unreachable
  355. yield (
  356. b"--frame\r\n"
  357. b"Content-Type: text/plain\r\n\r\n"
  358. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  359. )
  360. return
  361. reconnect_count += 1
  362. continue
  363. # Read JPEG frames from ffmpeg stdout
  364. buffer = b""
  365. stream_ended = False
  366. client_gone = False
  367. while True:
  368. if disconnect_event and disconnect_event.is_set():
  369. client_gone = True
  370. break
  371. try:
  372. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  373. if not chunk:
  374. # ffmpeg exited — log stderr and break to reconnect
  375. stderr_text = await _read_ffmpeg_stderr(process)
  376. if stderr_text:
  377. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  378. logger.warning("RTSP stream ended for %s (stream_id=%s), will reconnect", ip_address, stream_id)
  379. stream_ended = True
  380. break
  381. buffer += chunk
  382. # Extract complete JPEG frames from buffer
  383. while True:
  384. start_idx = buffer.find(jpeg_start)
  385. if start_idx == -1:
  386. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  387. break
  388. if start_idx > 0:
  389. buffer = buffer[start_idx:]
  390. end_idx = buffer.find(jpeg_end, 2)
  391. if end_idx == -1:
  392. break
  393. frame = buffer[: end_idx + 2]
  394. buffer = buffer[end_idx + 2 :]
  395. got_any_frames = True
  396. if printer_id is not None:
  397. import time
  398. _last_frames[printer_id] = frame
  399. _last_frame_times[printer_id] = time.time()
  400. if stream_id:
  401. _stream_last_frame_times[stream_id] = time.time()
  402. yield (
  403. b"--frame\r\n"
  404. b"Content-Type: image/jpeg\r\n"
  405. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  406. b"\r\n" + frame + b"\r\n"
  407. )
  408. except TimeoutError:
  409. stderr_text = await _read_ffmpeg_stderr(process)
  410. if stderr_text:
  411. logger.warning("ffmpeg stderr on timeout: %s", stderr_text)
  412. logger.warning("RTSP read timeout for %s (stream_id=%s)", ip_address, stream_id)
  413. stream_ended = True
  414. break
  415. except asyncio.CancelledError:
  416. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  417. client_gone = True
  418. break
  419. except GeneratorExit:
  420. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  421. client_gone = True
  422. break
  423. # Clean up this ffmpeg process before reconnecting or exiting
  424. await _terminate_ffmpeg(process, stream_id)
  425. process = None
  426. if client_gone:
  427. break
  428. # Check if stream was explicitly stopped (e.g., by stop endpoint)
  429. if stream_id and stream_id not in _active_streams:
  430. logger.info("Stream %s removed from active streams, stopping reconnect", stream_id)
  431. break
  432. if stream_ended:
  433. reconnect_count += 1
  434. continue
  435. # Normal exit (shouldn't reach here, but be safe)
  436. break
  437. if reconnect_count > _RTSP_MAX_RECONNECTS:
  438. logger.error(
  439. "RTSP max reconnects (%d) reached for %s (stream_id=%s)",
  440. _RTSP_MAX_RECONNECTS,
  441. ip_address,
  442. stream_id,
  443. )
  444. except FileNotFoundError:
  445. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  446. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  447. except asyncio.CancelledError:
  448. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  449. except GeneratorExit:
  450. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  451. except Exception as e:
  452. logger.exception("Camera stream error: %s", e)
  453. finally:
  454. # Remove from active streams and disconnect events
  455. if stream_id:
  456. _active_streams.pop(stream_id, None)
  457. _disconnect_events.pop(stream_id, None)
  458. _stream_last_frame_times.pop(stream_id, None)
  459. # Clean up frame buffer and timestamps
  460. if printer_id is not None:
  461. _last_frames.pop(printer_id, None)
  462. _last_frame_times.pop(printer_id, None)
  463. _stream_start_times.pop(printer_id, None)
  464. if process:
  465. await _terminate_ffmpeg(process, stream_id)
  466. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  467. # Shut down the TLS proxy
  468. proxy_server.close()
  469. await proxy_server.wait_closed()
  470. @router.post("/camera/stream-token")
  471. async def create_stream_token(
  472. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  473. ):
  474. """Create a reusable token for camera stream/snapshot access.
  475. Returns a token valid for 60 minutes that can be appended as ?token=xxx
  476. to camera stream/snapshot URLs loaded via <img> tags.
  477. """
  478. return {"token": await create_camera_stream_token()}
  479. @router.get("/{printer_id}/camera/stream")
  480. async def camera_stream(
  481. printer_id: int,
  482. request: Request,
  483. fps: int = 10,
  484. db: AsyncSession = Depends(get_db),
  485. _: None = RequireCameraStreamTokenIfAuthEnabled,
  486. ):
  487. """Stream live video from printer camera as MJPEG.
  488. This endpoint returns a multipart MJPEG stream that can be used directly
  489. in an <img> tag or video player.
  490. Requires a stream token query param (?token=xxx) when auth is enabled.
  491. Uses external camera if configured, otherwise uses built-in camera:
  492. - External: MJPEG, RTSP, or HTTP snapshot
  493. - A1/P1: Chamber image protocol (port 6000)
  494. - X1/H2/P2: RTSP via ffmpeg (port 322)
  495. Args:
  496. printer_id: Printer ID
  497. fps: Target frames per second (default: 10, max: 30)
  498. """
  499. printer = await get_printer_or_404(printer_id, db)
  500. # Check for external camera first
  501. if printer.external_camera_enabled and printer.external_camera_url:
  502. import time
  503. from backend.app.services.external_camera import generate_mjpeg_stream
  504. # Limit external camera FPS to reduce browser load
  505. fps = min(max(fps, 1), 15)
  506. logger.info(
  507. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  508. )
  509. # Track stream start
  510. _stream_start_times[printer_id] = time.time()
  511. _active_external_streams.add(printer_id)
  512. async def external_stream_wrapper():
  513. """Wrap external stream to track start/stop and update frame times."""
  514. try:
  515. async for frame in generate_mjpeg_stream(
  516. printer.external_camera_url, printer.external_camera_type, fps
  517. ):
  518. # generate_mjpeg_stream already handles rate limiting;
  519. # just track frame times for stall detection
  520. _last_frame_times[printer_id] = time.time()
  521. yield frame
  522. finally:
  523. _active_external_streams.discard(printer_id)
  524. logger.info("External camera stream ended for printer %s", printer_id)
  525. return StreamingResponse(
  526. external_stream_wrapper(),
  527. media_type="multipart/x-mixed-replace; boundary=frame",
  528. headers={
  529. "Cache-Control": "no-cache, no-store, must-revalidate",
  530. "Pragma": "no-cache",
  531. "Expires": "0",
  532. },
  533. )
  534. # Validate FPS - A1/P1 models max out at ~5 FPS
  535. if is_chamber_image_model(printer.model):
  536. fps = min(max(fps, 1), 5)
  537. else:
  538. fps = min(max(fps, 1), 30)
  539. # Choose the appropriate stream generator based on model
  540. if is_chamber_image_model(printer.model):
  541. stream_generator = generate_chamber_mjpeg_stream
  542. logger.info("Using chamber image protocol for %s", printer.model)
  543. else:
  544. stream_generator = generate_rtsp_mjpeg_stream
  545. logger.info("Using RTSP protocol for %s", printer.model)
  546. # Track stream start time. Set only if absent so the value reflects when
  547. # the SHARED upstream first started streaming, not when each new viewer
  548. # attached — otherwise /camera/status would report stream_uptime jumping
  549. # backward whenever a second viewer joins. The upstream generator's
  550. # finally clears this entry when the upstream actually ends.
  551. import time
  552. _stream_start_times.setdefault(printer_id, time.time())
  553. # Fan-out broadcaster (#1089): one upstream connection per printer, shared
  554. # across all viewers. Most Bambu printers only allow a single concurrent
  555. # camera connection, so opening the same printer in two tabs would
  556. # otherwise kick the first viewer off. The broadcaster owns the single
  557. # upstream and the per-viewer disconnect handling.
  558. #
  559. # Note: the upstream's fps is fixed by the first viewer who creates the
  560. # broadcaster. Concurrent viewers share that rate; new viewers after
  561. # teardown create a fresh broadcaster at their requested fps.
  562. fanout_key = f"printer-{printer_id}"
  563. upstream_stream_id = f"{printer_id}-fanout"
  564. def _factory(disconnect_event: asyncio.Event):
  565. # Re-bind locals into the closure so the async generator below sees
  566. # them — disconnect_event is owned by the broadcaster and signalled
  567. # when the last subscriber leaves (after the grace window).
  568. return stream_generator(
  569. ip_address=printer.ip_address,
  570. access_code=printer.access_code,
  571. model=printer.model,
  572. fps=fps,
  573. stream_id=upstream_stream_id,
  574. disconnect_event=disconnect_event,
  575. printer_id=printer_id,
  576. )
  577. # Subscribe with a one-shot retry to close a tiny race: the grace-window
  578. # teardown can flip the broadcaster to `stopped=True` between the registry
  579. # lookup and our subscribe call. The retry forces the registry to mint a
  580. # fresh broadcaster (since the now-stopped one is replaced), and the second
  581. # subscribe is guaranteed to land on it before any teardown can fire.
  582. broadcaster: MjpegBroadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  583. try:
  584. queue = await broadcaster.subscribe()
  585. except RuntimeError:
  586. broadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  587. queue = await broadcaster.subscribe()
  588. logger.info(
  589. "Camera viewer attached to %s (subscribers=%d)",
  590. fanout_key,
  591. broadcaster.subscriber_count,
  592. )
  593. async def _is_disconnected() -> bool:
  594. try:
  595. return await request.is_disconnected()
  596. except Exception:
  597. # Older starlette/uvicorn can raise during teardown — treat that
  598. # as "client gone" so the subscriber cleanly unsubscribes.
  599. return True
  600. def _log_detach(remaining: int) -> None:
  601. logger.info("Camera viewer detached from %s (subscribers=%d)", fanout_key, remaining)
  602. async def _generate():
  603. async for chunk in iter_subscriber(
  604. broadcaster,
  605. queue,
  606. is_disconnected=_is_disconnected,
  607. on_unsubscribe=_log_detach,
  608. ):
  609. yield chunk
  610. return StreamingResponse(
  611. _generate(),
  612. media_type="multipart/x-mixed-replace; boundary=frame",
  613. headers={
  614. "Cache-Control": "no-cache, no-store, must-revalidate",
  615. "Pragma": "no-cache",
  616. "Expires": "0",
  617. },
  618. )
  619. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  620. async def stop_camera_stream(
  621. printer_id: int,
  622. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  623. ):
  624. """Stop all active camera streams for a printer.
  625. This can be called by the frontend when the camera window is closed.
  626. Accepts both GET and POST (POST for sendBeacon compatibility).
  627. """
  628. stopped = 0
  629. # Tear down the fan-out broadcaster first (#1089). This cleanly notifies
  630. # all subscribed viewers and asks the upstream generator to stop
  631. # reconnecting before we fall back to forcefully killing the process below.
  632. if await shutdown_broadcaster(f"printer-{printer_id}"):
  633. logger.info("Shut down camera fan-out broadcaster for printer %s", printer_id)
  634. # Stop ffmpeg/RTSP streams
  635. to_remove = []
  636. for stream_id, process in list(_active_streams.items()):
  637. if stream_id.startswith(f"{printer_id}-"):
  638. to_remove.append(stream_id)
  639. # Signal the generator to stop reconnecting BEFORE killing the process
  640. event = _disconnect_events.get(stream_id)
  641. if event:
  642. event.set()
  643. if process.returncode is None:
  644. try:
  645. process.terminate()
  646. try:
  647. await asyncio.wait_for(process.wait(), timeout=2.0)
  648. except TimeoutError:
  649. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  650. process.kill()
  651. await process.wait()
  652. stopped += 1
  653. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  654. except ProcessLookupError:
  655. pass # Process already dead
  656. except OSError as e:
  657. logger.warning("Error stopping stream %s: %s", stream_id, e)
  658. _spawned_ffmpeg_pids.pop(process.pid, None)
  659. for stream_id in to_remove:
  660. _active_streams.pop(stream_id, None)
  661. _disconnect_events.pop(stream_id, None)
  662. _stream_last_frame_times.pop(stream_id, None)
  663. # Stop chamber image streams
  664. to_remove_chamber = []
  665. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  666. if stream_id.startswith(f"{printer_id}-"):
  667. to_remove_chamber.append(stream_id)
  668. # Signal the generator to stop
  669. event = _disconnect_events.get(stream_id)
  670. if event:
  671. event.set()
  672. try:
  673. writer.close()
  674. stopped += 1
  675. logger.info("Closed chamber image connection for stream %s", stream_id)
  676. except OSError as e:
  677. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  678. for stream_id in to_remove_chamber:
  679. _active_chamber_streams.pop(stream_id, None)
  680. _disconnect_events.pop(stream_id, None)
  681. _stream_last_frame_times.pop(stream_id, None)
  682. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  683. return {"stopped": stopped}
  684. @router.get("/{printer_id}/camera/snapshot")
  685. async def camera_snapshot(
  686. printer_id: int,
  687. db: AsyncSession = Depends(get_db),
  688. _: None = RequireCameraStreamTokenIfAuthEnabled,
  689. ):
  690. """Capture a single frame from the printer camera.
  691. Returns a JPEG image.
  692. Requires a stream token query param (?token=xxx) when auth is enabled.
  693. """
  694. import tempfile
  695. from pathlib import Path
  696. printer = await get_printer_or_404(printer_id, db)
  697. # Check for external camera first
  698. if printer.external_camera_enabled and printer.external_camera_url:
  699. from backend.app.services.external_camera import capture_frame
  700. frame_data = await capture_frame(
  701. printer.external_camera_url,
  702. printer.external_camera_type,
  703. timeout=15,
  704. snapshot_url=printer.external_camera_snapshot_url,
  705. )
  706. if not frame_data:
  707. raise HTTPException(
  708. status_code=503,
  709. detail="Failed to capture frame from external camera.",
  710. )
  711. return Response(
  712. content=frame_data,
  713. media_type="image/jpeg",
  714. headers={
  715. "Cache-Control": "no-cache, no-store, must-revalidate",
  716. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  717. },
  718. )
  719. # Reuse the fan-out broadcaster's buffered frame when a viewer is already
  720. # watching — avoids opening a second concurrent RTSP socket on printers
  721. # that allow only one camera connection (e.g. X2D firmware 01.01.00.00;
  722. # see #1271). Buffered frame is <1s old while a viewer is connected.
  723. buffered = try_get_active_buffered_frame(printer_id)
  724. if buffered:
  725. return Response(
  726. content=buffered,
  727. media_type="image/jpeg",
  728. headers={
  729. "Cache-Control": "no-cache, no-store, must-revalidate",
  730. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  731. },
  732. )
  733. # Create temporary file for the snapshot (0600 so only the app user can read it)
  734. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  735. os.close(fd)
  736. temp_path = Path(tmp_name)
  737. temp_path.chmod(0o600)
  738. try:
  739. success = await capture_camera_frame(
  740. ip_address=printer.ip_address,
  741. access_code=printer.access_code,
  742. model=printer.model,
  743. output_path=temp_path,
  744. timeout=15,
  745. )
  746. if not success:
  747. raise HTTPException(
  748. status_code=503,
  749. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  750. )
  751. # Read and return the image
  752. with open(temp_path, "rb") as f:
  753. image_data = f.read()
  754. return Response(
  755. content=image_data,
  756. media_type="image/jpeg",
  757. headers={
  758. "Cache-Control": "no-cache, no-store, must-revalidate",
  759. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  760. },
  761. )
  762. finally:
  763. # Clean up temp file
  764. if temp_path.exists():
  765. temp_path.unlink()
  766. @router.get("/{printer_id}/camera/test")
  767. async def test_camera(
  768. printer_id: int,
  769. db: AsyncSession = Depends(get_db),
  770. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  771. ):
  772. """Test camera connection for a printer.
  773. Returns success status and any error message.
  774. """
  775. printer = await get_printer_or_404(printer_id, db)
  776. result = await test_camera_connection(
  777. ip_address=printer.ip_address,
  778. access_code=printer.access_code,
  779. model=printer.model,
  780. )
  781. return result
  782. @router.get("/{printer_id}/camera/status")
  783. async def camera_status(
  784. printer_id: int,
  785. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  786. ):
  787. """Get the status of an active camera stream.
  788. Returns whether a stream is active and when the last frame was received.
  789. Used by the frontend to detect stalled streams and auto-reconnect.
  790. """
  791. import time
  792. # Check if there's an active stream for this printer
  793. has_active_stream = False
  794. # Check external camera streams
  795. if printer_id in _active_external_streams:
  796. has_active_stream = True
  797. # Check ffmpeg/RTSP streams
  798. if not has_active_stream:
  799. for stream_id in _active_streams:
  800. if stream_id.startswith(f"{printer_id}-"):
  801. process = _active_streams[stream_id]
  802. if process.returncode is None:
  803. has_active_stream = True
  804. break
  805. # Check chamber image streams
  806. if not has_active_stream:
  807. for stream_id in _active_chamber_streams:
  808. if stream_id.startswith(f"{printer_id}-"):
  809. has_active_stream = True
  810. break
  811. # Get timing information
  812. current_time = time.time()
  813. last_frame_time = _last_frame_times.get(printer_id)
  814. stream_start_time = _stream_start_times.get(printer_id)
  815. # Calculate seconds since last frame
  816. seconds_since_frame = None
  817. if last_frame_time is not None:
  818. seconds_since_frame = current_time - last_frame_time
  819. # Calculate stream uptime
  820. stream_uptime = None
  821. if stream_start_time is not None:
  822. stream_uptime = current_time - stream_start_time
  823. return {
  824. "active": has_active_stream,
  825. "has_frames": printer_id in _last_frames,
  826. "seconds_since_frame": seconds_since_frame,
  827. "stream_uptime": stream_uptime,
  828. # Consider stalled if no frame for more than 10 seconds after stream started
  829. "stalled": (
  830. has_active_stream
  831. and stream_uptime is not None
  832. and stream_uptime > 5 # Give 5 seconds for stream to start
  833. and (seconds_since_frame is None or seconds_since_frame > 10)
  834. ),
  835. }
  836. @router.post("/{printer_id}/camera/external/test")
  837. async def test_external_camera(
  838. printer_id: int,
  839. url: str,
  840. camera_type: str,
  841. db: AsyncSession = Depends(get_db),
  842. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  843. ):
  844. """Test external camera connection.
  845. Args:
  846. printer_id: Printer ID (for authorization)
  847. url: Camera URL or USB device path to test
  848. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  849. Returns:
  850. Dict with {success: bool, error?: str, resolution?: str}
  851. """
  852. # Verify printer exists (for authorization)
  853. await get_printer_or_404(printer_id, db)
  854. from backend.app.services.external_camera import test_connection
  855. return await test_connection(url, camera_type)
  856. @router.get("/{printer_id}/camera/check-plate")
  857. async def check_plate_empty(
  858. printer_id: int,
  859. plate_type: str | None = None,
  860. use_external: bool | None = None,
  861. include_debug_image: bool = False,
  862. db: AsyncSession = Depends(get_db),
  863. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  864. ):
  865. """Check if the build plate is empty using camera vision.
  866. Uses calibration-based difference detection - compares current frame
  867. to a reference image of the empty plate.
  868. IMPORTANT: Chamber light must be ON for reliable detection.
  869. Args:
  870. printer_id: Printer ID
  871. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  872. use_external: If True, prefer external camera over built-in. When omitted
  873. (None), defaults to the printer's external_camera_enabled setting —
  874. mirroring the runtime auto-check at print start (main.py). Without
  875. this default the UI's manual check would always use the built-in
  876. camera, mismatching the reference saved during calibration (#1359).
  877. include_debug_image: If True, return URL to annotated debug image
  878. Returns:
  879. Dict with detection results:
  880. - is_empty: bool - Whether plate appears empty
  881. - confidence: float - Confidence level (0.0 to 1.0)
  882. - difference_percent: float - How different from calibration reference
  883. - message: str - Human-readable result message
  884. - needs_calibration: bool - True if calibration is required
  885. - light_warning: bool - True if chamber light is off
  886. """
  887. from backend.app.services.plate_detection import (
  888. check_plate_empty as do_check,
  889. is_plate_detection_available,
  890. )
  891. from backend.app.services.printer_manager import printer_manager
  892. # Check printer exists first (before OpenCV check)
  893. printer = await get_printer_or_404(printer_id, db)
  894. if use_external is None:
  895. use_external = bool(
  896. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  897. )
  898. if not is_plate_detection_available():
  899. raise HTTPException(
  900. status_code=503,
  901. detail="Plate detection not available. Install opencv-python-headless to enable.",
  902. )
  903. # Check chamber light status
  904. light_warning = False
  905. state = printer_manager.get_status(printer_id)
  906. if state and not state.chamber_light:
  907. light_warning = True
  908. from backend.app.services.plate_detection import PlateDetector
  909. # Build ROI tuple from printer settings if available
  910. roi = None
  911. if all(
  912. [
  913. printer.plate_detection_roi_x is not None,
  914. printer.plate_detection_roi_y is not None,
  915. printer.plate_detection_roi_w is not None,
  916. printer.plate_detection_roi_h is not None,
  917. ]
  918. ):
  919. roi = (
  920. printer.plate_detection_roi_x,
  921. printer.plate_detection_roi_y,
  922. printer.plate_detection_roi_w,
  923. printer.plate_detection_roi_h,
  924. )
  925. result = await do_check(
  926. printer_id=printer.id,
  927. ip_address=printer.ip_address,
  928. access_code=printer.access_code,
  929. model=printer.model,
  930. plate_type=plate_type,
  931. include_debug_image=include_debug_image,
  932. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  933. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  934. use_external=use_external,
  935. roi=roi,
  936. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  937. )
  938. # Get reference count for the response
  939. detector = PlateDetector()
  940. ref_count = detector.get_calibration_count(printer.id)
  941. response = result.to_dict()
  942. response["light_warning"] = light_warning
  943. response["reference_count"] = ref_count
  944. response["max_references"] = detector.MAX_REFERENCES
  945. # Include current ROI in response
  946. if roi:
  947. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  948. else:
  949. # Return default ROI
  950. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  951. # If debug image requested and available, encode as base64 data URL
  952. if include_debug_image and result.debug_image:
  953. import base64
  954. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  955. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  956. return response
  957. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  958. async def calibrate_plate_detection(
  959. printer_id: int,
  960. label: str | None = None,
  961. use_external: bool | None = None,
  962. db: AsyncSession = Depends(get_db),
  963. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  964. ):
  965. """Calibrate plate detection by capturing a reference image of the empty plate.
  966. The plate MUST be empty when calling this endpoint. The captured image
  967. will be used as the reference for future detection comparisons.
  968. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  969. is automatically removed.
  970. IMPORTANT: Chamber light should be ON for calibration.
  971. Args:
  972. printer_id: Printer ID
  973. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  974. use_external: If True, prefer external camera over built-in. When omitted
  975. (None), defaults to the printer's external_camera_enabled setting so
  976. calibration captures from the same source the runtime auto-check
  977. uses at print start (#1359).
  978. Returns:
  979. Dict with:
  980. - success: bool - Whether calibration succeeded
  981. - message: str - Status message
  982. - index: int - The reference slot used (0-4)
  983. """
  984. from backend.app.services.plate_detection import (
  985. calibrate_plate,
  986. is_plate_detection_available,
  987. )
  988. from backend.app.services.printer_manager import printer_manager
  989. # Check printer exists first (before OpenCV check)
  990. printer = await get_printer_or_404(printer_id, db)
  991. if use_external is None:
  992. use_external = bool(
  993. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  994. )
  995. if not is_plate_detection_available():
  996. raise HTTPException(
  997. status_code=503,
  998. detail="Plate detection not available. Install opencv-python-headless to enable.",
  999. )
  1000. # Check chamber light - warn but don't block
  1001. state = printer_manager.get_status(printer_id)
  1002. light_warning = state and not state.chamber_light
  1003. success, message, index = await calibrate_plate(
  1004. printer_id=printer.id,
  1005. ip_address=printer.ip_address,
  1006. access_code=printer.access_code,
  1007. model=printer.model,
  1008. label=label,
  1009. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1010. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1011. use_external=use_external,
  1012. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1013. )
  1014. if light_warning and success:
  1015. message += " (Warning: Chamber light was off)"
  1016. return {"success": success, "message": message, "index": index}
  1017. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  1018. async def delete_plate_calibration(
  1019. printer_id: int,
  1020. plate_type: str | None = None,
  1021. db: AsyncSession = Depends(get_db),
  1022. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1023. ):
  1024. """Delete the plate detection calibration for a printer and plate type.
  1025. Args:
  1026. printer_id: Printer ID
  1027. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  1028. Returns:
  1029. Dict with:
  1030. - success: bool - Whether deletion succeeded
  1031. - message: str - Status message
  1032. """
  1033. from backend.app.services.plate_detection import (
  1034. delete_calibration,
  1035. is_plate_detection_available,
  1036. )
  1037. # Verify printer exists first (before OpenCV check)
  1038. await get_printer_or_404(printer_id, db)
  1039. if not is_plate_detection_available():
  1040. raise HTTPException(
  1041. status_code=503,
  1042. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1043. )
  1044. deleted = delete_calibration(printer_id, plate_type)
  1045. plate_msg = f" for '{plate_type}'" if plate_type else ""
  1046. return {
  1047. "success": deleted,
  1048. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  1049. }
  1050. @router.get("/{printer_id}/camera/plate-detection/status")
  1051. async def get_plate_detection_status(
  1052. printer_id: int,
  1053. plate_type: str | None = None,
  1054. db: AsyncSession = Depends(get_db),
  1055. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1056. ):
  1057. """Check plate detection status for a printer and plate type.
  1058. Returns:
  1059. Dict with:
  1060. - available: bool - Whether OpenCV is installed
  1061. - calibrated: bool - Whether printer has calibration for this plate type
  1062. - plate_type: str - The plate type queried
  1063. - chamber_light: bool - Whether chamber light is on
  1064. - message: str - Status message
  1065. """
  1066. from backend.app.services.plate_detection import (
  1067. get_calibration_status,
  1068. is_plate_detection_available,
  1069. )
  1070. from backend.app.services.printer_manager import printer_manager
  1071. # Verify printer exists first (before OpenCV check)
  1072. await get_printer_or_404(printer_id, db)
  1073. if not is_plate_detection_available():
  1074. return {
  1075. "available": False,
  1076. "calibrated": False,
  1077. "plate_type": plate_type,
  1078. "chamber_light": False,
  1079. "message": "OpenCV not installed",
  1080. }
  1081. # Get chamber light status
  1082. state = printer_manager.get_status(printer_id)
  1083. chamber_light = state.chamber_light if state else False
  1084. status = get_calibration_status(printer_id, plate_type)
  1085. status["chamber_light"] = chamber_light
  1086. return status
  1087. @router.get("/{printer_id}/camera/plate-detection/references")
  1088. async def get_plate_references(
  1089. printer_id: int,
  1090. db: AsyncSession = Depends(get_db),
  1091. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1092. ):
  1093. """Get all calibration references for a printer with metadata.
  1094. Returns list of references with index, label, timestamp, and thumbnail URL.
  1095. """
  1096. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1097. # Verify printer exists first (before OpenCV check)
  1098. await get_printer_or_404(printer_id, db)
  1099. if not is_plate_detection_available():
  1100. raise HTTPException(503, "Plate detection not available")
  1101. detector = PlateDetector()
  1102. references = detector.get_references(printer_id)
  1103. # Add thumbnail URLs
  1104. for ref in references:
  1105. ref["thumbnail_url"] = (
  1106. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  1107. )
  1108. return {
  1109. "references": references,
  1110. "max_references": detector.MAX_REFERENCES,
  1111. }
  1112. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  1113. async def get_reference_thumbnail(
  1114. printer_id: int,
  1115. index: int,
  1116. db: AsyncSession = Depends(get_db),
  1117. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1118. ):
  1119. """Get thumbnail image for a calibration reference.
  1120. Requires a stream token query param (?token=xxx) when auth is enabled.
  1121. """
  1122. from fastapi.responses import Response
  1123. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1124. # Verify printer exists first (before OpenCV check)
  1125. await get_printer_or_404(printer_id, db)
  1126. if not is_plate_detection_available():
  1127. raise HTTPException(503, "Plate detection not available")
  1128. detector = PlateDetector()
  1129. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  1130. if thumbnail is None:
  1131. raise HTTPException(404, "Reference not found")
  1132. return Response(content=thumbnail, media_type="image/jpeg")
  1133. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  1134. async def update_reference_label(
  1135. printer_id: int,
  1136. index: int,
  1137. label: str,
  1138. db: AsyncSession = Depends(get_db),
  1139. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1140. ):
  1141. """Update the label for a calibration reference."""
  1142. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1143. # Verify printer exists first (before OpenCV check)
  1144. await get_printer_or_404(printer_id, db)
  1145. if not is_plate_detection_available():
  1146. raise HTTPException(503, "Plate detection not available")
  1147. detector = PlateDetector()
  1148. success = detector.update_reference_label(printer_id, index, label)
  1149. if not success:
  1150. raise HTTPException(404, "Reference not found")
  1151. return {"success": True, "index": index, "label": label}
  1152. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  1153. async def delete_reference(
  1154. printer_id: int,
  1155. index: int,
  1156. db: AsyncSession = Depends(get_db),
  1157. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1158. ):
  1159. """Delete a specific calibration reference."""
  1160. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1161. # Verify printer exists first (before OpenCV check)
  1162. await get_printer_or_404(printer_id, db)
  1163. if not is_plate_detection_available():
  1164. raise HTTPException(503, "Plate detection not available")
  1165. detector = PlateDetector()
  1166. success = detector.delete_reference(printer_id, index)
  1167. if not success:
  1168. raise HTTPException(404, "Reference not found")
  1169. return {"success": True, "message": "Reference deleted"}
  1170. def _scan_bambu_ffmpeg_pids() -> list[int]:
  1171. """Scan /proc for ffmpeg processes with Bambu RTSP URLs.
  1172. These are definitely ours — no other software connects to rtsp(s)://bblp:.
  1173. This catches orphans that survive app restarts and are not in any tracking dict.
  1174. """
  1175. import os
  1176. pids = []
  1177. try:
  1178. for entry in os.listdir("/proc"):
  1179. if not entry.isdigit():
  1180. continue
  1181. try:
  1182. with open(f"/proc/{entry}/cmdline", "rb") as f:
  1183. cmdline = f.read()
  1184. # Match both rtsp:// (via TLS proxy) and rtsps:// (direct)
  1185. if b"ffmpeg" in cmdline and (b"rtsp://bblp:" in cmdline or b"rtsps://bblp:" in cmdline):
  1186. pids.append(int(entry))
  1187. except (OSError, PermissionError, ValueError):
  1188. continue
  1189. except OSError:
  1190. pass
  1191. return pids
  1192. async def cleanup_orphaned_streams():
  1193. """Clean up orphaned ffmpeg processes and stale stream entries.
  1194. Called periodically from the background task loop in main.py.
  1195. Three-layer cleanup:
  1196. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  1197. from previous app sessions. This is the nuclear safety net.
  1198. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  1199. that were removed from _active_streams but not killed.
  1200. 3. _active_streams — kills stale entries with no recent frames.
  1201. """
  1202. import os
  1203. import signal
  1204. import time
  1205. cleaned = 0
  1206. now = time.time()
  1207. # Collect PIDs that are legitimately in-use (active stream, process alive)
  1208. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  1209. # Also exclude PIDs from one-shot snapshot captures (Obico detection, finish photos, etc.)
  1210. from backend.app.services.camera import _active_capture_pids
  1211. active_pids |= _active_capture_pids
  1212. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  1213. # Any ffmpeg with rtsp(s)://bblp: that is NOT in an active stream is orphaned.
  1214. for pid in _scan_bambu_ffmpeg_pids():
  1215. if pid in active_pids:
  1216. continue
  1217. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  1218. try:
  1219. os.kill(pid, signal.SIGKILL)
  1220. except (ProcessLookupError, OSError):
  1221. pass
  1222. _spawned_ffmpeg_pids.pop(pid, None)
  1223. cleaned += 1
  1224. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1225. for pid in list(_spawned_ffmpeg_pids):
  1226. try:
  1227. os.kill(pid, 0) # existence check
  1228. except (ProcessLookupError, OSError):
  1229. _spawned_ffmpeg_pids.pop(pid, None)
  1230. # 3. Clean up _active_streams entries with dead processes
  1231. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1232. for sid in dead_streams:
  1233. proc = _active_streams.pop(sid, None)
  1234. if proc:
  1235. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1236. cleaned += 1
  1237. # 4. Kill stale active streams (alive but no frames for >30s)
  1238. # Uses per-stream timestamps to avoid false "fresh" readings from newer streams
  1239. for sid, proc in list(_active_streams.items()):
  1240. if proc.returncode is not None:
  1241. continue
  1242. # Per-stream frame time is authoritative; fall back to per-printer
  1243. stream_last_frame = _stream_last_frame_times.get(sid)
  1244. if stream_last_frame is None:
  1245. try:
  1246. printer_id = int(sid.split("-", 1)[0])
  1247. except (ValueError, IndexError):
  1248. continue
  1249. stream_last_frame = _last_frame_times.get(printer_id)
  1250. spawn_time = _spawned_ffmpeg_pids.get(proc.pid, now)
  1251. if stream_last_frame is None:
  1252. stream_last_frame = spawn_time
  1253. if now - spawn_time > 60 and now - stream_last_frame > 30:
  1254. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - stream_last_frame)
  1255. # Signal the generator to stop reconnecting
  1256. event = _disconnect_events.get(sid)
  1257. if event:
  1258. event.set()
  1259. try:
  1260. proc.kill()
  1261. await proc.wait()
  1262. except (ProcessLookupError, OSError):
  1263. pass
  1264. _active_streams.pop(sid, None)
  1265. _disconnect_events.pop(sid, None)
  1266. _stream_last_frame_times.pop(sid, None)
  1267. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1268. cleaned += 1
  1269. # 4. Clean stale chamber stream entries
  1270. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1271. for sid in dead_chamber:
  1272. _active_chamber_streams.pop(sid, None)
  1273. cleaned += 1
  1274. if cleaned:
  1275. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)