external_camera.py 57 KB

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