camera.py 98 KB

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