camera.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. """Camera capture service for Bambu Lab printers.
  2. Supports two camera protocols:
  3. - RTSP: Used by X1, X1C, X1E, X2D, H2C, H2D, H2DPRO, H2S, P2S (port 322)
  4. - Chamber Image: Used by A1, A1MINI, P1P, P1S (port 6000, custom binary protocol)
  5. """
  6. import asyncio
  7. import functools
  8. import logging
  9. import os
  10. import shutil
  11. import ssl
  12. import struct
  13. import subprocess
  14. import uuid
  15. import weakref
  16. from datetime import datetime
  17. from pathlib import Path
  18. from backend.app.utils.ffmpeg_output import NO_FFMPEG_OUTPUT, summarize_ffmpeg_stderr
  19. logger = logging.getLogger(__name__)
  20. # JPEG markers
  21. JPEG_START = b"\xff\xd8"
  22. JPEG_END = b"\xff\xd9"
  23. # Cache the ffmpeg path after first lookup
  24. _ffmpeg_path: str | None = None
  25. # Cached result of rtsp_socket_timeout_flag(); see that function for context.
  26. _rtsp_socket_timeout_flag: str | None = None
  27. # Track PIDs of ffmpeg processes spawned for one-shot frame capture (snapshot).
  28. # The cleanup task in routes/camera.py checks this set to avoid killing active captures.
  29. _active_capture_pids: set[int] = set()
  30. # In-flight one-shot captures, keyed by printer IP (#2705).
  31. #
  32. # Bambu firmware allows exactly one camera connection, and the existing guards
  33. # (is_stream_active / try_get_active_buffered_frame, #1271 + #1348) only stop a
  34. # capturer from competing with the fan-out BROADCASTER. They do nothing for
  35. # capturer-vs-capturer with no viewer attached, where every consumer correctly
  36. # concludes it isn't competing with a viewer and then collides with the others.
  37. # Eight paths reach capture_camera_frame_bytes() independently — Obico polling,
  38. # /camera/snapshot, the finish-photo moment and its disk-writing sibling, plate
  39. # detection, the camera test and the diagnose tool — so the single-flight lives
  40. # at the bottom of the stack and needs no call-site changes.
  41. #
  42. # Keyed by IP rather than printer_id because IP is what the firmware's one-
  43. # connection limit applies to: two printer rows pointing at the same address
  44. # still share one camera. (This function never sees a printer_id anyway.) The
  45. # key deliberately excludes the timeout, or callers that disagree about it —
  46. # and they all do, from 10s to 30s — would never coalesce, which is exactly
  47. # the Obico-vs-snapshot pair from the report.
  48. _inflight_captures: dict[str, asyncio.Task[bytes | None]] = {}
  49. # In-flight connection handlers for each live TLS proxy server (#3001).
  50. #
  51. # This belongs on the server object, and for one release it lived there as an
  52. # instance attribute. That works on asyncio's own Server and raises
  53. # AttributeError on uvloop's, which is a Cython cdef class with no __dict__.
  54. # Every launch path this repo ships pins --loop asyncio (added for #1896), so
  55. # none of them could hit it -- but requirements.txt pins uvicorn[standard],
  56. # which installs uvloop, so anything launched without that flag gets uvloop
  57. # from --loop auto and loses every RTSP camera. That is real deployments: the
  58. # Proxmox VE Helper-Scripts LXC writes its own unit, and native installs
  59. # predating the #1896 pin never get it either, since update.sh does not rewrite
  60. # unit files. So the loop is not ours to assume, and this must not depend on it.
  61. # The test suite could not see it either: conftest builds the loop from the
  62. # default policy, so it only ever exercised the loop where the assignment is
  63. # legal.
  64. #
  65. # Keyed weakly so a server that is dropped without close_tls_proxy() -- an
  66. # exception between create and close -- takes its entry with it. Keying on
  67. # id(server) instead would leak those entries forever and, worse, hand a later
  68. # server a dead one's handler set once CPython recycles the address.
  69. _proxy_handlers: "weakref.WeakKeyDictionary[asyncio.Server, set[asyncio.Task]]" = weakref.WeakKeyDictionary()
  70. def get_ffmpeg_path() -> str | None:
  71. """Find the ffmpeg executable path.
  72. Uses shutil.which first, then checks common installation locations
  73. for systems where PATH may be limited (e.g., systemd services).
  74. """
  75. global _ffmpeg_path
  76. if _ffmpeg_path is not None:
  77. return _ffmpeg_path
  78. # Try PATH first
  79. ffmpeg_path = shutil.which("ffmpeg")
  80. # If not found via PATH, check common installation locations
  81. if ffmpeg_path is None:
  82. common_paths = [
  83. "/usr/bin/ffmpeg",
  84. "/usr/local/bin/ffmpeg",
  85. "/opt/homebrew/bin/ffmpeg", # macOS Homebrew
  86. "/snap/bin/ffmpeg", # Ubuntu Snap
  87. "C:\\ffmpeg\\bin\\ffmpeg.exe", # Windows common
  88. ]
  89. for path in common_paths:
  90. if Path(path).exists():
  91. ffmpeg_path = path
  92. break
  93. _ffmpeg_path = ffmpeg_path
  94. if ffmpeg_path:
  95. logger.info("Found ffmpeg at: %s", ffmpeg_path)
  96. else:
  97. logger.warning("ffmpeg not found in PATH or common locations")
  98. return ffmpeg_path
  99. def rtsp_socket_timeout_flag() -> str:
  100. """Return the ffmpeg argv flag (without the leading dash) that sets the
  101. RTSP demuxer's client-side TCP socket I/O timeout, in microseconds.
  102. ffmpeg has shipped three different option arrangements for this over
  103. time, and Bambuddy supports the full range:
  104. - **Modern ffmpeg (5.x / 6.x / 7.x)** — Debian 13, Ubuntu 24.04, current
  105. Homebrew, etc. ``-timeout`` is the socket I/O timeout (microseconds);
  106. ``-stimeout`` was REMOVED.
  107. - **Transitional ffmpeg (~late-4.x, some 5.x builds)** — Ubuntu 22.04's
  108. shipped version is one of these. ``-timeout`` was deprecated and
  109. *repurposed* to mean the RTSP listen-mode incoming-connection
  110. timeout — and any non-zero value implies ``-listen``, which makes
  111. ffmpeg bind the localhost proxy port and fail with EADDRINUSE
  112. (#1504). ``-stimeout`` was the replacement socket I/O timeout in
  113. that window.
  114. - **Old ffmpeg (early 4.x and earlier)** — ``-timeout`` is socket I/O
  115. timeout (the original meaning, before the deprecation churn).
  116. We probe ``-h demuxer=rtsp`` once and cache: if ``-stimeout`` is
  117. advertised, prefer it (covers the transitional window and stays
  118. correct on the older builds that still accept it as an alias); else
  119. fall back to ``-timeout`` (correct on modern and pre-deprecation
  120. ffmpeg). The result is cached for the process lifetime — ffmpeg
  121. isn't going to swap mid-run.
  122. Returns the option name without the leading dash, e.g. ``"timeout"``
  123. or ``"stimeout"``. Callers must prepend ``-`` themselves so a string
  124. formatting bug can't pass an empty flag.
  125. """
  126. global _rtsp_socket_timeout_flag
  127. if _rtsp_socket_timeout_flag is not None:
  128. return _rtsp_socket_timeout_flag
  129. ffmpeg = get_ffmpeg_path()
  130. chosen = "timeout" # safe default for modern ffmpeg
  131. if ffmpeg:
  132. try:
  133. result = subprocess.run(
  134. [ffmpeg, "-hide_banner", "-h", "demuxer=rtsp"],
  135. capture_output=True,
  136. text=True,
  137. timeout=5,
  138. check=False,
  139. )
  140. help_text = (result.stdout or "") + (result.stderr or "")
  141. # Help lines list each option as `-<name> ` (trailing space) — match
  142. # that exact form so we don't accidentally hit a substring elsewhere.
  143. if "-stimeout " in help_text:
  144. chosen = "stimeout"
  145. except (OSError, subprocess.SubprocessError) as exc:
  146. # If probing fails, keep the modern-ffmpeg default. Worst case
  147. # is the EADDRINUSE regression returns for transitional-ffmpeg
  148. # users — same as before this function existed.
  149. logger.warning("Could not probe ffmpeg RTSP timeout flag, defaulting to -timeout: %s", exc)
  150. _rtsp_socket_timeout_flag = chosen
  151. logger.info("RTSP socket I/O timeout flag: -%s", chosen)
  152. return chosen
  153. def supports_rtsp(model: str | None) -> bool:
  154. """Check if printer model supports RTSP camera streaming.
  155. RTSP supported: X1, X1C, X1E, X2D, H2C, H2D, H2DPRO, H2S, P2S
  156. Chamber image only: A1, A1MINI, P1P, P1S
  157. Note: Model can be either display name (e.g., "P2S") or internal code (e.g., "N7").
  158. Internal codes from MQTT/SSDP:
  159. - BL-P001: X1/X1C
  160. - C13: X1E
  161. - N6: X2D
  162. - O1D: H2D
  163. - O1C, O1C2: H2C
  164. - O1S: H2S
  165. - O1E, O2D: H2D Pro
  166. - N7: P2S
  167. """
  168. if model:
  169. model_upper = model.upper()
  170. # Display names: X1, X1C, X1E, X2D, H2C, H2D, H2DPRO, H2S, P2S
  171. if model_upper.startswith(("X1", "X2", "H2", "P2")):
  172. return True
  173. # Internal codes for RTSP models
  174. if model_upper in ("BL-P001", "C13", "N6", "O1D", "O1C", "O1C2", "O1S", "O1E", "O2D", "N7"):
  175. return True
  176. # A1/P1 and unknown models use chamber image protocol
  177. return False
  178. def get_camera_port(model: str | None) -> int:
  179. """Get the camera port based on printer model.
  180. X1/X2/H2/P2 series use RTSP on port 322.
  181. A1/P1 series use chamber image protocol on port 6000.
  182. """
  183. if supports_rtsp(model):
  184. return 322
  185. return 6000
  186. def rewrite_rtsp_request_url(data: bytes, proxy_url: bytes, real_url: bytes) -> bytes:
  187. """Rewrite RTSP request-line URLs, leaving other lines (e.g. Authorization) intact.
  188. RTSP request lines have the form ``METHOD <url> RTSP/1.0\\r\\n``.
  189. Only those lines are modified so that Digest auth headers (which embed
  190. the original URL and a cryptographic hash) are not broken.
  191. """
  192. rtsp_marker = b" RTSP/1.0"
  193. if rtsp_marker not in data:
  194. return data
  195. lines = data.split(b"\r\n")
  196. for i, line in enumerate(lines):
  197. if line.endswith(rtsp_marker):
  198. lines[i] = line.replace(proxy_url, real_url)
  199. break
  200. return b"\r\n".join(lines)
  201. async def create_tls_proxy(target_host: str, target_port: int) -> tuple[int, "asyncio.Server"]:
  202. """Create a local TCP→TLS proxy for RTSP streams.
  203. Bambu printers use RTSPS (RTSP over TLS) with self-signed certificates.
  204. The Debian ffmpeg package uses GnuTLS, whose hardened defaults reject
  205. certain TLS behaviors (renegotiation, legacy ciphers) that some printer
  206. firmwares (notably P2S) rely on. This causes streams to drop after a
  207. few seconds.
  208. This proxy terminates TLS using Python's ssl module (OpenSSL), which is
  209. more permissive, and exposes a plain TCP port that ffmpeg connects to
  210. with ``rtsp://`` instead of ``rtsps://``.
  211. RTSP embeds URLs in protocol messages (DESCRIBE, SETUP, PLAY). The proxy
  212. rewrites ``127.0.0.1:<proxy_port>`` → ``<target_host>:<target_port>`` in
  213. client→server data so the printer recognises the stream path.
  214. Returns ``(local_port, server)``. Caller must close it with
  215. :func:`close_tls_proxy` when done.
  216. """
  217. ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  218. ssl_ctx.check_hostname = False
  219. ssl_ctx.verify_mode = ssl.CERT_NONE
  220. # Filled in after the server socket is created (handler only runs after).
  221. _local_port: list[int] = [0]
  222. # Strong references to the in-flight connection handlers (#2968).
  223. # ``asyncio.start_server`` wraps the callback in a task and keeps only a
  224. # weak reference to it, so a handler still awaiting its two forwarders can
  225. # be garbage-collected out from under itself — which is asyncio's
  226. # "Task was destroyed but it is pending!", logged at ERROR with a traceback
  227. # pointing here and no indication that it is a teardown race rather than a
  228. # camera fault. Holding the set also gives close_tls_proxy something to
  229. # cancel, so shutdown stops depending on ffmpeg having dropped its end.
  230. # The set is published in _proxy_handlers once the server exists; see the
  231. # note there for why it is not an attribute on the server itself.
  232. handlers: set[asyncio.Task] = set()
  233. async def _handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter):
  234. current = asyncio.current_task()
  235. if current is not None:
  236. handlers.add(current)
  237. tls_writer = None
  238. try:
  239. tls_reader, tls_writer = await asyncio.wait_for(
  240. asyncio.open_connection(target_host, target_port, ssl=ssl_ctx),
  241. timeout=10.0,
  242. )
  243. # URL patterns for RTSP request-line rewriting.
  244. proxy_url = f"rtsp://127.0.0.1:{_local_port[0]}".encode()
  245. real_url = f"rtsps://{target_host}:{target_port}".encode()
  246. # Note on the broad except below: dst.write() raises RuntimeError
  247. # under uvloop when the underlying handle has already been torn
  248. # down (uvloop.loop.UVHandle._ensure_alive). asyncio's default
  249. # selector loop reports the same situation as ConnectionResetError
  250. # / OSError, so a tuple that doesn't include RuntimeError leaks the
  251. # uvloop variant up to asyncio's unhandled-exception logger
  252. # ("Unhandled exception in client_connected_cb"). The forwarders
  253. # are intentionally fire-and-forget on tear-down — once either
  254. # peer drops, both halves of the proxy should exit quietly.
  255. async def _fwd_to_server(src: asyncio.StreamReader, dst: asyncio.StreamWriter):
  256. """Forward client→server, rewriting RTSP request-line URLs only."""
  257. try:
  258. while True:
  259. data = await src.read(65536)
  260. if not data:
  261. break
  262. data = rewrite_rtsp_request_url(data, proxy_url, real_url)
  263. dst.write(data)
  264. await dst.drain()
  265. except (ConnectionError, OSError, asyncio.CancelledError, RuntimeError):
  266. pass
  267. finally:
  268. if not dst.is_closing():
  269. try:
  270. dst.close()
  271. except OSError:
  272. pass
  273. async def _fwd_to_client(src: asyncio.StreamReader, dst: asyncio.StreamWriter):
  274. """Forward server→client unchanged."""
  275. try:
  276. while True:
  277. data = await src.read(65536)
  278. if not data:
  279. break
  280. dst.write(data)
  281. await dst.drain()
  282. except (ConnectionError, OSError, asyncio.CancelledError, RuntimeError):
  283. pass
  284. finally:
  285. if not dst.is_closing():
  286. try:
  287. dst.close()
  288. except OSError:
  289. pass
  290. await asyncio.gather(
  291. _fwd_to_server(client_reader, tls_writer),
  292. _fwd_to_client(tls_reader, client_writer),
  293. )
  294. except (ConnectionError, OSError, TimeoutError) as e:
  295. logger.debug("TLS proxy connection to %s:%s failed: %s", target_host, target_port, e)
  296. except asyncio.CancelledError:
  297. # close_tls_proxy cancelling us at shutdown, which is the only thing
  298. # that cancels this task. Swallowing a cancellation is normally
  299. # wrong because it hides the request from whoever made it; here we
  300. # *are* whoever made it, the cleanup it exists to trigger is in the
  301. # finally below, and nothing awaits this task's result. Asyncio's
  302. # own done-callback for a connection handler treats a cancelled task
  303. # differently from a completed one, so ending in the ordinary way
  304. # keeps the teardown on one path across Python versions.
  305. pass
  306. finally:
  307. if current is not None:
  308. handlers.discard(current)
  309. for w in (client_writer, tls_writer):
  310. if w and not w.is_closing():
  311. try:
  312. w.close()
  313. except OSError:
  314. pass
  315. server = await asyncio.start_server(_handle, "127.0.0.1", 0)
  316. _local_port[0] = server.sockets[0].getsockname()[1]
  317. _proxy_handlers[server] = handlers
  318. logger.debug("TLS proxy for %s:%s listening on 127.0.0.1:%s", target_host, target_port, _local_port[0])
  319. return _local_port[0], server
  320. async def close_tls_proxy(server: "asyncio.Server") -> None:
  321. """Shut a :func:`create_tls_proxy` server down without leaving tasks behind.
  322. ``server.close()`` stops the listener but leaves established connections
  323. running, and ``wait_closed()`` is only as deterministic as the peer: it
  324. waits for the handlers, and a handler waits for ffmpeg to drop its end of
  325. the socket. By the time this is called ffmpeg has already been reaped, so
  326. the connection is dead weight — cancelling it is both correct and the only
  327. way to guarantee no handler outlives the server that owns it.
  328. ``Server.close_clients()`` would do this natively, but it landed in Python
  329. 3.13 and Bambuddy supports 3.10, so the handler set is tracked by hand in
  330. ``_proxy_handlers``.
  331. Safe to call on any ``asyncio.Server`` from anywhere else: a server that
  332. was not created here is simply absent from the registry, and this degrades
  333. to the close/wait it replaces.
  334. """
  335. handlers: set[asyncio.Task] = _proxy_handlers.pop(server, set())
  336. server.close()
  337. for task in list(handlers):
  338. task.cancel()
  339. if handlers:
  340. await asyncio.gather(*list(handlers), return_exceptions=True)
  341. await server.wait_closed()
  342. def is_chamber_image_model(model: str | None) -> bool:
  343. """Check if printer uses chamber image protocol instead of RTSP.
  344. A1, A1MINI, P1P, P1S use the chamber image protocol on port 6000.
  345. """
  346. return not supports_rtsp(model)
  347. def build_camera_url(ip_address: str, access_code: str, model: str | None) -> str:
  348. """Build the RTSPS URL for the printer camera (RTSP models only)."""
  349. port = get_camera_port(model)
  350. return f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  351. def _create_chamber_auth_payload(access_code: str) -> bytes:
  352. """Create the 80-byte authentication payload for chamber image protocol.
  353. Format:
  354. - Bytes 0-3: 0x40 0x00 0x00 0x00 (magic)
  355. - Bytes 4-7: 0x00 0x30 0x00 0x00 (command)
  356. - Bytes 8-15: zeros (padding)
  357. - Bytes 16-47: username "bblp" (32 bytes, null-padded)
  358. - Bytes 48-79: access code (32 bytes, null-padded)
  359. """
  360. username = b"bblp"
  361. access_code_bytes = access_code.encode("utf-8")
  362. # Build the 80-byte payload
  363. payload = struct.pack(
  364. "<II8s32s32s",
  365. 0x40, # Magic header
  366. 0x3000, # Command
  367. b"\x00" * 8, # Padding
  368. username.ljust(32, b"\x00"), # Username padded to 32 bytes
  369. access_code_bytes.ljust(32, b"\x00"), # Access code padded to 32 bytes
  370. )
  371. return payload
  372. def _create_ssl_context() -> ssl.SSLContext:
  373. """Create an SSL context for chamber image connection.
  374. Bambu printers use self-signed certificates, so we disable verification.
  375. """
  376. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  377. ctx.check_hostname = False
  378. ctx.verify_mode = ssl.CERT_NONE
  379. return ctx
  380. async def read_chamber_image_frame(
  381. ip_address: str,
  382. access_code: str,
  383. timeout: float = 10.0,
  384. ) -> bytes | None:
  385. """Read a single JPEG frame from the chamber image protocol.
  386. This is used by A1/P1 printers which don't support RTSP.
  387. Args:
  388. ip_address: Printer IP address
  389. access_code: Printer access code
  390. timeout: Connection timeout in seconds
  391. Returns:
  392. JPEG image data or None if failed
  393. """
  394. port = 6000
  395. ssl_context = _create_ssl_context()
  396. try:
  397. # Connect with SSL
  398. reader, writer = await asyncio.wait_for(
  399. asyncio.open_connection(ip_address, port, ssl=ssl_context),
  400. timeout=timeout,
  401. )
  402. try:
  403. # Send authentication payload
  404. auth_payload = _create_chamber_auth_payload(access_code)
  405. writer.write(auth_payload)
  406. await writer.drain()
  407. # Read the 16-byte header
  408. header = await asyncio.wait_for(reader.readexactly(16), timeout=timeout)
  409. if len(header) < 16:
  410. logger.error("Chamber image: incomplete header received")
  411. return None
  412. # Parse payload size from header (little-endian uint32 at offset 0)
  413. payload_size = struct.unpack("<I", header[0:4])[0]
  414. if payload_size == 0 or payload_size > 10_000_000: # Sanity check: max 10MB
  415. logger.error("Chamber image: invalid payload size %s", payload_size)
  416. return None
  417. # Read the JPEG data
  418. jpeg_data = await asyncio.wait_for(
  419. reader.readexactly(payload_size),
  420. timeout=timeout,
  421. )
  422. # Validate JPEG markers
  423. if not jpeg_data.startswith(JPEG_START):
  424. logger.error("Chamber image: data is not a valid JPEG (missing start marker)")
  425. return None
  426. if not jpeg_data.endswith(JPEG_END):
  427. logger.warning("Chamber image: JPEG missing end marker, may be truncated")
  428. logger.debug("Chamber image: received %s bytes", len(jpeg_data))
  429. return jpeg_data
  430. finally:
  431. writer.close()
  432. try:
  433. await writer.wait_closed()
  434. except OSError:
  435. pass # Socket already closed; cleanup is best-effort
  436. except TimeoutError:
  437. logger.error("Chamber image: connection timeout to %s:%s", ip_address, port)
  438. return None
  439. except ConnectionRefusedError:
  440. logger.error("Chamber image: connection refused by %s:%s", ip_address, port)
  441. return None
  442. except Exception as e:
  443. logger.exception("Chamber image: error connecting to %s:%s: %s", ip_address, port, e)
  444. return None
  445. async def generate_chamber_image_stream(
  446. ip_address: str,
  447. access_code: str,
  448. fps: int = 5,
  449. ) -> asyncio.StreamReader | None:
  450. """Create a persistent connection for streaming chamber images.
  451. Returns a connected reader or None if connection failed.
  452. """
  453. port = 6000
  454. ssl_context = _create_ssl_context()
  455. try:
  456. reader, writer = await asyncio.wait_for(
  457. asyncio.open_connection(ip_address, port, ssl=ssl_context),
  458. timeout=10.0,
  459. )
  460. # Send authentication payload
  461. auth_payload = _create_chamber_auth_payload(access_code)
  462. writer.write(auth_payload)
  463. await writer.drain()
  464. logger.info("Chamber image: connected to %s:%s", ip_address, port)
  465. return reader, writer
  466. except Exception as e:
  467. logger.error("Chamber image: failed to connect to %s:%s: %s", ip_address, port, e)
  468. return None
  469. async def read_next_chamber_frame(reader: asyncio.StreamReader, timeout: float = 10.0) -> bytes | None:
  470. """Read the next JPEG frame from an established chamber image connection."""
  471. try:
  472. # Read the 16-byte header
  473. header = await asyncio.wait_for(reader.readexactly(16), timeout=timeout)
  474. # Parse payload size from header (little-endian uint32 at offset 0)
  475. payload_size = struct.unpack("<I", header[0:4])[0]
  476. if payload_size == 0 or payload_size > 10_000_000:
  477. logger.error("Chamber image: invalid payload size %s", payload_size)
  478. return None
  479. # Read the JPEG data
  480. jpeg_data = await asyncio.wait_for(
  481. reader.readexactly(payload_size),
  482. timeout=timeout,
  483. )
  484. return jpeg_data
  485. except asyncio.IncompleteReadError:
  486. logger.warning("Chamber image: connection closed by printer")
  487. return None
  488. except TimeoutError:
  489. logger.warning("Chamber image: read timeout")
  490. return None
  491. except Exception as e:
  492. logger.error("Chamber image: error reading frame: %s", e)
  493. return None
  494. async def capture_camera_frame(
  495. ip_address: str,
  496. access_code: str,
  497. model: str | None,
  498. output_path: Path,
  499. timeout: int = 30,
  500. ) -> bool:
  501. """Capture a single frame from the printer's camera stream and save to disk.
  502. Uses capture_camera_frame_bytes() internally for protocol selection,
  503. then writes the result to the specified output path.
  504. Args:
  505. ip_address: Printer IP address
  506. access_code: Printer access code
  507. model: Printer model (X1, H2D, P1, A1, etc.)
  508. output_path: Path where to save the captured image
  509. timeout: Timeout in seconds for the capture operation
  510. Returns:
  511. True if capture was successful, False otherwise
  512. """
  513. output_path.parent.mkdir(parents=True, exist_ok=True)
  514. jpeg_data = await capture_camera_frame_bytes(ip_address, access_code, model, timeout)
  515. if jpeg_data:
  516. try:
  517. with open(output_path, "wb") as f:
  518. f.write(jpeg_data)
  519. logger.info("Saved camera frame to: %s", output_path)
  520. return True
  521. except OSError as e:
  522. logger.error("Failed to write camera frame: %s", e)
  523. return False
  524. return False
  525. def capture_in_flight(ip_address: str) -> bool:
  526. """Return True iff a one-shot capture for this IP is running right now.
  527. For callers that need to know whether they will JOIN someone else's
  528. capture rather than perform their own — currently only the diagnose tool,
  529. which reports on what it measured and so must not present a coalesced
  530. frame as proof that it opened its own connection (see camera_diagnose).
  531. Ordinary consumers should ignore this: they want "a recent frame", and
  532. capture_camera_frame_bytes() already does the right thing for them.
  533. """
  534. task = _inflight_captures.get(ip_address)
  535. return task is not None and not task.done()
  536. def _discard_inflight_capture(ip_address: str, task: asyncio.Task) -> None:
  537. """Done-callback: drop the finished task from the in-flight registry.
  538. Guarded on identity so a slow task that finishes after a newer capture
  539. has registered can't evict its successor.
  540. Also retrieves the exception, if any. The leader normally awaits the task
  541. and would surface it, but a leader whose own caller was cancelled leaves
  542. nobody to collect it — and an unretrieved task exception is logged by
  543. asyncio as a warning with a traceback at an arbitrary later point.
  544. """
  545. if _inflight_captures.get(ip_address) is task:
  546. del _inflight_captures[ip_address]
  547. if not task.cancelled() and task.exception() is not None:
  548. logger.debug("In-flight camera capture for %s ended in an exception", ip_address)
  549. async def capture_camera_frame_bytes(
  550. ip_address: str,
  551. access_code: str,
  552. model: str | None,
  553. timeout: int = 15,
  554. ) -> bytes | None:
  555. """Capture a single frame and return as JPEG bytes (no disk write).
  556. Concurrent callers for the same printer share one capture (#2705): the
  557. first opens the connection, everyone arriving while it is in flight awaits
  558. the same result. Every consumer here wants "a recent frame" rather than
  559. "a frame captured at exactly my timestamp", so handing identical bytes to
  560. simultaneous callers is correct — and it is the only way to honour the
  561. firmware's one-connection limit without serialising captures behind a lock
  562. (which would just turn a collision into a queue).
  563. This coalesces; it does not cache. A call that arrives after the previous
  564. capture finished always captures fresh. Two consumers of these frames —
  565. plate detection and the finish-photo path — decide things about a running
  566. print from them, and a stale frame there is worse than a slow one: the
  567. whole of #1397 was a finish photo taken seconds late showing the bed
  568. already lowered.
  569. Args:
  570. ip_address: Printer IP address
  571. access_code: Printer access code
  572. model: Printer model (X1, H2D, P1, A1, etc.)
  573. timeout: Timeout in seconds for the capture operation. Applies to this
  574. caller's own wait, including when it joins another caller's
  575. capture — the call sites disagree about the value (10s for plate
  576. detection, 20s for Obico), and a follower must not silently
  577. inherit the leader's deadline in either direction.
  578. Returns:
  579. JPEG bytes if capture was successful, None otherwise
  580. """
  581. # A follower whose leader fails takes a turn of its own rather than
  582. # inheriting a failure it never had a chance to avoid — by then the leader
  583. # has finished, so there is no socket left to compete with. Bounded at two
  584. # rounds: if the capture we joined AND its replacement both failed, a third
  585. # connection won't help, and this caller has already spent its patience.
  586. for _ in range(2):
  587. leader = _inflight_captures.get(ip_address)
  588. if leader is None or leader.done():
  589. break
  590. try:
  591. frame = await asyncio.wait_for(asyncio.shield(leader), timeout=timeout)
  592. except TimeoutError:
  593. # shield() keeps the capture running for whoever else is still
  594. # waiting on it — giving up is this caller's decision alone.
  595. logger.warning(
  596. "Gave up waiting %ss on the in-flight camera capture for %s",
  597. timeout,
  598. ip_address,
  599. )
  600. return None
  601. except asyncio.CancelledError:
  602. # Distinguish "the capture I joined was cancelled" from "I was
  603. # cancelled". Only the former is ours to recover from.
  604. if not leader.cancelled():
  605. raise
  606. logger.info("In-flight camera capture for %s was cancelled; capturing our own", ip_address)
  607. continue
  608. if frame is not None:
  609. logger.info(
  610. "Reusing in-flight camera capture for %s: %s bytes (no second connection opened)",
  611. ip_address,
  612. len(frame),
  613. )
  614. return frame
  615. logger.info("In-flight camera capture for %s failed; capturing our own", ip_address)
  616. else:
  617. return None
  618. task = asyncio.create_task(_capture_camera_frame_bytes_uncoalesced(ip_address, access_code, model, timeout))
  619. _inflight_captures[ip_address] = task
  620. task.add_done_callback(functools.partial(_discard_inflight_capture, ip_address))
  621. # No wait_for here: this caller IS the capture, and the implementation
  622. # already enforces `timeout` internally where it can also kill the ffmpeg
  623. # process. A second deadline on top would abandon the subprocess instead.
  624. # shield() so that a cancelled leader (a client navigating away mid-
  625. # snapshot is routine) doesn't take the capture down with it — the
  626. # followers already waiting on it still get their frame.
  627. return await asyncio.shield(task)
  628. async def _capture_camera_frame_bytes_uncoalesced(
  629. ip_address: str,
  630. access_code: str,
  631. model: str | None,
  632. timeout: int = 15,
  633. ) -> bytes | None:
  634. """Open a connection and capture one frame. See capture_camera_frame_bytes.
  635. Callers want that wrapper, not this: it opens a socket unconditionally,
  636. which is the collision #2705 is about.
  637. """
  638. # Chamber image models: A1/P1 - returns bytes directly
  639. if is_chamber_image_model(model):
  640. logger.info("Capturing camera frame bytes from %s using chamber image protocol (model: %s)", ip_address, model)
  641. return await read_chamber_image_frame(ip_address, access_code, timeout=float(timeout))
  642. # RTSP models: X1/H2/P2 - use ffmpeg piping to stdout
  643. # TLS proxy avoids GnuTLS compatibility issues with some printer firmwares
  644. port = get_camera_port(model)
  645. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  646. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  647. ffmpeg = get_ffmpeg_path()
  648. if not ffmpeg:
  649. await close_tls_proxy(proxy_server)
  650. logger.error("ffmpeg not found for camera frame capture")
  651. return None
  652. cmd = [
  653. ffmpeg,
  654. "-y",
  655. "-rtsp_transport",
  656. "tcp",
  657. "-rtsp_flags",
  658. "prefer_tcp",
  659. "-i",
  660. camera_url,
  661. "-frames:v",
  662. "1",
  663. "-f",
  664. "image2pipe",
  665. "-vcodec",
  666. "mjpeg",
  667. "-q:v",
  668. "2",
  669. "-",
  670. ]
  671. logger.info("Capturing camera frame bytes from %s using RTSP (model: %s)", ip_address, model)
  672. process = None
  673. try:
  674. process = await asyncio.create_subprocess_exec(
  675. *cmd,
  676. stdout=asyncio.subprocess.PIPE,
  677. stderr=asyncio.subprocess.PIPE,
  678. )
  679. _active_capture_pids.add(process.pid)
  680. try:
  681. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  682. except TimeoutError:
  683. process.kill()
  684. await process.wait()
  685. logger.error("Camera frame bytes capture timed out after %ss", timeout)
  686. return None
  687. if process.returncode == 0 and stdout and len(stdout) >= 100:
  688. logger.info("Successfully captured camera frame bytes: %s bytes", len(stdout))
  689. return stdout
  690. else:
  691. # The summariser drops ffmpeg's banner and masks the access code
  692. # the RTSP input URL carries; without it this line was 200
  693. # characters of build configuration (#2968).
  694. stderr_text = summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT
  695. logger.error("ffmpeg frame bytes capture failed (code %s): %s", process.returncode, stderr_text)
  696. return None
  697. except FileNotFoundError:
  698. logger.error("ffmpeg not found for camera frame capture")
  699. return None
  700. except Exception as e:
  701. logger.exception("Camera frame bytes capture failed: %s", e)
  702. return None
  703. finally:
  704. if process is not None:
  705. _active_capture_pids.discard(process.pid)
  706. await close_tls_proxy(proxy_server)
  707. async def extract_video_last_frame(video_path: Path, output_path: Path) -> bool:
  708. """Extract the last frame of `video_path` as JPEG at `output_path`.
  709. Used to source finish photos from a Bambu timelapse. The Bambu firmware
  710. stops timelapse recording AFTER the toolhead parks but BEFORE the bed-drop
  711. end-gcode runs, so the last frame frames the finished print correctly.
  712. A live camera grab at `gcode_state=FINISH` captures the bed already
  713. lowered (#1397).
  714. Implementation: ``-update 1`` writes each decoded frame to the same
  715. output file (overwriting), so the file left on disk after ffmpeg
  716. finishes is the LAST frame. This works regardless of how short the
  717. video is — a small print's timelapse can be sub-second / sub-30 frames
  718. (one frame per layer-change capture), and the earlier ``-sseof -1.0``
  719. approach failed there because the seek went before the start of the
  720. file and ffmpeg silently returned frame 0 (empty bed at print start).
  721. Decoding every frame is fine: Bambu timelapses are short by
  722. construction (<1 minute even on hours-long prints).
  723. Returns False on missing ffmpeg, missing video, subprocess failure or
  724. timeout. Never raises.
  725. """
  726. ffmpeg = get_ffmpeg_path()
  727. if not ffmpeg:
  728. logger.warning("Cannot extract video last frame: ffmpeg not available")
  729. return False
  730. if not video_path.exists() or video_path.stat().st_size == 0:
  731. logger.warning("Cannot extract last frame: %s missing or empty", video_path)
  732. return False
  733. output_path.parent.mkdir(parents=True, exist_ok=True)
  734. cmd = [
  735. ffmpeg,
  736. "-y",
  737. "-i",
  738. str(video_path),
  739. "-q:v",
  740. "2",
  741. "-update",
  742. "1",
  743. str(output_path),
  744. ]
  745. process = None
  746. try:
  747. process = await asyncio.create_subprocess_exec(
  748. *cmd,
  749. stdout=asyncio.subprocess.PIPE,
  750. stderr=asyncio.subprocess.PIPE,
  751. )
  752. _, stderr = await asyncio.wait_for(process.communicate(), timeout=15.0)
  753. if process.returncode != 0:
  754. logger.warning(
  755. "ffmpeg failed extracting last frame from %s: %s",
  756. video_path,
  757. summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT,
  758. )
  759. return False
  760. if not output_path.exists() or output_path.stat().st_size == 0:
  761. logger.warning("ffmpeg produced no output for %s", video_path)
  762. return False
  763. return True
  764. except asyncio.TimeoutError:
  765. logger.warning("ffmpeg timed out extracting last frame from %s", video_path)
  766. if process is not None:
  767. try:
  768. process.kill()
  769. await process.wait()
  770. except ProcessLookupError:
  771. pass # Already exited
  772. return False
  773. except OSError as e:
  774. logger.warning("ffmpeg subprocess error for %s: %s", video_path, e)
  775. return False
  776. def apply_camera_rotation(image_data: bytes, rotation: int, logger: logging.Logger) -> bytes:
  777. """Apply a camera_rotation value (degrees clockwise) to a captured JPEG.
  778. Shared by every capture path that saves a still image (notification
  779. snapshots, finish photos, layer-timelapse frames) - previously only
  780. wired into the notification-snapshot path, which left finish photos
  781. and timelapse videos upside-down whenever camera_rotation was set.
  782. Returns *image_data* itself (identity, not a copy) when there is nothing
  783. to do or the rotate fails; callers that write to disk use that to skip a
  784. pointless rewrite.
  785. """
  786. if not rotation:
  787. return image_data
  788. try:
  789. from io import BytesIO
  790. from PIL import Image
  791. img = Image.open(BytesIO(image_data))
  792. # PIL rotate is counter-clockwise, so negate for clockwise rotation
  793. img = img.rotate(-rotation, expand=True)
  794. buf = BytesIO()
  795. img.save(buf, format="JPEG", quality=90)
  796. rotated = buf.getvalue()
  797. # Debug, not info: layer-timelapse calls this once per layer, so a tall
  798. # print would otherwise put hundreds of lines in the log for something
  799. # the surrounding capture already reports at debug level.
  800. logger.debug("Applied %d° camera rotation: %s → %s bytes", rotation, len(image_data), len(rotated))
  801. return rotated
  802. except Exception as e:
  803. logger.warning("Failed to apply camera rotation: %s", e)
  804. return image_data
  805. async def apply_camera_rotation_to_file(path: Path, rotation: int, logger: logging.Logger) -> None:
  806. """Rotate a JPEG that has already been written to disk, in place.
  807. Two finish-photo sources never hold the frame as bytes - ``ffmpeg`` writes
  808. the file for them, and they return only a filename - so they can't use
  809. ``apply_camera_rotation`` directly. Best-effort: any failure leaves the
  810. unrotated file in place, which is what the caller had before.
  811. """
  812. if not rotation:
  813. return
  814. try:
  815. data = await asyncio.to_thread(path.read_bytes)
  816. rotated = await asyncio.to_thread(apply_camera_rotation, data, rotation, logger)
  817. if rotated is data:
  818. # Nothing was done (the rotate failed and returned its input) -
  819. # rewriting the same bytes would only risk truncating a good file.
  820. return
  821. await asyncio.to_thread(path.write_bytes, rotated)
  822. except Exception as e:
  823. logger.warning("Failed to rotate %s in place: %s", path.name, e)
  824. async def capture_finish_photo(
  825. printer_id: int,
  826. ip_address: str,
  827. access_code: str,
  828. model: str | None,
  829. archive_dir: Path,
  830. rotation: int = 0,
  831. ) -> str | None:
  832. """Capture a finish photo and save it to the archive's photos folder.
  833. Args:
  834. printer_id: ID of the printer
  835. ip_address: Printer IP address
  836. access_code: Printer access code
  837. model: Printer model
  838. archive_dir: Directory of the archive (where the 3MF is stored)
  839. rotation: Printer's configured camera_rotation (degrees clockwise).
  840. ffmpeg writes the file directly here, so the rotation is applied
  841. to it afterwards rather than to bytes in hand.
  842. Returns:
  843. Filename of the captured photo, or None if capture failed
  844. """
  845. # Create photos subdirectory
  846. photos_dir = archive_dir / "photos"
  847. photos_dir.mkdir(parents=True, exist_ok=True)
  848. # Generate filename with timestamp
  849. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  850. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  851. output_path = (
  852. photos_dir / filename
  853. ) # SEC-PATH-OK: filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg" generated above
  854. success = await capture_camera_frame(
  855. ip_address=ip_address,
  856. access_code=access_code,
  857. model=model,
  858. output_path=output_path,
  859. timeout=30,
  860. )
  861. if success:
  862. await apply_camera_rotation_to_file(output_path, rotation, logger)
  863. logger.info("Finish photo saved: %s", filename)
  864. return filename
  865. else:
  866. logger.warning("Failed to capture finish photo for printer %s", printer_id)
  867. return None
  868. async def test_camera_connection(
  869. ip_address: str,
  870. access_code: str,
  871. model: str | None,
  872. ) -> dict:
  873. """Test if the camera stream is accessible.
  874. Returns dict with success status and any error message.
  875. """
  876. import tempfile
  877. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  878. os.close(fd)
  879. test_path = Path(tmp_name)
  880. test_path.chmod(0o600)
  881. try:
  882. success = await capture_camera_frame(
  883. ip_address=ip_address,
  884. access_code=access_code,
  885. model=model,
  886. output_path=test_path,
  887. timeout=15,
  888. )
  889. if success:
  890. return {"success": True, "message": "Camera connection successful"}
  891. else:
  892. return {
  893. "success": False,
  894. "error": (
  895. "Failed to capture frame from camera. "
  896. "Ensure the printer is powered on, camera is enabled, and Developer Mode is active. "
  897. "If running in Docker, try 'network_mode: host' in docker-compose.yml."
  898. ),
  899. }
  900. finally:
  901. # Clean up test file
  902. if test_path.exists():
  903. test_path.unlink()