camera.py 42 KB

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