camera.py 91 KB

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