camera.py 42 KB

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