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