camera.py 58 KB

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