external_camera.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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 functools
  9. import ipaddress
  10. import logging
  11. import re
  12. import shutil
  13. import socket
  14. from collections.abc import AsyncGenerator, Callable
  15. from pathlib import Path
  16. from urllib.parse import urlparse
  17. import aiohttp
  18. from backend.app.core.logging_filters import redact_url_credentials
  19. from backend.app.utils.ffmpeg_output import NO_FFMPEG_OUTPUT, summarize_ffmpeg_stderr
  20. logger = logging.getLogger(__name__)
  21. # Protocols ffmpeg may use for an RTSP input. RTSP negotiates its media
  22. # transport at runtime, so the transports have to be here alongside rtsp itself;
  23. # tls and crypto cover encrypted variants. Everything ffmpeg would otherwise
  24. # accept behind an -i — file, http, tcp to anywhere, concat — is left out, so a
  25. # stream that references something outside itself cannot pull it in.
  26. _RTSP_PROTOCOL_WHITELIST = "rtsp,rtp,udp,tcp,tls,crypto"
  27. def _blocked_host_reason(hostname: str) -> str | None:
  28. """Describe why *hostname* is a destination we refuse to fetch, or None to allow it.
  29. Camera URLs are user-supplied and reach the network — over aiohttp for the
  30. HTTP types, and as an ``ffmpeg -i`` argument for RTSP — so this is where the
  31. SSRF boundary sits. LAN addresses are deliberately allowed: cameras live on
  32. the same network as Bambuddy, and blocking RFC-1918 would remove the feature
  33. rather than protect it. What is left to refuse is the host talking to
  34. itself, the unspecified address, link-local (which is where the cloud
  35. metadata endpoint lives), and the metadata hostnames.
  36. IP literals are classified with ``ipaddress`` rather than compared against a
  37. list of spellings, because 127.0.0.1, 127.0.0.2, 2130706433, 0177.0.0.1,
  38. 127.1 and ::ffff:127.0.0.1 all arrive at loopback and a list of strings only
  39. ever catches whichever one someone thought to write down. ``inet_aton``
  40. comes first because it accepts the legacy octal, decimal and short forms
  41. that ``ip_address`` rejects — the C resolvers behind aiohttp and ffmpeg
  42. accept them, so refusing to understand them here would only mean not seeing
  43. where the request is actually going.
  44. """
  45. host = hostname.lower()
  46. ip: ipaddress.IPv4Address | ipaddress.IPv6Address | None = None
  47. try:
  48. ip = ipaddress.ip_address(socket.inet_aton(host))
  49. except OSError:
  50. try:
  51. ip = ipaddress.ip_address(host)
  52. except ValueError:
  53. ip = None
  54. if ip is None:
  55. # A name, not an address. It is not resolved here on purpose: aiohttp
  56. # and ffmpeg each resolve independently afterwards, so a check here
  57. # decides nothing about where they end up (DNS rebinding), while a
  58. # lookup on every capture would break LAN cameras behind slow or
  59. # intermittent local DNS.
  60. if host == "localhost" or host.endswith(".localhost"):
  61. return "localhost"
  62. if host in ("metadata.google.internal", "metadata.google"):
  63. return "a cloud metadata service"
  64. return None
  65. # ::ffff:127.0.0.1 is loopback wearing an IPv6 spelling.
  66. mapped = getattr(ip, "ipv4_mapped", None)
  67. if mapped is not None:
  68. ip = mapped
  69. if ip.is_loopback:
  70. return "loopback"
  71. if ip.is_unspecified:
  72. return "the unspecified address"
  73. if ip.is_link_local:
  74. return "a link-local address (the cloud metadata range)"
  75. return None
  76. def _sanitize_camera_url(url: str, allowed_schemes: tuple[str, ...] = ("http", "https", "rtsp")) -> str | None:
  77. """Validate and sanitize camera URL, returning a safe reconstructed URL.
  78. This validates that the URL is well-formed, uses an allowed scheme, does not
  79. target the host itself or a cloud metadata service, and returns a URL
  80. reconstructed from the validated components.
  81. Note: This intentionally allows user-provided URLs as that is the
  82. purpose of external camera configuration. Local network IPs are
  83. allowed since cameras are typically on the same LAN.
  84. Args:
  85. url: URL to validate and sanitize
  86. allowed_schemes: Tuple of allowed URL schemes
  87. Returns:
  88. Sanitized URL string if valid, None otherwise
  89. """
  90. try:
  91. parsed = urlparse(url)
  92. if not parsed.scheme or not parsed.netloc:
  93. return None
  94. # Validate scheme against allowlist
  95. scheme = parsed.scheme.lower()
  96. if scheme not in allowed_schemes:
  97. return None
  98. hostname = parsed.hostname or ""
  99. if not hostname:
  100. return None
  101. blocked = _blocked_host_reason(hostname)
  102. if blocked:
  103. logger.warning("Blocked camera URL targeting %s: %s", blocked, hostname)
  104. return None
  105. # Reconstruct URL from validated components to break taint chain
  106. # This creates a new string from validated parts
  107. #
  108. # The credentials are carried across verbatim from netloc rather than
  109. # via parsed.username/.password, which urlparse has already percent-
  110. # decoded: re-emitting those would corrupt any password containing an
  111. # @ or a :. They have to survive at all because most RTSP cameras — and
  112. # a fair number of MJPEG ones — carry their login in the URL, and
  113. # dropping it turns every one of them into an authentication failure.
  114. netloc = parsed.netloc
  115. userinfo = f"{netloc.rsplit('@', 1)[0]}@" if "@" in netloc else ""
  116. # parsed.hostname has already stripped the brackets off an IPv6 literal;
  117. # without them back the result is not a URL any client can parse.
  118. host_str = f"[{hostname}]" if ":" in hostname else hostname
  119. port_str = f":{parsed.port}" if parsed.port else ""
  120. path = parsed.path or ""
  121. query = f"?{parsed.query}" if parsed.query else ""
  122. fragment = f"#{parsed.fragment}" if parsed.fragment else ""
  123. # Build sanitized URL from validated components
  124. sanitized = f"{scheme}://{userinfo}{host_str}{port_str}{path}{query}{fragment}"
  125. return sanitized
  126. except ValueError:
  127. return None
  128. def _validate_camera_url(url: str, allowed_schemes: tuple[str, ...] = ("http", "https", "rtsp")) -> bool:
  129. """Validate camera URL format (legacy wrapper).
  130. Args:
  131. url: URL to validate
  132. allowed_schemes: Tuple of allowed URL schemes
  133. Returns:
  134. True if URL is valid, False otherwise
  135. """
  136. return _sanitize_camera_url(url, allowed_schemes) is not 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. async def _capture_mjpeg_frame(url: str, timeout: int) -> bytes | None:
  456. """Extract a single representative frame from an MJPEG stream.
  457. Many MJPEG sources — go2rtc most notably (#1177), and several IP cameras —
  458. emit a "warm-up" frame on the byte that follows connection accept: usually
  459. the last keyframe held in the encoder, which is often black or stale until
  460. the encoder catches up to live content. To return a frame that's actually
  461. representative of the scene we read past the first frame and return the
  462. second; if the connection closes / times out / hits the buffer cap before
  463. a second frame ever arrives we fall back to the first so callers still
  464. get *something* (better than degrading slow / single-frame streams to None,
  465. which would regress every code path that consumed pre-fix behaviour).
  466. Note: this function intentionally makes requests to user-configured URLs.
  467. External camera support requires connecting to user-specified camera
  468. endpoints. URL is sanitized and dangerous destinations are blocked.
  469. """
  470. safe_url = _sanitize_camera_url(url, ("http", "https"))
  471. if not safe_url:
  472. logger.error("Invalid MJPEG URL format: %s...", redact_url_credentials(url)[:50])
  473. return None
  474. jpeg_start = b"\xff\xd8"
  475. jpeg_end = b"\xff\xd9"
  476. first_frame: bytes | None = None # warm-up frame; fallback if no second arrives
  477. buffer = b""
  478. try:
  479. async with (
  480. aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session,
  481. session.get(safe_url) as response,
  482. ):
  483. if response.status != 200:
  484. logger.error("MJPEG stream returned status %s", response.status)
  485. return None
  486. async for chunk in response.content.iter_chunked(8192):
  487. buffer += chunk
  488. # A single chunk can carry multiple frames (e.g. high-FPS sources)
  489. # or a partial frame. Drain every complete frame we already have
  490. # before pulling the next chunk.
  491. while True:
  492. start_idx = buffer.find(jpeg_start)
  493. if start_idx == -1:
  494. # No frame start yet — drop trailing garbage, keep waiting.
  495. break
  496. end_idx = buffer.find(jpeg_end, start_idx + 2)
  497. if end_idx == -1:
  498. # Partial frame; trim already-discarded prefix so the
  499. # buffer stays bounded across long-running streams.
  500. if start_idx > 0:
  501. buffer = buffer[start_idx:]
  502. break
  503. frame = buffer[start_idx : end_idx + 2]
  504. buffer = buffer[end_idx + 2 :]
  505. if first_frame is None:
  506. first_frame = frame # warm-up; keep but don't return yet
  507. continue
  508. return frame # representative second frame
  509. if len(buffer) > 5 * 1024 * 1024: # 5MB limit
  510. logger.warning("MJPEG buffer exceeded 5MB without finding frame")
  511. break # exit chunk loop, fall through to first_frame fallback
  512. except TimeoutError:
  513. logger.warning("MJPEG frame capture timed out after %ss", timeout)
  514. except (aiohttp.ClientError, OSError) as e:
  515. logger.error("MJPEG frame capture failed: %s", e)
  516. # Stream ended / timed out / buffer cap before a second frame arrived.
  517. # Return whatever warm-up frame we managed to read; better an iffy frame
  518. # than None for callers that need *some* image (snapshot UX, plate-detect
  519. # CV, finish photo). None only if no frame ever arrived at all.
  520. return first_frame
  521. async def _capture_rtsp_frame(url: str, timeout: int) -> bytes | None:
  522. """Capture frame from RTSP using ffmpeg.
  523. For rtsps:// URLs, a local TLS proxy is used to avoid GnuTLS issues.
  524. Note: this function intentionally connects to user-configured URLs, the same
  525. as the MJPEG and snapshot paths. The URL is sanitized and dangerous
  526. destinations are blocked before it reaches ffmpeg.
  527. """
  528. ffmpeg = get_ffmpeg_path()
  529. if not ffmpeg:
  530. logger.error("ffmpeg not found - required for RTSP capture")
  531. return None
  532. # ffmpeg's -i accepts every protocol it was built with, so an unchecked URL
  533. # here is a request to any host and scheme the caller names, not merely to a
  534. # camera. Restricting the scheme to RTSP is what keeps this a camera fetch.
  535. safe_url = _sanitize_camera_url(url, ("rtsp", "rtsps"))
  536. if not safe_url:
  537. logger.error("Invalid RTSP URL: %s...", redact_url_credentials(url)[:50])
  538. return None
  539. # If rtsps://, use TLS proxy
  540. proxy_server = None
  541. effective_url = safe_url
  542. if safe_url.lower().startswith("rtsps://"):
  543. try:
  544. from urllib.parse import urlparse
  545. from backend.app.services.camera import close_tls_proxy, create_tls_proxy
  546. parsed = urlparse(safe_url)
  547. target_port = parsed.port or 322
  548. proxy_port, proxy_server = await create_tls_proxy(parsed.hostname, target_port)
  549. userinfo = ""
  550. if parsed.username:
  551. userinfo = parsed.username
  552. if parsed.password:
  553. userinfo += f":{parsed.password}"
  554. userinfo += "@"
  555. # Points at loopback deliberately, and is built after the check
  556. # above rather than re-checked: the destination that mattered was
  557. # the one the caller named, and it has already been vetted.
  558. effective_url = f"rtsp://{userinfo}127.0.0.1:{proxy_port}{parsed.path}"
  559. if parsed.query:
  560. effective_url += f"?{parsed.query}"
  561. except Exception as e:
  562. logger.warning("Failed to create TLS proxy for RTSP capture, falling back: %s", e)
  563. effective_url = safe_url
  564. cmd = [
  565. ffmpeg,
  566. "-rtsp_transport",
  567. "tcp",
  568. # Belt and braces on the scheme check above: a demuxer that follows a
  569. # reference out of the stream cannot leave these protocols either.
  570. "-protocol_whitelist",
  571. _RTSP_PROTOCOL_WHITELIST,
  572. "-i",
  573. effective_url,
  574. "-frames:v",
  575. "1",
  576. "-f",
  577. "image2pipe",
  578. "-vcodec",
  579. "mjpeg",
  580. "-q:v",
  581. "2",
  582. "-",
  583. ]
  584. try:
  585. logger.debug("Running ffmpeg RTSP capture...")
  586. process = await asyncio.create_subprocess_exec(
  587. *cmd,
  588. stdout=asyncio.subprocess.PIPE,
  589. stderr=asyncio.subprocess.PIPE,
  590. )
  591. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  592. logger.debug(
  593. "ffmpeg returned: code=%s, stdout=%s bytes, stderr=%s bytes",
  594. process.returncode,
  595. len(stdout),
  596. len(stderr),
  597. )
  598. if process.returncode != 0:
  599. # The summariser masks the camera password the input URL carries.
  600. logger.error("ffmpeg RTSP capture failed: %s", summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT)
  601. return None
  602. if not stdout or len(stdout) < 100:
  603. logger.error("ffmpeg returned empty or too small frame")
  604. return None
  605. return stdout
  606. except TimeoutError:
  607. logger.warning("RTSP frame capture timed out after %ss", timeout)
  608. if process:
  609. process.kill()
  610. return None
  611. except OSError as e:
  612. logger.error("RTSP frame capture failed: %s", e)
  613. return None
  614. finally:
  615. if proxy_server:
  616. await close_tls_proxy(proxy_server)
  617. def _transcode_to_jpeg(data: bytes) -> bytes | None:
  618. """Decode an arbitrary still image (PNG/WebP/BMP/GIF/...) and re-encode as JPEG.
  619. Some camera/proxy snapshot endpoints serve stills as PNG or WebP rather than
  620. JPEG. A browser opened directly at the URL renders those fine, but our MJPEG
  621. ``multipart/x-mixed-replace`` stream hard-labels every part
  622. ``Content-Type: image/jpeg`` — so a non-JPEG payload makes the browser reject
  623. the frame and drop the whole stream ("connection lost", #1902). Transcoding to
  624. JPEG keeps the stream genuinely MJPEG and also keeps the JPEG-only downstream
  625. (plate detection, Obico, finish photo) working.
  626. Returns None if the bytes are not a decodable image (e.g. an HTML error page)
  627. or if the imaging libraries are unavailable — callers fall back to the raw
  628. bytes so behaviour is never worse than before.
  629. """
  630. try:
  631. import cv2
  632. import numpy as np
  633. except ImportError:
  634. return None
  635. try:
  636. img = cv2.imdecode(np.frombuffer(data, dtype=np.uint8), cv2.IMREAD_COLOR)
  637. if img is None:
  638. return None
  639. ok, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 85])
  640. if not ok:
  641. return None
  642. return buf.tobytes()
  643. except Exception as e: # cv2 raises cv2.error (a subclass of Exception) on bad input
  644. logger.debug("Snapshot transcode to JPEG failed: %s", e)
  645. return None
  646. async def _capture_snapshot(url: str, timeout: int) -> bytes | None:
  647. """Fetch snapshot from HTTP URL.
  648. Note: This function intentionally makes requests to user-configured URLs.
  649. External camera support requires connecting to user-specified camera endpoints.
  650. URL is sanitized and dangerous destinations are blocked.
  651. """
  652. # Sanitize URL - returns reconstructed URL from validated components
  653. safe_url = _sanitize_camera_url(url, ("http", "https"))
  654. if not safe_url:
  655. logger.error("Invalid snapshot URL format: %s...", redact_url_credentials(url)[:50])
  656. return None
  657. try:
  658. async with (
  659. aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session,
  660. session.get(safe_url) as response,
  661. ):
  662. if response.status != 200:
  663. logger.error("Snapshot URL returned status %s", response.status)
  664. return None
  665. data = await response.read()
  666. except TimeoutError:
  667. logger.warning("Snapshot capture timed out after %ss", timeout)
  668. return None
  669. except (aiohttp.ClientError, OSError) as e:
  670. logger.error("Snapshot capture failed: %s", e)
  671. return None
  672. # Fast path: already JPEG (SOI marker), stream it as-is (no decode/re-encode).
  673. if data.startswith(b"\xff\xd8"):
  674. return data
  675. # Not JPEG. Many snapshot endpoints serve PNG/WebP/BMP — transcode to JPEG so
  676. # the browser's MJPEG stream (and JPEG-only downstream) keep working instead of
  677. # dropping the connection (#1902). Run off the event loop: cv2 decode/encode is
  678. # CPU-bound and this can be polled at up to 15 fps while a camera view is open.
  679. transcoded = await asyncio.to_thread(_transcode_to_jpeg, data)
  680. if transcoded is not None:
  681. logger.debug(
  682. "Transcoded non-JPEG snapshot (%d bytes, header %s) to JPEG",
  683. len(data),
  684. data[:4].hex(),
  685. )
  686. return transcoded
  687. # Couldn't decode it as an image at all — most likely not an image response
  688. # (HTML error page, auth redirect, wrong URL). Return the raw bytes as a last
  689. # resort (unchanged behaviour) but log enough to debug.
  690. logger.warning(
  691. "External camera snapshot is not a decodable image "
  692. "(%d bytes, header %s) — verify the camera URL returns an image",
  693. len(data),
  694. data[:4].hex(),
  695. )
  696. return data
  697. async def test_connection(url: str, camera_type: str) -> dict:
  698. """Test camera connection.
  699. Returns:
  700. Dict with {success: bool, error?: str, resolution?: str, coalesced: bool}
  701. ``coalesced`` is True when the frame came from a capture that was already
  702. running rather than from a connection this test opened. Captures are shared
  703. (see ``capture_frame``), so a test that lands while Obico is polling — or
  704. while any other one-shot consumer is mid-capture — gets that frame back and
  705. would otherwise report a healthy connection it never made, which is the one
  706. answer a *connection test* must not give silently. Forcing an uncoalesced
  707. capture here would be worse: it would open the second handle to a
  708. single-reader device that this whole mechanism exists to prevent. So the
  709. test still shares, and says so. Mirrors the ``coalesced_capture`` code the
  710. built-in diagnostic reports for the same situation (camera_diagnose.py).
  711. """
  712. logger.info("Testing camera connection: type=%s, url=%s...", camera_type, redact_url_credentials(url)[:50])
  713. # Sampled before the call, while it can still distinguish "someone else is
  714. # mid-capture" from "I am the one capturing".
  715. coalesced = capture_in_flight(url, camera_type)
  716. try:
  717. frame = await capture_frame(url, camera_type, timeout=10)
  718. logger.info("Capture result: %s bytes%s", len(frame) if frame else 0, " (coalesced)" if coalesced else "")
  719. if frame:
  720. # Try to get resolution from JPEG header
  721. resolution = None
  722. try:
  723. # Simple JPEG dimension extraction
  724. # SOF0 marker is FF C0, followed by length, precision, height, width
  725. sof_markers = [b"\xff\xc0", b"\xff\xc1", b"\xff\xc2"]
  726. for marker in sof_markers:
  727. idx = frame.find(marker)
  728. if idx != -1 and idx + 9 <= len(frame):
  729. height = (frame[idx + 5] << 8) | frame[idx + 6]
  730. width = (frame[idx + 7] << 8) | frame[idx + 8]
  731. resolution = f"{width}x{height}"
  732. break
  733. except (IndexError, ValueError):
  734. pass # Resolution detection is optional; fall back to default
  735. return {"success": True, "resolution": resolution, "coalesced": coalesced}
  736. else:
  737. return {"success": False, "error": "Failed to capture frame from camera", "coalesced": coalesced}
  738. except Exception as e:
  739. # Sanitize error message - don't expose internal details
  740. error_type = type(e).__name__
  741. logger.error("Camera connection test failed: %s", e)
  742. return {"success": False, "error": f"Connection failed: {error_type}", "coalesced": coalesced}
  743. async def generate_mjpeg_stream(
  744. url: str,
  745. camera_type: str,
  746. fps: int = 10,
  747. *,
  748. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  749. on_frame: Callable[[bytes], None] | None = None,
  750. stop_event: asyncio.Event | None = None,
  751. ) -> AsyncGenerator[bytes, None]:
  752. """Generator yielding MJPEG frames for streaming.
  753. Args:
  754. url: Camera URL or USB device path
  755. camera_type: "mjpeg", "rtsp", "snapshot", or "usb"
  756. fps: Target frames per second
  757. on_process: Called with the spawned ffmpeg process for the ``usb`` and
  758. ``rtsp`` paths so the route layer can register it into the shared
  759. stream registries — that's what lets ``/camera/stop`` and the orphan
  760. janitor find and kill a leaked ffmpeg that's holding a USB device
  761. open (#2675). Without it the process is reachable only from this
  762. generator's own ``finally``, which an abrupt client disconnect can
  763. skip (same cancellation-timing class as #776).
  764. on_frame: Called with each RAW frame, before it is wrapped for the wire,
  765. so the route layer can publish it as the printer's buffered frame
  766. (#2707). It has to be a callback: what this generator yields is
  767. multipart-wrapped, so a consumer of the stream cannot recover the
  768. JPEG, and until now nothing populated the buffer for external
  769. cameras at all — leaving every one-shot consumer (layer timelapse,
  770. finish photo, Obico, plate check) with nothing to reuse and no
  771. option but to open a competing handle on a single-reader device.
  772. Exceptions are logged and swallowed: buffering must never be able
  773. to break the live stream.
  774. stop_event: When set, the reconnect loops stop retrying — so an explicit
  775. stop (which kills the current ffmpeg) doesn't immediately respawn a
  776. new process and reacquire the device.
  777. Yields:
  778. MJPEG frame data with HTTP multipart boundaries
  779. """
  780. frame_interval = 1.0 / max(fps, 1)
  781. last_frame_time = 0.0
  782. def _publish(frame: bytes) -> bytes:
  783. """Hand the raw frame to on_frame, then format it for the wire."""
  784. if on_frame is not None:
  785. try:
  786. on_frame(frame)
  787. except Exception:
  788. logger.exception("on_frame callback raised")
  789. return _format_mjpeg_frame(frame)
  790. if camera_type == "mjpeg":
  791. # Proxy MJPEG stream directly, with reconnect on timeout
  792. max_retries = 3
  793. for attempt in range(max_retries + 1):
  794. frame_yielded = False
  795. async for frame in _stream_mjpeg(url):
  796. frame_yielded = True
  797. current_time = asyncio.get_event_loop().time()
  798. if current_time - last_frame_time >= frame_interval:
  799. last_frame_time = current_time
  800. yield _publish(frame)
  801. if not frame_yielded or attempt == max_retries or (stop_event is not None and stop_event.is_set()):
  802. break
  803. logger.warning(
  804. "External MJPEG stream ended, reconnecting (attempt %d/%d)...",
  805. attempt + 1,
  806. max_retries,
  807. )
  808. await asyncio.sleep(2)
  809. elif camera_type == "rtsp":
  810. # Use ffmpeg to convert RTSP to MJPEG, with reconnect on timeout
  811. max_retries = 3
  812. for attempt in range(max_retries + 1):
  813. frame_yielded = False
  814. async for frame in _stream_rtsp(url, fps, on_process=on_process):
  815. frame_yielded = True
  816. yield _publish(frame)
  817. if not frame_yielded or attempt == max_retries or (stop_event is not None and stop_event.is_set()):
  818. break
  819. logger.warning(
  820. "External RTSP stream ended, reconnecting (attempt %d/%d)...",
  821. attempt + 1,
  822. max_retries,
  823. )
  824. await asyncio.sleep(2)
  825. elif camera_type == "usb":
  826. # Use ffmpeg to stream from USB camera
  827. async for frame in _stream_usb(url, fps, on_process=on_process):
  828. yield _publish(frame)
  829. elif camera_type == "snapshot":
  830. # Poll snapshot URL at interval
  831. while True:
  832. try:
  833. frame = await _capture_snapshot(url, timeout=10)
  834. if frame:
  835. yield _publish(frame)
  836. await asyncio.sleep(frame_interval)
  837. except asyncio.CancelledError:
  838. break
  839. except (aiohttp.ClientError, OSError) as e:
  840. logger.warning("Snapshot poll failed: %s", e)
  841. await asyncio.sleep(frame_interval)
  842. def _format_mjpeg_frame(frame: bytes) -> bytes:
  843. """Format frame for MJPEG HTTP response."""
  844. return (
  845. b"--frame\r\n"
  846. b"Content-Type: image/jpeg\r\n"
  847. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  848. b"\r\n" + frame + b"\r\n"
  849. )
  850. async def _stream_mjpeg(url: str) -> AsyncGenerator[bytes, None]:
  851. """Stream frames from MJPEG URL.
  852. Note: This function intentionally makes requests to user-configured URLs.
  853. External camera support requires connecting to user-specified camera endpoints.
  854. URL is sanitized and dangerous destinations are blocked.
  855. """
  856. # Sanitize URL - returns reconstructed URL from validated components
  857. safe_url = _sanitize_camera_url(url, ("http", "https"))
  858. if not safe_url:
  859. logger.error("Invalid MJPEG stream URL: %s...", redact_url_credentials(url)[:50])
  860. return
  861. try:
  862. timeout = aiohttp.ClientTimeout(total=None, sock_read=30)
  863. async with aiohttp.ClientSession(timeout=timeout) as session, session.get(safe_url) as response:
  864. if response.status != 200:
  865. logger.error("MJPEG stream returned status %s", response.status)
  866. return
  867. buffer = b""
  868. jpeg_start = b"\xff\xd8"
  869. jpeg_end = b"\xff\xd9"
  870. async for chunk in response.content.iter_chunked(8192):
  871. buffer += chunk
  872. # Extract complete frames from buffer
  873. while True:
  874. start_idx = buffer.find(jpeg_start)
  875. if start_idx == -1:
  876. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  877. break
  878. if start_idx > 0:
  879. buffer = buffer[start_idx:]
  880. end_idx = buffer.find(jpeg_end, 2)
  881. if end_idx == -1:
  882. break
  883. frame = buffer[: end_idx + 2]
  884. buffer = buffer[end_idx + 2 :]
  885. yield frame
  886. except asyncio.CancelledError:
  887. logger.info("MJPEG stream cancelled")
  888. except (aiohttp.ClientError, OSError) as e:
  889. logger.error("MJPEG stream error: %s", e)
  890. async def _stream_rtsp(
  891. url: str,
  892. fps: int,
  893. *,
  894. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  895. ) -> AsyncGenerator[bytes, None]:
  896. """Stream frames from RTSP URL via ffmpeg.
  897. For rtsps:// URLs, a local TLS proxy (Python OpenSSL) is used instead
  898. of relying on ffmpeg's GnuTLS backend, which has compatibility issues
  899. with some printer firmwares.
  900. Note: this function intentionally connects to user-configured URLs. The URL
  901. is sanitized and dangerous destinations are blocked before it reaches
  902. ffmpeg — see ``_capture_rtsp_frame``, which guards the one-shot path the
  903. same way.
  904. """
  905. ffmpeg = get_ffmpeg_path()
  906. if not ffmpeg:
  907. logger.error("ffmpeg not found - required for RTSP streaming")
  908. return
  909. from backend.app.services.camera import rtsp_socket_timeout_flag
  910. safe_url = _sanitize_camera_url(url, ("rtsp", "rtsps"))
  911. if not safe_url:
  912. logger.error("Invalid RTSP stream URL: %s...", redact_url_credentials(url)[:50])
  913. return
  914. # If the URL uses rtsps://, set up a TLS proxy so ffmpeg uses plain rtsp://
  915. proxy_server = None
  916. effective_url = safe_url
  917. if safe_url.lower().startswith("rtsps://"):
  918. try:
  919. from urllib.parse import urlparse
  920. from backend.app.services.camera import close_tls_proxy, create_tls_proxy
  921. parsed = urlparse(safe_url)
  922. target_port = parsed.port or 322
  923. proxy_port, proxy_server = await create_tls_proxy(parsed.hostname, target_port)
  924. # Rewrite URL: rtsps://user:pass@host:port/path → rtsp://user:pass@127.0.0.1:proxy/path
  925. userinfo = ""
  926. if parsed.username:
  927. userinfo = parsed.username
  928. if parsed.password:
  929. userinfo += f":{parsed.password}"
  930. userinfo += "@"
  931. # Loopback by design, and built after the check above rather than
  932. # re-checked — see the same rewrite in _capture_rtsp_frame.
  933. effective_url = f"rtsp://{userinfo}127.0.0.1:{proxy_port}{parsed.path}"
  934. if parsed.query:
  935. effective_url += f"?{parsed.query}"
  936. except Exception as e:
  937. logger.warning("Failed to create TLS proxy for RTSP, falling back to direct: %s", e)
  938. effective_url = safe_url
  939. cmd = [
  940. ffmpeg,
  941. "-rtsp_transport",
  942. "tcp",
  943. "-rtsp_flags",
  944. "prefer_tcp",
  945. "-protocol_whitelist",
  946. _RTSP_PROTOCOL_WHITELIST,
  947. # Socket I/O timeout name varies by ffmpeg version (#1504); see
  948. # `rtsp_socket_timeout_flag()` in services.camera.
  949. f"-{rtsp_socket_timeout_flag()}",
  950. "30000000",
  951. "-buffer_size",
  952. "1024000",
  953. "-max_delay",
  954. "500000",
  955. "-probesize",
  956. "32",
  957. "-analyzeduration",
  958. "0",
  959. "-fflags",
  960. "nobuffer",
  961. "-flags",
  962. "low_delay",
  963. "-i",
  964. effective_url,
  965. "-f",
  966. "mjpeg",
  967. "-q:v",
  968. "5",
  969. "-r",
  970. str(fps),
  971. "-an",
  972. "-",
  973. ]
  974. process = None
  975. try:
  976. process = await asyncio.create_subprocess_exec(
  977. *cmd,
  978. stdout=asyncio.subprocess.PIPE,
  979. stderr=asyncio.subprocess.PIPE,
  980. )
  981. # Register immediately — before the startup probe below — so a process
  982. # that hangs on connect (rather than exiting) is still reachable by the
  983. # stop endpoint / orphan janitor (#2675).
  984. if on_process is not None:
  985. on_process(process)
  986. # Brief check for immediate startup failures
  987. await asyncio.sleep(0.1)
  988. if process.returncode is not None:
  989. stderr = await process.stderr.read()
  990. # The summariser masks the camera password the input URL carries.
  991. logger.error(
  992. "ffmpeg RTSP stream failed immediately: %s", summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT
  993. )
  994. return
  995. buffer = b""
  996. jpeg_start = b"\xff\xd8"
  997. jpeg_end = b"\xff\xd9"
  998. while True:
  999. try:
  1000. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  1001. if not chunk:
  1002. break
  1003. buffer += chunk
  1004. # Extract complete frames
  1005. while True:
  1006. start_idx = buffer.find(jpeg_start)
  1007. if start_idx == -1:
  1008. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  1009. break
  1010. if start_idx > 0:
  1011. buffer = buffer[start_idx:]
  1012. end_idx = buffer.find(jpeg_end, 2)
  1013. if end_idx == -1:
  1014. break
  1015. frame = buffer[: end_idx + 2]
  1016. buffer = buffer[end_idx + 2 :]
  1017. yield frame
  1018. except TimeoutError:
  1019. logger.warning("RTSP stream read timeout")
  1020. break
  1021. except asyncio.CancelledError:
  1022. logger.info("RTSP stream cancelled")
  1023. except OSError as e:
  1024. logger.error("RTSP stream error: %s", e)
  1025. finally:
  1026. if process and process.returncode is None:
  1027. process.terminate()
  1028. try:
  1029. await asyncio.wait_for(process.wait(), timeout=2.0)
  1030. except TimeoutError:
  1031. process.kill()
  1032. await process.wait()
  1033. if proxy_server:
  1034. await close_tls_proxy(proxy_server)
  1035. async def _stream_usb(
  1036. device: str,
  1037. fps: int,
  1038. *,
  1039. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  1040. ) -> AsyncGenerator[bytes, None]:
  1041. """Stream frames from USB camera via ffmpeg."""
  1042. ffmpeg = get_ffmpeg_path()
  1043. if not ffmpeg:
  1044. logger.error("ffmpeg not found - required for USB camera streaming")
  1045. return
  1046. # Same validation as the one-shot path: a prefix check accepted
  1047. # /dev/video/../../<anything that exists>, which -f v4l2 would then refuse
  1048. # rather than the check refusing it.
  1049. safe_device = _safe_usb_device_path(device)
  1050. if not safe_device:
  1051. return
  1052. device = safe_device
  1053. # ffmpeg command to stream from USB camera (v4l2)
  1054. cmd = [
  1055. ffmpeg,
  1056. "-f",
  1057. "v4l2",
  1058. "-framerate",
  1059. str(fps),
  1060. "-i",
  1061. device,
  1062. "-f",
  1063. "mjpeg",
  1064. "-q:v",
  1065. "5",
  1066. "-r",
  1067. str(fps),
  1068. "-",
  1069. ]
  1070. process = None
  1071. try:
  1072. logger.info("Starting USB camera stream from %s at %s fps", device, fps)
  1073. process = await asyncio.create_subprocess_exec(
  1074. *cmd,
  1075. stdout=asyncio.subprocess.PIPE,
  1076. stderr=asyncio.subprocess.PIPE,
  1077. )
  1078. # Register immediately — before the startup probe below — so a process
  1079. # that hangs in open()/ioctl on a still-locked device (rather than
  1080. # exiting with a "busy" error) is still reachable by the stop endpoint /
  1081. # orphan janitor (#2675).
  1082. if on_process is not None:
  1083. on_process(process)
  1084. # Give ffmpeg a moment to start and check for immediate failures
  1085. await asyncio.sleep(0.5)
  1086. if process.returncode is not None:
  1087. stderr = await process.stderr.read()
  1088. logger.error(
  1089. "ffmpeg USB stream failed immediately: %s", summarize_ffmpeg_stderr(stderr) or NO_FFMPEG_OUTPUT
  1090. )
  1091. return
  1092. buffer = b""
  1093. jpeg_start = b"\xff\xd8"
  1094. jpeg_end = b"\xff\xd9"
  1095. while True:
  1096. try:
  1097. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  1098. if not chunk:
  1099. break
  1100. buffer += chunk
  1101. # Extract complete frames
  1102. while True:
  1103. start_idx = buffer.find(jpeg_start)
  1104. if start_idx == -1:
  1105. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  1106. break
  1107. if start_idx > 0:
  1108. buffer = buffer[start_idx:]
  1109. end_idx = buffer.find(jpeg_end, 2)
  1110. if end_idx == -1:
  1111. break
  1112. frame = buffer[: end_idx + 2]
  1113. buffer = buffer[end_idx + 2 :]
  1114. yield frame
  1115. except TimeoutError:
  1116. logger.warning("USB stream read timeout")
  1117. break
  1118. except asyncio.CancelledError:
  1119. logger.info("USB stream cancelled")
  1120. except OSError as e:
  1121. logger.error("USB stream error: %s", e)
  1122. finally:
  1123. if process and process.returncode is None:
  1124. process.terminate()
  1125. try:
  1126. await asyncio.wait_for(process.wait(), timeout=2.0)
  1127. except TimeoutError:
  1128. process.kill()
  1129. await process.wait()