camera.py 60 KB

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