camera.py 91 KB

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