camera.py 100 KB

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