external_camera.py 56 KB

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