external_camera.py 62 KB

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