external_camera.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. """External camera service.
  2. Supports MJPEG streams, RTSP streams (via ffmpeg), HTTP snapshot URLs, and USB cameras.
  3. Security Note: This service intentionally makes requests to user-configured camera URLs.
  4. This is necessary functionality for external camera integration. URLs are validated
  5. to ensure they are well-formed before use.
  6. """
  7. import asyncio
  8. import contextlib
  9. import functools
  10. import ipaddress
  11. import logging
  12. import re
  13. import shutil
  14. import socket
  15. import time
  16. import zlib
  17. from collections.abc import AsyncGenerator, Callable
  18. from pathlib import Path
  19. from urllib.parse import urljoin, urlparse
  20. import aiohttp
  21. from backend.app.core.logging_filters import redact_url_credentials
  22. from backend.app.utils.ffmpeg_output import (
  23. FFMPEG_RTSP_LOGLEVEL,
  24. NO_FFMPEG_OUTPUT,
  25. read_ffmpeg_log_until_open,
  26. summarize_ffmpeg_stderr,
  27. watch_ffmpeg_log,
  28. )
  29. logger = logging.getLogger(__name__)
  30. # Protocols ffmpeg may use for an RTSP input. RTSP negotiates its media
  31. # transport at runtime, so the transports have to be here alongside rtsp itself;
  32. # tls and crypto cover encrypted variants. Everything ffmpeg would otherwise
  33. # accept behind an -i — file, http, tcp to anywhere, concat — is left out, so a
  34. # stream that references something outside itself cannot pull it in.
  35. _RTSP_PROTOCOL_WHITELIST = "rtsp,rtp,udp,tcp,tls,crypto"
  36. def _blocked_host_reason(hostname: str) -> str | None:
  37. """Describe why *hostname* is a destination we refuse to fetch, or None to allow it.
  38. Camera URLs are user-supplied and reach the network — over aiohttp for the
  39. HTTP types, and as an ``ffmpeg -i`` argument for RTSP — so this is where the
  40. SSRF boundary sits. LAN addresses are deliberately allowed: cameras live on
  41. the same network as Bambuddy, and blocking RFC-1918 would remove the feature
  42. rather than protect it. What is left to refuse is the host talking to
  43. itself, the unspecified address, link-local (which is where the cloud
  44. metadata endpoint lives), and the metadata hostnames.
  45. IP literals are classified with ``ipaddress`` rather than compared against a
  46. list of spellings, because 127.0.0.1, 127.0.0.2, 2130706433, 0177.0.0.1,
  47. 127.1 and ::ffff:127.0.0.1 all arrive at loopback and a list of strings only
  48. ever catches whichever one someone thought to write down. ``inet_aton``
  49. comes first because it accepts the legacy octal, decimal and short forms
  50. that ``ip_address`` rejects — the C resolvers behind aiohttp and ffmpeg
  51. accept them, so refusing to understand them here would only mean not seeing
  52. where the request is actually going.
  53. """
  54. from backend.app.api.routes._url_safety import CLOUD_METADATA_HOSTNAMES, CLOUD_METADATA_IPS, unwrap_ipv4_mapped
  55. # A trailing dot names the same host to every resolver.
  56. host = hostname.lower().rstrip(".")
  57. # The HTTP clients map other dot characters, fullwidth digits and similar
  58. # forms to plain ASCII before they connect: a host not written in ASCII
  59. # cannot be judged here, so it is refused.
  60. if not host.isascii():
  61. return "a host name not written in ASCII (use punycode, xn--...)"
  62. ip: ipaddress.IPv4Address | ipaddress.IPv6Address | None = None
  63. try:
  64. ip = ipaddress.ip_address(socket.inet_aton(host))
  65. except OSError:
  66. try:
  67. ip = ipaddress.ip_address(host)
  68. except ValueError:
  69. ip = None
  70. if ip is None:
  71. # A name, not an address. It is not resolved here on purpose: aiohttp
  72. # and ffmpeg each resolve independently afterwards, so a check here
  73. # decides nothing about where they end up (DNS rebinding), while a
  74. # lookup on every capture would break LAN cameras behind slow or
  75. # intermittent local DNS.
  76. if host == "localhost" or host.endswith(".localhost"):
  77. return "localhost"
  78. if host in CLOUD_METADATA_HOSTNAMES:
  79. return "a cloud metadata service"
  80. return None
  81. # ::ffff:127.0.0.1 is loopback wearing an IPv6 spelling, and a zone id
  82. # only hides the address it is attached to.
  83. ip = unwrap_ipv4_mapped(ip)
  84. if ip in CLOUD_METADATA_IPS:
  85. return "a cloud metadata service"
  86. if ip.is_loopback:
  87. return "loopback"
  88. if ip.is_unspecified:
  89. return "the unspecified address"
  90. if ip.is_link_local:
  91. return "a link-local address (the cloud metadata range)"
  92. return None
  93. def _sanitize_camera_url(url: str, allowed_schemes: tuple[str, ...] = ("http", "https", "rtsp")) -> str | None:
  94. """Validate and sanitize camera URL, returning a safe reconstructed URL.
  95. This validates that the URL is well-formed, uses an allowed scheme, does not
  96. target the host itself or a cloud metadata service, and returns a URL
  97. reconstructed from the validated components.
  98. Note: This intentionally allows user-provided URLs as that is the
  99. purpose of external camera configuration. Local network IPs are
  100. allowed since cameras are typically on the same LAN.
  101. Args:
  102. url: URL to validate and sanitize
  103. allowed_schemes: Tuple of allowed URL schemes
  104. Returns:
  105. Sanitized URL string if valid, None otherwise
  106. """
  107. try:
  108. parsed = urlparse(url)
  109. if not parsed.scheme or not parsed.netloc:
  110. return None
  111. # Validate scheme against allowlist
  112. scheme = parsed.scheme.lower()
  113. if scheme not in allowed_schemes:
  114. return None
  115. hostname = parsed.hostname or ""
  116. if not hostname:
  117. return None
  118. blocked = _blocked_host_reason(hostname)
  119. if blocked:
  120. logger.warning("Blocked camera URL targeting %s: %s", blocked, hostname)
  121. return None
  122. # Reconstruct URL from validated components to break taint chain
  123. # This creates a new string from validated parts
  124. #
  125. # The credentials are carried across verbatim from netloc rather than
  126. # via parsed.username/.password, which urlparse has already percent-
  127. # decoded: re-emitting those would corrupt any password containing an
  128. # @ or a :. They have to survive at all because most RTSP cameras — and
  129. # a fair number of MJPEG ones — carry their login in the URL, and
  130. # dropping it turns every one of them into an authentication failure.
  131. netloc = parsed.netloc
  132. userinfo = f"{netloc.rsplit('@', 1)[0]}@" if "@" in netloc else ""
  133. # parsed.hostname has already stripped the brackets off an IPv6 literal;
  134. # without them back the result is not a URL any client can parse.
  135. host_str = f"[{hostname}]" if ":" in hostname else hostname
  136. port_str = f":{parsed.port}" if parsed.port else ""
  137. path = parsed.path or ""
  138. query = f"?{parsed.query}" if parsed.query else ""
  139. fragment = f"#{parsed.fragment}" if parsed.fragment else ""
  140. # Build sanitized URL from validated components
  141. sanitized = f"{scheme}://{userinfo}{host_str}{port_str}{path}{query}{fragment}"
  142. return sanitized
  143. except ValueError:
  144. return None
  145. def list_usb_cameras() -> list[dict]:
  146. """List available USB cameras (V4L2 devices on Linux).
  147. Returns:
  148. List of dicts with {device: str, name: str, capabilities: list}
  149. """
  150. cameras = []
  151. video_devices = sorted(Path("/dev").glob("video*"))
  152. for device in video_devices:
  153. device_path = str(device)
  154. info = {"device": device_path, "name": device.name, "capabilities": []}
  155. # Try to get device info via v4l2-ctl
  156. v4l2_ctl = shutil.which("v4l2-ctl")
  157. if v4l2_ctl:
  158. import subprocess
  159. try:
  160. result = subprocess.run(
  161. [v4l2_ctl, "-d", device_path, "--info"],
  162. capture_output=True,
  163. text=True,
  164. timeout=5,
  165. )
  166. if result.returncode == 0:
  167. # Parse device name from output
  168. for line in result.stdout.splitlines():
  169. if "Card type" in line:
  170. info["name"] = line.split(":", 1)[1].strip()
  171. elif "Driver name" in line:
  172. info["driver"] = line.split(":", 1)[1].strip()
  173. # Check if device supports video capture
  174. result = subprocess.run(
  175. [v4l2_ctl, "-d", device_path, "--list-formats"],
  176. capture_output=True,
  177. text=True,
  178. timeout=5,
  179. )
  180. if result.returncode == 0 and result.stdout.strip():
  181. info["capabilities"].append("capture")
  182. # Parse available formats
  183. formats = re.findall(r"'(\w+)'", result.stdout)
  184. info["formats"] = list(set(formats))
  185. except (subprocess.TimeoutExpired, Exception) as e:
  186. logger.debug("v4l2-ctl failed for %s: %s", device_path, e)
  187. # Only include devices that look like video capture devices
  188. # Skip metadata devices (typically odd numbered like video1, video3)
  189. try:
  190. device_num = int(device.name.replace("video", ""))
  191. # Even numbered devices are usually capture, odd are metadata
  192. # But also check if we got capabilities
  193. if info.get("capabilities") or device_num % 2 == 0:
  194. cameras.append(info)
  195. except ValueError:
  196. cameras.append(info)
  197. return cameras
  198. def get_ffmpeg_path() -> str | None:
  199. """Get the path to ffmpeg executable."""
  200. # Try shutil.which first
  201. path = shutil.which("ffmpeg")
  202. if path:
  203. return path
  204. # Check common locations (systemd services may have limited PATH)
  205. for common_path in ["/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/opt/homebrew/bin/ffmpeg"]:
  206. if Path(common_path).exists():
  207. return common_path
  208. return None
  209. # In-flight one-shot captures, keyed by (url, camera_type, snapshot_url) —
  210. # the tuple that actually identifies the physical resource being contended
  211. # (#2707 comment thread, following #2705's shape for the built-in path).
  212. #
  213. # V4L2 USB devices allow exactly one open handle, and is_stream_active() /
  214. # try_get_active_buffered_frame() (#2707) only stop a one-shot capturer from
  215. # competing with the fan-out live view. They do nothing for capturer-vs-
  216. # capturer with no viewer attached, where every consumer correctly concludes
  217. # it isn't competing with a viewer and then collides with the others -
  218. # exactly the #2705 report, just for this module's callers instead of
  219. # capture_camera_frame_bytes()'s (Obico polling, the in-print frame bank,
  220. # the finish-photo moment, plate detection, and the notification snapshot
  221. # all reach capture_frame() independently).
  222. #
  223. # snapshot_url is part of the key (not just url/camera_type) because it
  224. # routes to a completely different endpoint (#1177) - two printers that
  225. # share a camera_url but differ only in snapshot_url must not coalesce.
  226. _inflight_captures: dict[tuple[str, str, str | None], asyncio.Task[bytes | None]] = {}
  227. def capture_in_flight(url: str, camera_type: str, snapshot_url: str | None = None) -> bool:
  228. """Return True iff a one-shot capture for this key is running right now.
  229. Mirrors camera.py's capture_in_flight() for the built-in path - for a
  230. caller that needs to know it will JOIN someone else's capture rather
  231. than open its own connection. Ordinary consumers should ignore this:
  232. they want "a recent frame", and capture_frame() already does the right
  233. thing for them.
  234. """
  235. task = _inflight_captures.get((url, camera_type, snapshot_url))
  236. return task is not None and not task.done()
  237. def _discard_inflight_capture(key: tuple[str, str, str | None], task: asyncio.Task) -> None:
  238. """Done-callback: drop the finished task from the in-flight registry.
  239. Guarded on identity so a slow task that finishes after a newer capture
  240. has registered for the same key can't evict its successor.
  241. Also retrieves the exception, if any: the leader normally awaits the
  242. task and would surface it, but a leader whose own caller was cancelled
  243. leaves nobody to collect it, and an unretrieved task exception is
  244. logged by asyncio as a warning with a traceback at an arbitrary later
  245. point otherwise.
  246. """
  247. if _inflight_captures.get(key) is task:
  248. del _inflight_captures[key]
  249. if not task.cancelled() and task.exception() is not None:
  250. logger.debug("In-flight external-camera capture for %s ended in an exception", _log_key(key))
  251. def _log_key(key: tuple[str, str, str | None]) -> str:
  252. """Render an in-flight key for a log line, with credentials redacted.
  253. Unlike camera.py's coalescing — which is keyed by IP address and so has
  254. nothing to hide — these keys carry the camera URL, and an RTSP camera URL
  255. routinely embeds ``user:pass@``. Redact before truncating: slicing first
  256. can cut the URL short of the ``@`` the pattern anchors on and leave the
  257. password in the log, which is why every other URL log in this module does
  258. it in this order.
  259. """
  260. return redact_url_credentials(key[0])[:50] if key[0] else "None"
  261. async def capture_frame(
  262. url: str,
  263. camera_type: str,
  264. timeout: int = 15,
  265. snapshot_url: str | None = None,
  266. ) -> bytes | None:
  267. """Capture single frame from external camera.
  268. Args:
  269. url: Live-stream URL (MJPEG stream, RTSP URL, HTTP snapshot URL, or USB device path).
  270. camera_type: "mjpeg", "rtsp", "snapshot", or "usb".
  271. timeout: Connection timeout in seconds. Applies to this caller's own
  272. wait, including when it joins another caller's capture - call
  273. sites disagree about the value, and a follower must not silently
  274. inherit the leader's deadline in either direction.
  275. snapshot_url: Optional override for single-frame capture. When set, fetched
  276. via plain HTTP GET regardless of `camera_type`. Bypasses MJPEG warm-up
  277. handling on sources that expose a dedicated frame endpoint (e.g. go2rtc's
  278. `/api/frame.jpeg` reliably returns a clean image while the MJPEG stream's
  279. first frame is often the encoder's stale keyframe). #1177.
  280. Returns:
  281. JPEG bytes or None on failure
  282. Concurrent callers for the same (url, camera_type, snapshot_url) share
  283. one capture (#2705-shape fix, filed for the external-camera path as a
  284. follow-up on #2707): the first opens the connection, everyone arriving
  285. while it's in flight awaits the same result. This coalesces; it does
  286. not cache - a call that arrives after the previous capture finished
  287. always captures fresh, since plate detection and the finish-photo path
  288. judge a running print from these frames and a stale one there is worse
  289. than a slow one (#1397).
  290. """
  291. key = (url, camera_type, snapshot_url)
  292. # A follower whose leader fails takes a turn of its own rather than
  293. # inheriting a failure it never had a chance to avoid - by then the
  294. # leader has finished, so there's no connection left to compete with.
  295. # Bounded at two rounds: if the capture we joined AND its replacement
  296. # both failed, a third attempt won't help, and this caller has already
  297. # spent its patience.
  298. for _ in range(2):
  299. leader = _inflight_captures.get(key)
  300. if leader is None or leader.done():
  301. break
  302. try:
  303. frame = await asyncio.wait_for(asyncio.shield(leader), timeout=timeout)
  304. except TimeoutError:
  305. # shield() keeps the capture running for whoever else is still
  306. # waiting on it - giving up is this caller's decision alone.
  307. logger.warning(
  308. "Gave up waiting %ss on the in-flight external-camera capture for %s", timeout, _log_key(key)
  309. )
  310. return None
  311. except asyncio.CancelledError:
  312. # Distinguish "the capture I joined was cancelled" from "I was
  313. # cancelled". Only the former is ours to recover from.
  314. if not leader.cancelled():
  315. raise
  316. logger.info("In-flight external-camera capture for %s was cancelled; capturing our own", _log_key(key))
  317. continue
  318. if frame is not None:
  319. logger.debug(
  320. "Reusing in-flight external-camera capture for %s: %d bytes (no second connection opened)",
  321. _log_key(key),
  322. len(frame),
  323. )
  324. return frame
  325. logger.debug("In-flight external-camera capture for %s failed; capturing our own", _log_key(key))
  326. else:
  327. return None
  328. task = asyncio.create_task(_capture_frame_uncoalesced(url, camera_type, timeout, snapshot_url))
  329. _inflight_captures[key] = task
  330. task.add_done_callback(functools.partial(_discard_inflight_capture, key))
  331. # No wait_for here: this caller IS the capture, and each dispatched
  332. # _capture_* function already enforces `timeout` internally, where it
  333. # can also kill the ffmpeg process - a second deadline on top would
  334. # abandon the subprocess instead of killing it. shield() so a cancelled
  335. # leader (a client navigating away mid-request is routine) doesn't take
  336. # the capture down with it - followers already waiting on it still get
  337. # their frame.
  338. return await asyncio.shield(task)
  339. async def _capture_frame_uncoalesced(
  340. url: str,
  341. camera_type: str,
  342. timeout: int,
  343. snapshot_url: str | None,
  344. ) -> bytes | None:
  345. """Open a connection and capture one frame. See capture_frame().
  346. Callers want that wrapper, not this: it opens a connection
  347. unconditionally, which is the collision #2705/#2707 are about.
  348. Failure is reported as ``None``, never as an exception. That is load-
  349. bearing now that captures are shared: the coalescing wrapper hands one
  350. task's outcome to every caller waiting on it, and it can only give a
  351. follower its own turn for an outcome it can recognise. An exception
  352. escaping here would instead propagate to every follower at once —
  353. turning one caller's failure into N — and none of them would retry.
  354. The per-type helpers below each catch what they expect and return None,
  355. but they catch narrowly (``aiohttp.ClientError``/``OSError``/timeouts),
  356. so this is the structural guarantee rather than one contingent on their
  357. coverage. Mirrors ``_capture_camera_frame_bytes_uncoalesced`` in
  358. camera.py, which ends in the same blanket catch for the same reason.
  359. """
  360. try:
  361. if snapshot_url:
  362. # Redact before truncating — slicing first can cut the URL short of the
  363. # ``@`` the pattern anchors on and leave the password in the log.
  364. logger.debug("capture_frame using snapshot override url=%s...", redact_url_credentials(snapshot_url)[:50])
  365. return await _capture_snapshot(snapshot_url, timeout)
  366. logger.debug(
  367. "capture_frame called: type=%s, url=%s...",
  368. camera_type,
  369. redact_url_credentials(url)[:50] if url else "None",
  370. )
  371. if camera_type == "mjpeg":
  372. return await _capture_mjpeg_frame(url, timeout)
  373. elif camera_type == "rtsp":
  374. return await _capture_rtsp_frame(url, timeout)
  375. elif camera_type == "snapshot":
  376. return await _capture_snapshot(url, timeout)
  377. elif camera_type == "usb":
  378. return await _capture_usb_frame(url, timeout)
  379. else:
  380. logger.warning("Unknown camera type: %s", camera_type)
  381. return None
  382. except asyncio.CancelledError:
  383. # Cancellation is not a capture failure and must stay distinguishable:
  384. # the wrapper checks ``leader.cancelled()`` to decide whether a
  385. # follower may take its own turn.
  386. raise
  387. except Exception:
  388. logger.exception("External camera capture failed for %s", redact_url_credentials(url)[:50] if url else "None")
  389. return None
  390. def _safe_usb_device_path(device: str) -> str | None:
  391. """Rebuild a /dev/videoN path from a validated device number, or None.
  392. Validate device path - must be /dev/videoN format where N is 0-99. This
  393. prevents path traversal by using a strict allowlist approach: the returned
  394. path is built from an integer, which cannot carry a traversal, rather than
  395. from any part of the caller's string.
  396. Returns None if the device does not exist, so a caller cannot hand ffmpeg a
  397. path to something that is not a device node.
  398. """
  399. device_match = re.match(r"^/dev/video(\d{1,2})$", device)
  400. if not device_match:
  401. logger.error("Invalid USB device path format: %s", device)
  402. return None
  403. # Convert to integer to break taint chain - integers cannot contain path traversal
  404. # lgtm[py/path-injection] - device_num is validated integer 0-99
  405. device_num = int(device_match.group(1)) # Safe: regex guarantees 1-2 digits
  406. # Construct safe path from validated integer (completely untainted)
  407. safe_device_path = Path(f"/dev/video{device_num}") # lgtm[py/path-injection]
  408. if not safe_device_path.exists():
  409. logger.error("USB device does not exist: %s", safe_device_path)
  410. return None
  411. return str(safe_device_path) # lgtm[py/path-injection]
  412. async def _capture_usb_frame(device: str, timeout: int) -> bytes | None:
  413. """Capture frame from USB camera using ffmpeg."""
  414. ffmpeg = get_ffmpeg_path()
  415. if not ffmpeg:
  416. logger.error("ffmpeg not found - required for USB camera capture")
  417. return None
  418. safe_device = _safe_usb_device_path(device)
  419. if not safe_device:
  420. return None
  421. # Use the safe path for ffmpeg - this is a hardcoded /dev/videoN path
  422. device = safe_device # lgtm[py/path-injection]
  423. # Use ffmpeg to grab a single frame from USB camera
  424. cmd = [
  425. ffmpeg,
  426. "-f",
  427. "v4l2",
  428. "-i",
  429. device,
  430. "-frames:v",
  431. "1",
  432. "-f",
  433. "image2pipe",
  434. "-vcodec",
  435. "mjpeg",
  436. "-q:v",
  437. "2",
  438. "-",
  439. ]
  440. from backend.app.services.camera import _active_capture_pids
  441. process = None
  442. try:
  443. logger.debug("Running USB capture: %s", " ".join(cmd))
  444. process = await asyncio.create_subprocess_exec(
  445. *cmd,
  446. stdout=asyncio.subprocess.PIPE,
  447. stderr=asyncio.subprocess.PIPE,
  448. )
  449. # Registered like the Bambu one-shot capture, or the orphan janitor
  450. # (routes/camera.cleanup_orphaned_streams) kills it mid-capture.
  451. _active_capture_pids.add(process.pid)
  452. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  453. if process.returncode != 0:
  454. logger.error("ffmpeg USB capture failed: %s", summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT)
  455. return None
  456. if not stdout or len(stdout) < 100:
  457. logger.error("ffmpeg returned empty or too small frame from USB camera")
  458. return None
  459. return stdout
  460. except TimeoutError:
  461. logger.warning("USB frame capture timed out after %ss", timeout)
  462. if process:
  463. process.kill()
  464. await process.wait()
  465. return None
  466. except OSError as e:
  467. logger.error("USB frame capture failed: %s", e)
  468. return None
  469. finally:
  470. if process is not None:
  471. _active_capture_pids.discard(process.pid)
  472. # Redirects a camera URL may take before the fetch gives up.
  473. _MAX_CAMERA_REDIRECTS = 5
  474. _REDIRECT_STATUSES = (301, 302, 303, 307, 308)
  475. def _with_same_camera_login(current: str, target: str) -> str:
  476. """*target* with the login of *current* when it is the same camera (scheme,
  477. host and port) and names no login of its own, as the HTTP client kept it."""
  478. here, there = urlparse(current), urlparse(target)
  479. if there.username or not here.username:
  480. return target
  481. if (here.scheme, here.hostname, here.port) != (there.scheme, there.hostname, there.port):
  482. return target
  483. return there._replace(netloc=f"{here.netloc.rsplit('@', 1)[0]}@{there.netloc}").geturl()
  484. @contextlib.asynccontextmanager
  485. async def _get_camera_url(session: aiohttp.ClientSession, url: str, schemes: tuple[str, ...]):
  486. """GET a sanitized camera URL, following redirects only where the camera
  487. guard allows: each destination is checked as the URL itself was. Yields
  488. the response, or None when a redirect goes somewhere refused or never ends.
  489. """
  490. current = url
  491. for _ in range(_MAX_CAMERA_REDIRECTS + 1):
  492. async with session.get(current, allow_redirects=False) as response:
  493. location = response.headers.get("Location") if response.status in _REDIRECT_STATUSES else None
  494. if location is None:
  495. yield response
  496. return
  497. try:
  498. target = _sanitize_camera_url(_with_same_camera_login(current, urljoin(current, location)), schemes)
  499. except ValueError:
  500. # A malformed Location (bad IPv6 literal, port out of range).
  501. target = None
  502. if target is None:
  503. logger.error(
  504. "Camera URL redirected to a refused destination: %s", (redact_url_credentials(location) or "")[:50]
  505. )
  506. yield None
  507. return
  508. current = target
  509. logger.error("Camera URL redirected more than %d times", _MAX_CAMERA_REDIRECTS)
  510. yield None
  511. async def _capture_mjpeg_frame(url: str, timeout: int) -> bytes | None:
  512. """Extract a single representative frame from an MJPEG stream.
  513. Many MJPEG sources — go2rtc most notably (#1177), and several IP cameras —
  514. emit a "warm-up" frame on the byte that follows connection accept: usually
  515. the last keyframe held in the encoder, which is often black or stale until
  516. the encoder catches up to live content. To return a frame that's actually
  517. representative of the scene we read past the first frame and return the
  518. second; if the connection closes / times out / hits the buffer cap before
  519. a second frame ever arrives we fall back to the first so callers still
  520. get *something* (better than degrading slow / single-frame streams to None,
  521. which would regress every code path that consumed pre-fix behaviour).
  522. Note: this function intentionally makes requests to user-configured URLs.
  523. External camera support requires connecting to user-specified camera
  524. endpoints. URL is sanitized and dangerous destinations are blocked.
  525. """
  526. safe_url = _sanitize_camera_url(url, ("http", "https"))
  527. if not safe_url:
  528. logger.error("Invalid MJPEG URL format: %s...", redact_url_credentials(url)[:50])
  529. return None
  530. jpeg_start = b"\xff\xd8"
  531. jpeg_end = b"\xff\xd9"
  532. first_frame: bytes | None = None # warm-up frame; fallback if no second arrives
  533. buffer = b""
  534. try:
  535. async with (
  536. asyncio.timeout(timeout),
  537. aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session,
  538. _get_camera_url(session, safe_url, ("http", "https")) as response,
  539. ):
  540. if response is None:
  541. return None
  542. if response.status != 200:
  543. logger.error("MJPEG stream returned status %s", response.status)
  544. return None
  545. async for chunk in response.content.iter_chunked(8192):
  546. buffer += chunk
  547. # A single chunk can carry multiple frames (e.g. high-FPS sources)
  548. # or a partial frame. Drain every complete frame we already have
  549. # before pulling the next chunk.
  550. while True:
  551. start_idx = buffer.find(jpeg_start)
  552. if start_idx == -1:
  553. # No frame start yet — drop trailing garbage, keep waiting.
  554. break
  555. end_idx = buffer.find(jpeg_end, start_idx + 2)
  556. if end_idx == -1:
  557. # Partial frame; trim already-discarded prefix so the
  558. # buffer stays bounded across long-running streams.
  559. if start_idx > 0:
  560. buffer = buffer[start_idx:]
  561. break
  562. frame = buffer[start_idx : end_idx + 2]
  563. buffer = buffer[end_idx + 2 :]
  564. if first_frame is None:
  565. first_frame = frame # warm-up; keep but don't return yet
  566. continue
  567. return frame # representative second frame
  568. if len(buffer) > 5 * 1024 * 1024: # 5MB limit
  569. logger.warning("MJPEG buffer exceeded 5MB without finding frame")
  570. break # exit chunk loop, fall through to first_frame fallback
  571. except TimeoutError:
  572. logger.warning("MJPEG frame capture timed out after %ss", timeout)
  573. except (aiohttp.ClientError, OSError) as e:
  574. logger.error("MJPEG frame capture failed: %s", e)
  575. # Stream ended / timed out / buffer cap before a second frame arrived.
  576. # Return whatever warm-up frame we managed to read; better an iffy frame
  577. # than None for callers that need *some* image (snapshot UX, plate-detect
  578. # CV, finish photo). None only if no frame ever arrived at all.
  579. return first_frame
  580. async def _capture_rtsp_frame(url: str, timeout: int) -> bytes | None:
  581. """Capture frame from RTSP using ffmpeg.
  582. For rtsps:// URLs, a local TLS proxy is used to avoid GnuTLS issues.
  583. Note: this function intentionally connects to user-configured URLs, the same
  584. as the MJPEG and snapshot paths. The URL is sanitized and dangerous
  585. destinations are blocked before it reaches ffmpeg.
  586. """
  587. ffmpeg = get_ffmpeg_path()
  588. if not ffmpeg:
  589. logger.error("ffmpeg not found - required for RTSP capture")
  590. return None
  591. # ffmpeg's -i accepts every protocol it was built with, so an unchecked URL
  592. # here is a request to any host and scheme the caller names, not merely to a
  593. # camera. Restricting the scheme to RTSP is what keeps this a camera fetch.
  594. safe_url = _sanitize_camera_url(url, ("rtsp", "rtsps"))
  595. if not safe_url:
  596. logger.error("Invalid RTSP URL: %s...", redact_url_credentials(url)[:50])
  597. return None
  598. # If rtsps://, use TLS proxy
  599. proxy_server = None
  600. effective_url = safe_url
  601. if safe_url.lower().startswith("rtsps://"):
  602. try:
  603. from urllib.parse import urlparse
  604. from backend.app.services.camera import close_tls_proxy, create_tls_proxy
  605. parsed = urlparse(safe_url)
  606. target_port = parsed.port or 322
  607. proxy_port, proxy_server = await create_tls_proxy(parsed.hostname, target_port)
  608. userinfo = ""
  609. if parsed.username:
  610. userinfo = parsed.username
  611. if parsed.password:
  612. userinfo += f":{parsed.password}"
  613. userinfo += "@"
  614. # Points at loopback deliberately, and is built after the check
  615. # above rather than re-checked: the destination that mattered was
  616. # the one the caller named, and it has already been vetted.
  617. effective_url = f"rtsp://{userinfo}127.0.0.1:{proxy_port}{parsed.path}"
  618. if parsed.query:
  619. effective_url += f"?{parsed.query}"
  620. except Exception as e:
  621. logger.warning("Failed to create TLS proxy for RTSP capture, falling back: %s", e)
  622. effective_url = safe_url
  623. cmd = [
  624. ffmpeg,
  625. *FFMPEG_RTSP_LOGLEVEL,
  626. "-rtsp_transport",
  627. "tcp",
  628. # Belt and braces on the scheme check above: a demuxer that follows a
  629. # reference out of the stream cannot leave these protocols either.
  630. "-protocol_whitelist",
  631. _RTSP_PROTOCOL_WHITELIST,
  632. "-i",
  633. effective_url,
  634. "-frames:v",
  635. "1",
  636. "-f",
  637. "image2pipe",
  638. "-vcodec",
  639. "mjpeg",
  640. "-q:v",
  641. "2",
  642. "-",
  643. ]
  644. try:
  645. logger.debug("Running ffmpeg RTSP capture...")
  646. process = await asyncio.create_subprocess_exec(
  647. *cmd,
  648. stdout=asyncio.subprocess.PIPE,
  649. stderr=asyncio.subprocess.PIPE,
  650. )
  651. async with asyncio.timeout(timeout):
  652. state, log = await read_ffmpeg_log_until_open(process)
  653. stdout, stderr = await process.communicate()
  654. stderr = log + stderr
  655. logger.debug(
  656. "ffmpeg returned: code=%s, stdout=%s bytes, stderr=%s bytes",
  657. process.returncode,
  658. len(stdout),
  659. len(stderr),
  660. )
  661. if state == "redirected":
  662. return None
  663. if process.returncode != 0 or state != "open":
  664. # The summariser masks the camera password the input URL carries.
  665. logger.error("ffmpeg RTSP capture failed: %s", summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT)
  666. return None
  667. if not stdout or len(stdout) < 100:
  668. logger.error("ffmpeg returned empty or too small frame")
  669. return None
  670. return stdout
  671. except TimeoutError:
  672. logger.warning("RTSP frame capture timed out after %ss", timeout)
  673. if process:
  674. process.kill()
  675. return None
  676. except OSError as e:
  677. logger.error("RTSP frame capture failed: %s", e)
  678. return None
  679. finally:
  680. if proxy_server:
  681. await close_tls_proxy(proxy_server)
  682. def _transcode_to_jpeg(data: bytes) -> bytes | None:
  683. """Decode an arbitrary still image (PNG/WebP/BMP/GIF/...) and re-encode as JPEG.
  684. Some camera/proxy snapshot endpoints serve stills as PNG or WebP rather than
  685. JPEG. A browser opened directly at the URL renders those fine, but our MJPEG
  686. ``multipart/x-mixed-replace`` stream hard-labels every part
  687. ``Content-Type: image/jpeg`` — so a non-JPEG payload makes the browser reject
  688. the frame and drop the whole stream ("connection lost", #1902). Transcoding to
  689. JPEG keeps the stream genuinely MJPEG and also keeps the JPEG-only downstream
  690. (plate detection, Obico, finish photo) working.
  691. Returns None if the bytes are not a decodable image (e.g. an HTML error page)
  692. or if the imaging libraries are unavailable; the caller then has no image.
  693. The raw bytes are not passed on: a URL's response is not a camera frame.
  694. """
  695. try:
  696. import cv2
  697. import numpy as np
  698. except ImportError:
  699. return None
  700. try:
  701. img = cv2.imdecode(np.frombuffer(data, dtype=np.uint8), cv2.IMREAD_COLOR)
  702. if img is None:
  703. return None
  704. ok, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 85])
  705. if not ok:
  706. return None
  707. return buf.tobytes()
  708. except Exception as e: # cv2 raises cv2.error (a subclass of Exception) on bad input
  709. logger.debug("Snapshot transcode to JPEG failed: %s", e)
  710. return None
  711. async def _capture_snapshot(url: str, timeout: int) -> bytes | None:
  712. """Fetch snapshot from HTTP URL.
  713. Note: This function intentionally makes requests to user-configured URLs.
  714. External camera support requires connecting to user-specified camera endpoints.
  715. URL is sanitized and dangerous destinations are blocked.
  716. """
  717. # Sanitize URL - returns reconstructed URL from validated components
  718. safe_url = _sanitize_camera_url(url, ("http", "https"))
  719. if not safe_url:
  720. logger.error("Invalid snapshot URL format: %s...", redact_url_credentials(url)[:50])
  721. return None
  722. try:
  723. # One deadline for every redirect and the read, as the client's own
  724. # timeout covered them when it followed redirects itself.
  725. async with (
  726. asyncio.timeout(timeout),
  727. aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session,
  728. _get_camera_url(session, safe_url, ("http", "https")) as response,
  729. ):
  730. if response is None:
  731. return None
  732. if response.status != 200:
  733. logger.error("Snapshot URL returned status %s", response.status)
  734. return None
  735. data = await response.read()
  736. except TimeoutError:
  737. logger.warning("Snapshot capture timed out after %ss", timeout)
  738. return None
  739. except (aiohttp.ClientError, OSError) as e:
  740. logger.error("Snapshot capture failed: %s", e)
  741. return None
  742. # Fast path: already JPEG (SOI marker), stream it as-is (no decode/re-encode).
  743. if data.startswith(b"\xff\xd8"):
  744. return data
  745. # Not JPEG. Many snapshot endpoints serve PNG/WebP/BMP — transcode to JPEG so
  746. # the browser's MJPEG stream (and JPEG-only downstream) keep working instead of
  747. # dropping the connection (#1902). Run off the event loop: cv2 decode/encode is
  748. # CPU-bound and this can be polled at up to 15 fps while a camera view is open.
  749. transcoded = await asyncio.to_thread(_transcode_to_jpeg, data)
  750. if transcoded is not None:
  751. logger.debug(
  752. "Transcoded non-JPEG snapshot (%d bytes, header %s) to JPEG",
  753. len(data),
  754. data[:4].hex(),
  755. )
  756. return transcoded
  757. # Couldn't decode it as an image at all — most likely not an image response
  758. # (HTML error page, auth redirect, wrong URL). Not passed on: whatever a URL
  759. # returns would reach the viewer of the camera stream.
  760. logger.warning(
  761. "External camera snapshot is not a decodable image "
  762. "(%d bytes, header %s) — verify the camera URL returns an image",
  763. len(data),
  764. data[:4].hex(),
  765. )
  766. return None
  767. def jpeg_resolution(frame: bytes) -> str | None:
  768. """``"WIDTHxHEIGHT"`` from a JPEG's SOF marker, or None when there is none.
  769. The SOF marker (FF C0/C1/C2) is followed by length, precision, height, width.
  770. """
  771. for marker in (b"\xff\xc0", b"\xff\xc1", b"\xff\xc2"):
  772. idx = frame.find(marker)
  773. if idx != -1 and idx + 9 <= len(frame):
  774. height = (frame[idx + 5] << 8) | frame[idx + 6]
  775. width = (frame[idx + 7] << 8) | frame[idx + 8]
  776. return f"{width}x{height}"
  777. return None
  778. async def test_connection(url: str, camera_type: str) -> dict:
  779. """Test camera connection.
  780. Returns:
  781. Dict with {success: bool, error?: str, resolution?: str, coalesced: bool}
  782. ``coalesced`` is True when the frame came from a capture that was already
  783. running rather than from a connection this test opened. Captures are shared
  784. (see ``capture_frame``), so a test that lands while Obico is polling — or
  785. while any other one-shot consumer is mid-capture — gets that frame back and
  786. would otherwise report a healthy connection it never made, which is the one
  787. answer a *connection test* must not give silently. Forcing an uncoalesced
  788. capture here would be worse: it would open the second handle to a
  789. single-reader device that this whole mechanism exists to prevent. So the
  790. test still shares, and says so. Mirrors the ``coalesced_capture`` code the
  791. built-in diagnostic reports for the same situation (camera_diagnose.py).
  792. """
  793. logger.info("Testing camera connection: type=%s, url=%s...", camera_type, redact_url_credentials(url)[:50])
  794. # Sampled before the call, while it can still distinguish "someone else is
  795. # mid-capture" from "I am the one capturing".
  796. coalesced = capture_in_flight(url, camera_type)
  797. try:
  798. frame = await capture_frame(url, camera_type, timeout=10)
  799. logger.info("Capture result: %s bytes%s", len(frame) if frame else 0, " (coalesced)" if coalesced else "")
  800. if frame:
  801. return {"success": True, "resolution": jpeg_resolution(frame), "coalesced": coalesced}
  802. else:
  803. return {"success": False, "error": "Failed to capture frame from camera", "coalesced": coalesced}
  804. except Exception as e:
  805. # Sanitize error message - don't expose internal details
  806. error_type = type(e).__name__
  807. logger.error("Camera connection test failed: %s", e)
  808. return {"success": False, "error": f"Connection failed: {error_type}", "coalesced": coalesced}
  809. async def generate_mjpeg_stream(
  810. url: str,
  811. camera_type: str,
  812. fps: int = 10,
  813. *,
  814. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  815. on_frame: Callable[[bytes], None] | None = None,
  816. stop_event: asyncio.Event | None = None,
  817. ) -> AsyncGenerator[bytes, None]:
  818. """Generator yielding MJPEG frames for streaming.
  819. Args:
  820. url: Camera URL or USB device path
  821. camera_type: "mjpeg", "rtsp", "snapshot", or "usb"
  822. fps: Target frames per second
  823. on_process: Called with the spawned ffmpeg process for the ``usb`` and
  824. ``rtsp`` paths so the route layer can register it into the shared
  825. stream registries — that's what lets ``/camera/stop`` and the orphan
  826. janitor find and kill a leaked ffmpeg that's holding a USB device
  827. open (#2675). Without it the process is reachable only from this
  828. generator's own ``finally``, which an abrupt client disconnect can
  829. skip (same cancellation-timing class as #776).
  830. on_frame: Called with each RAW frame, before it is wrapped for the wire,
  831. so the route layer can publish it as the printer's buffered frame
  832. (#2707). It has to be a callback: what this generator yields is
  833. multipart-wrapped, so a consumer of the stream cannot recover the
  834. JPEG, and until now nothing populated the buffer for external
  835. cameras at all — leaving every one-shot consumer (layer timelapse,
  836. finish photo, Obico, plate check) with nothing to reuse and no
  837. option but to open a competing handle on a single-reader device.
  838. Exceptions are logged and swallowed: buffering must never be able
  839. to break the live stream.
  840. stop_event: When set, the reconnect loops stop retrying — so an explicit
  841. stop (which kills the current ffmpeg) doesn't immediately respawn a
  842. new process and reacquire the device.
  843. Yields:
  844. MJPEG frame data with HTTP multipart boundaries
  845. """
  846. frame_interval = 1.0 / max(fps, 1)
  847. last_frame_time = 0.0
  848. def _publish(frame: bytes) -> bytes:
  849. """Hand the raw frame to on_frame, then format it for the wire."""
  850. if on_frame is not None:
  851. try:
  852. on_frame(frame)
  853. except Exception:
  854. logger.exception("on_frame callback raised")
  855. return _format_mjpeg_frame(frame)
  856. async def _reconnecting(open_session, label: str):
  857. """Yield frames across sessions, reconnecting after each that delivered.
  858. A session that ends without a single frame stops the stream: the
  859. source is down, and retrying is the viewer's call. One that delivered
  860. frames and then ended is a routine drop and is always reconnected.
  861. This used to be three reconnects for the life of the stream, so a
  862. server that closes its sessions periodically ended the stream for good
  863. on the fourth drop, however long each session had run -- the external
  864. twin of the built-in RTSP path's lifetime reconnect budget.
  865. """
  866. drops = 0
  867. while True:
  868. frame_yielded = False
  869. # aclosing: stop the session's ffmpeg the moment this generator is
  870. # closed, rather than whenever the abandoned iterator is collected.
  871. async with contextlib.aclosing(open_session()) as session:
  872. async for frame in session:
  873. frame_yielded = True
  874. yield frame
  875. if not frame_yielded or (stop_event is not None and stop_event.is_set()):
  876. break
  877. # The sessions swallow CancelledError and simply end, so a viewer
  878. # whose task was cancelled mid-read looks like a routine drop here.
  879. # Never redial for a task that is being cancelled (Task.cancelling
  880. # is 3.11+; without it this falls back to the next await raising).
  881. task = asyncio.current_task()
  882. if task is not None and getattr(task, "cancelling", lambda: 0)():
  883. break
  884. drops += 1
  885. logger.warning("External %s stream ended, reconnecting (drop %d)...", label, drops)
  886. await asyncio.sleep(2)
  887. if camera_type == "mjpeg":
  888. # Proxy MJPEG stream directly, reconnecting after routine drops.
  889. async with contextlib.aclosing(_reconnecting(lambda: _stream_mjpeg(url), "MJPEG")) as frames:
  890. async for frame in frames:
  891. current_time = asyncio.get_event_loop().time()
  892. if current_time - last_frame_time >= frame_interval:
  893. last_frame_time = current_time
  894. yield _publish(frame)
  895. elif camera_type == "rtsp":
  896. # Use ffmpeg to convert RTSP to MJPEG, reconnecting after routine drops.
  897. # One freeze watch for the whole stream: the still-scene rule compares a
  898. # new session's first frame with the one the last session froze on.
  899. freeze = _FreezeWatch()
  900. async with contextlib.aclosing(
  901. _reconnecting(lambda: _stream_rtsp(url, fps, on_process=on_process, freeze=freeze), "RTSP")
  902. ) as frames:
  903. async for frame in frames:
  904. yield _publish(frame)
  905. elif camera_type == "usb":
  906. # Use ffmpeg to stream from USB camera
  907. async for frame in _stream_usb(url, fps, on_process=on_process):
  908. yield _publish(frame)
  909. elif camera_type == "snapshot":
  910. # Poll snapshot URL at interval
  911. while True:
  912. try:
  913. frame = await _capture_snapshot(url, timeout=10)
  914. if frame:
  915. yield _publish(frame)
  916. await asyncio.sleep(frame_interval)
  917. except asyncio.CancelledError:
  918. break
  919. except (aiohttp.ClientError, OSError) as e:
  920. logger.warning("Snapshot poll failed: %s", e)
  921. await asyncio.sleep(frame_interval)
  922. def _format_mjpeg_frame(frame: bytes) -> bytes:
  923. """Format frame for MJPEG HTTP response."""
  924. return (
  925. b"--frame\r\n"
  926. b"Content-Type: image/jpeg\r\n"
  927. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  928. b"\r\n" + frame + b"\r\n"
  929. )
  930. async def _stream_mjpeg(url: str) -> AsyncGenerator[bytes, None]:
  931. """Stream frames from MJPEG URL.
  932. Note: This function intentionally makes requests to user-configured URLs.
  933. External camera support requires connecting to user-specified camera endpoints.
  934. URL is sanitized and dangerous destinations are blocked.
  935. """
  936. # Sanitize URL - returns reconstructed URL from validated components
  937. safe_url = _sanitize_camera_url(url, ("http", "https"))
  938. if not safe_url:
  939. logger.error("Invalid MJPEG stream URL: %s...", redact_url_credentials(url)[:50])
  940. return
  941. try:
  942. timeout = aiohttp.ClientTimeout(total=None, sock_read=30)
  943. async with (
  944. aiohttp.ClientSession(timeout=timeout) as session,
  945. _get_camera_url(session, safe_url, ("http", "https")) as response,
  946. ):
  947. if response is None:
  948. return
  949. if response.status != 200:
  950. logger.error("MJPEG stream returned status %s", response.status)
  951. return
  952. buffer = b""
  953. jpeg_start = b"\xff\xd8"
  954. jpeg_end = b"\xff\xd9"
  955. async for chunk in response.content.iter_chunked(8192):
  956. buffer += chunk
  957. # Extract complete frames from buffer
  958. while True:
  959. start_idx = buffer.find(jpeg_start)
  960. if start_idx == -1:
  961. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  962. break
  963. if start_idx > 0:
  964. buffer = buffer[start_idx:]
  965. end_idx = buffer.find(jpeg_end, 2)
  966. if end_idx == -1:
  967. break
  968. frame = buffer[: end_idx + 2]
  969. buffer = buffer[end_idx + 2 :]
  970. yield frame
  971. except asyncio.CancelledError:
  972. logger.info("MJPEG stream cancelled")
  973. except (aiohttp.ClientError, OSError) as e:
  974. logger.error("MJPEG stream error: %s", e)
  975. # How long an external RTSP stream may emit byte-identical frames before its
  976. # ffmpeg is restarted, and the longer re-check for a picture that really does
  977. # not change: the same rule as the printer's own RTSP stream (#3218, see
  978. # routes/camera._RTSP_FROZEN_SECONDS). ffmpeg's ``-r fps`` repeats its last
  979. # frame after the camera stops sending, so counting frames sees a live stream.
  980. _EXTERNAL_RTSP_FROZEN_SECONDS = 20.0
  981. _EXTERNAL_RTSP_STILL_RECHECK_SECONDS = 300.0
  982. class _FreezeWatch:
  983. """Notices an RTSP picture that has stopped changing, across sessions.
  984. A live camera rarely repeats a frame byte for byte (sensor noise), so a run
  985. of identical frames usually means ffmpeg is repeating a frozen one. When the
  986. first frame after the restart is that same picture again, the camera really
  987. shows it (a dark, idle scene), and it is only re-checked at the longer
  988. interval until it changes.
  989. Unlike a Bambu camera, an external one can legitimately repeat frames for a
  990. while: a source slower than ffmpeg's ``-r`` rate, or a surveillance camera's
  991. smart codec on a static scene. So the limit is three times the longest gap
  992. seen between real changes (a "freeze" after which the camera showed a new
  993. picture counts as one), never below the 20 s of the printer's camera and
  994. never above the still-scene interval.
  995. """
  996. def __init__(self) -> None:
  997. self.frozen_crc: int | None = None
  998. self.still_scene = False
  999. self.unchanged_for = 0.0
  1000. self._last_crc: int | None = None
  1001. self._since = 0.0
  1002. self._longest_gap = 0.0
  1003. def start_session(self) -> None:
  1004. self._last_crc = None
  1005. def _limit(self) -> float:
  1006. if self.still_scene:
  1007. return _EXTERNAL_RTSP_STILL_RECHECK_SECONDS
  1008. return min(
  1009. max(_EXTERNAL_RTSP_FROZEN_SECONDS, 3 * self._longest_gap),
  1010. _EXTERNAL_RTSP_STILL_RECHECK_SECONDS,
  1011. )
  1012. def frozen(self, frame: bytes, now: float) -> bool:
  1013. crc = zlib.crc32(frame)
  1014. if self._last_crc is None:
  1015. if self.frozen_crc is not None and crc != self.frozen_crc:
  1016. # The picture had not frozen: the camera is just slow to change.
  1017. self._longest_gap = max(self._longest_gap, self.unchanged_for)
  1018. self.still_scene = self.frozen_crc is not None and crc == self.frozen_crc
  1019. self._last_crc = crc
  1020. self._since = now
  1021. return False
  1022. if crc != self._last_crc:
  1023. self._longest_gap = max(self._longest_gap, now - self._since)
  1024. self._last_crc = crc
  1025. self._since = now
  1026. self.still_scene = False
  1027. self.frozen_crc = None
  1028. return False
  1029. self.unchanged_for = now - self._since
  1030. if self.unchanged_for > self._limit():
  1031. self.frozen_crc = crc
  1032. return True
  1033. return False
  1034. async def _end_stream_ffmpeg(process: asyncio.subprocess.Process) -> None:
  1035. """Stop a streaming ffmpeg, bounded.
  1036. Through the camera routes' terminator, which drains the pipes while it
  1037. waits: a streaming ffmpeg is usually blocked writing to a full stdout pipe,
  1038. where it ignores SIGTERM and, once killed, wait() never returns (#2580).
  1039. Unbounded, that hung the shared upstream's teardown, and with it every stop,
  1040. camera change, printer delete and shutdown waiting on the fan-out.
  1041. """
  1042. from backend.app.api.routes.camera import _terminate_ffmpeg
  1043. await _terminate_ffmpeg(process)
  1044. async def _stream_rtsp(
  1045. url: str,
  1046. fps: int,
  1047. *,
  1048. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  1049. freeze: _FreezeWatch | None = None,
  1050. ) -> AsyncGenerator[bytes, None]:
  1051. """Stream frames from RTSP URL via ffmpeg.
  1052. For rtsps:// URLs, a local TLS proxy (Python OpenSSL) is used instead
  1053. of relying on ffmpeg's GnuTLS backend, which has compatibility issues
  1054. with some printer firmwares.
  1055. Note: this function intentionally connects to user-configured URLs. The URL
  1056. is sanitized and dangerous destinations are blocked before it reaches
  1057. ffmpeg — see ``_capture_rtsp_frame``, which guards the one-shot path the
  1058. same way.
  1059. """
  1060. ffmpeg = get_ffmpeg_path()
  1061. if not ffmpeg:
  1062. logger.error("ffmpeg not found - required for RTSP streaming")
  1063. return
  1064. from backend.app.services.camera import rtsp_socket_timeout_flag
  1065. safe_url = _sanitize_camera_url(url, ("rtsp", "rtsps"))
  1066. if not safe_url:
  1067. logger.error("Invalid RTSP stream URL: %s...", redact_url_credentials(url)[:50])
  1068. return
  1069. # If the URL uses rtsps://, set up a TLS proxy so ffmpeg uses plain rtsp://
  1070. proxy_server = None
  1071. effective_url = safe_url
  1072. if safe_url.lower().startswith("rtsps://"):
  1073. try:
  1074. from urllib.parse import urlparse
  1075. from backend.app.services.camera import close_tls_proxy, create_tls_proxy
  1076. parsed = urlparse(safe_url)
  1077. target_port = parsed.port or 322
  1078. proxy_port, proxy_server = await create_tls_proxy(parsed.hostname, target_port)
  1079. # Rewrite URL: rtsps://user:pass@host:port/path → rtsp://user:pass@127.0.0.1:proxy/path
  1080. userinfo = ""
  1081. if parsed.username:
  1082. userinfo = parsed.username
  1083. if parsed.password:
  1084. userinfo += f":{parsed.password}"
  1085. userinfo += "@"
  1086. # Loopback by design, and built after the check above rather than
  1087. # re-checked — see the same rewrite in _capture_rtsp_frame.
  1088. effective_url = f"rtsp://{userinfo}127.0.0.1:{proxy_port}{parsed.path}"
  1089. if parsed.query:
  1090. effective_url += f"?{parsed.query}"
  1091. except Exception as e:
  1092. logger.warning("Failed to create TLS proxy for RTSP, falling back to direct: %s", e)
  1093. effective_url = safe_url
  1094. cmd = [
  1095. ffmpeg,
  1096. *FFMPEG_RTSP_LOGLEVEL,
  1097. "-rtsp_transport",
  1098. "tcp",
  1099. "-rtsp_flags",
  1100. "prefer_tcp",
  1101. "-protocol_whitelist",
  1102. _RTSP_PROTOCOL_WHITELIST,
  1103. # Socket I/O timeout name varies by ffmpeg version (#1504); see
  1104. # `rtsp_socket_timeout_flag()` in services.camera.
  1105. f"-{rtsp_socket_timeout_flag()}",
  1106. "30000000",
  1107. "-buffer_size",
  1108. "1024000",
  1109. "-max_delay",
  1110. "500000",
  1111. # No probe cap here (#3082). The input is whatever camera the user
  1112. # owns, so there is no stream to tune a fast-start probe against: a
  1113. # 32-byte probe expires before a source that carries SPS/PPS in-band
  1114. # rather than in its SDP has sent them, and ffmpeg then starts no
  1115. # H.264 decoder and emits nothing at all. ffmpeg's defaults are a
  1116. # ceiling rather than a wait, so a camera that announces itself in the
  1117. # first packet still starts as fast as it ever did.
  1118. #
  1119. # `_capture_rtsp_frame` has always run on those defaults, which is how
  1120. # a camera could pass the connection test and still show a black live
  1121. # view. The printer path is the opposite case — a known Bambu camera
  1122. # per model — and keeps its tuning in `camera_profiles.py`.
  1123. "-fflags",
  1124. "nobuffer",
  1125. "-flags",
  1126. "low_delay",
  1127. "-i",
  1128. effective_url,
  1129. "-f",
  1130. "mjpeg",
  1131. "-q:v",
  1132. "5",
  1133. "-r",
  1134. str(fps),
  1135. "-an",
  1136. "-",
  1137. ]
  1138. process = None
  1139. log_watch = None
  1140. try:
  1141. process = await asyncio.create_subprocess_exec(
  1142. *cmd,
  1143. stdout=asyncio.subprocess.PIPE,
  1144. stderr=asyncio.subprocess.PIPE,
  1145. )
  1146. # Register immediately — before the startup probe below — so a process
  1147. # that hangs on connect (rather than exiting) is still reachable by the
  1148. # stop endpoint / orphan janitor (#2675).
  1149. if on_process is not None:
  1150. on_process(process)
  1151. # No frame is read before ffmpeg reports the input open: a redirect it
  1152. # followed on the way would be in its log by then.
  1153. try:
  1154. state, log = await asyncio.wait_for(read_ffmpeg_log_until_open(process), timeout=30.0)
  1155. except TimeoutError:
  1156. logger.warning("RTSP stream did not open within 30s")
  1157. return
  1158. if state == "ended":
  1159. assert process.stderr is not None
  1160. log += await process.stderr.read()
  1161. # The summariser masks the camera password the input URL carries.
  1162. logger.error("ffmpeg RTSP stream failed: %s", summarize_ffmpeg_stderr(log) or NO_FFMPEG_OUTPUT)
  1163. return
  1164. if state != "open":
  1165. return
  1166. log_watch = asyncio.create_task(watch_ffmpeg_log(process))
  1167. if freeze is not None:
  1168. freeze.start_session()
  1169. buffer = b""
  1170. jpeg_start = b"\xff\xd8"
  1171. jpeg_end = b"\xff\xd9"
  1172. while True:
  1173. try:
  1174. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  1175. if not chunk:
  1176. break
  1177. buffer += chunk
  1178. # Extract complete frames
  1179. while True:
  1180. start_idx = buffer.find(jpeg_start)
  1181. if start_idx == -1:
  1182. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  1183. break
  1184. if start_idx > 0:
  1185. buffer = buffer[start_idx:]
  1186. end_idx = buffer.find(jpeg_end, 2)
  1187. if end_idx == -1:
  1188. break
  1189. frame = buffer[: end_idx + 2]
  1190. buffer = buffer[end_idx + 2 :]
  1191. yield frame
  1192. if freeze is not None and freeze.frozen(frame, time.monotonic()):
  1193. # Ending the session restarts ffmpeg (_reconnecting).
  1194. if freeze.still_scene:
  1195. logger.info("External RTSP still-scene re-check, restarting ffmpeg")
  1196. else:
  1197. logger.warning(
  1198. "External RTSP picture frozen for %.0fs, restarting ffmpeg",
  1199. freeze.unchanged_for,
  1200. )
  1201. return
  1202. except TimeoutError:
  1203. logger.warning("RTSP stream read timeout")
  1204. break
  1205. except asyncio.CancelledError:
  1206. logger.info("RTSP stream cancelled")
  1207. except OSError as e:
  1208. logger.error("RTSP stream error: %s", e)
  1209. finally:
  1210. if log_watch is not None:
  1211. log_watch.cancel()
  1212. if process and process.returncode is None:
  1213. await _end_stream_ffmpeg(process)
  1214. if proxy_server:
  1215. await close_tls_proxy(proxy_server)
  1216. async def _stream_usb(
  1217. device: str,
  1218. fps: int,
  1219. *,
  1220. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  1221. ) -> AsyncGenerator[bytes, None]:
  1222. """Stream frames from USB camera via ffmpeg."""
  1223. ffmpeg = get_ffmpeg_path()
  1224. if not ffmpeg:
  1225. logger.error("ffmpeg not found - required for USB camera streaming")
  1226. return
  1227. # Same validation as the one-shot path: a prefix check accepted
  1228. # /dev/video/../../<anything that exists>, which -f v4l2 would then refuse
  1229. # rather than the check refusing it.
  1230. safe_device = _safe_usb_device_path(device)
  1231. if not safe_device:
  1232. return
  1233. device = safe_device
  1234. # ffmpeg command to stream from USB camera (v4l2)
  1235. cmd = [
  1236. ffmpeg,
  1237. "-f",
  1238. "v4l2",
  1239. "-framerate",
  1240. str(fps),
  1241. "-i",
  1242. device,
  1243. "-f",
  1244. "mjpeg",
  1245. "-q:v",
  1246. "5",
  1247. "-r",
  1248. str(fps),
  1249. "-",
  1250. ]
  1251. process = None
  1252. try:
  1253. logger.info("Starting USB camera stream from %s at %s fps", device, fps)
  1254. process = await asyncio.create_subprocess_exec(
  1255. *cmd,
  1256. stdout=asyncio.subprocess.PIPE,
  1257. stderr=asyncio.subprocess.PIPE,
  1258. )
  1259. # Register immediately — before the startup probe below — so a process
  1260. # that hangs in open()/ioctl on a still-locked device (rather than
  1261. # exiting with a "busy" error) is still reachable by the stop endpoint /
  1262. # orphan janitor (#2675).
  1263. if on_process is not None:
  1264. on_process(process)
  1265. # Give ffmpeg a moment to start and check for immediate failures
  1266. await asyncio.sleep(0.5)
  1267. if process.returncode is not None:
  1268. stderr = await process.stderr.read()
  1269. logger.error(
  1270. "ffmpeg USB stream failed immediately: %s", summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT
  1271. )
  1272. return
  1273. buffer = b""
  1274. jpeg_start = b"\xff\xd8"
  1275. jpeg_end = b"\xff\xd9"
  1276. while True:
  1277. try:
  1278. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  1279. if not chunk:
  1280. break
  1281. buffer += chunk
  1282. # Extract complete frames
  1283. while True:
  1284. start_idx = buffer.find(jpeg_start)
  1285. if start_idx == -1:
  1286. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  1287. break
  1288. if start_idx > 0:
  1289. buffer = buffer[start_idx:]
  1290. end_idx = buffer.find(jpeg_end, 2)
  1291. if end_idx == -1:
  1292. break
  1293. frame = buffer[: end_idx + 2]
  1294. buffer = buffer[end_idx + 2 :]
  1295. yield frame
  1296. except TimeoutError:
  1297. logger.warning("USB stream read timeout")
  1298. break
  1299. except asyncio.CancelledError:
  1300. logger.info("USB stream cancelled")
  1301. except OSError as e:
  1302. logger.error("USB stream error: %s", e)
  1303. finally:
  1304. if process and process.returncode is None:
  1305. await _end_stream_ffmpeg(process)