camera.py 100 KB

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