camera.py 97 KB

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