external_camera.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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. logger = logging.getLogger(__name__)
  20. # Protocols ffmpeg may use for an RTSP input. RTSP negotiates its media
  21. # transport at runtime, so the transports have to be here alongside rtsp itself;
  22. # tls and crypto cover encrypted variants. Everything ffmpeg would otherwise
  23. # accept behind an -i — file, http, tcp to anywhere, concat — is left out, so a
  24. # stream that references something outside itself cannot pull it in.
  25. _RTSP_PROTOCOL_WHITELIST = "rtsp,rtp,udp,tcp,tls,crypto"
  26. def _blocked_host_reason(hostname: str) -> str | None:
  27. """Describe why *hostname* is a destination we refuse to fetch, or None to allow it.
  28. Camera URLs are user-supplied and reach the network — over aiohttp for the
  29. HTTP types, and as an ``ffmpeg -i`` argument for RTSP — so this is where the
  30. SSRF boundary sits. LAN addresses are deliberately allowed: cameras live on
  31. the same network as Bambuddy, and blocking RFC-1918 would remove the feature
  32. rather than protect it. What is left to refuse is the host talking to
  33. itself, the unspecified address, link-local (which is where the cloud
  34. metadata endpoint lives), and the metadata hostnames.
  35. IP literals are classified with ``ipaddress`` rather than compared against a
  36. list of spellings, because 127.0.0.1, 127.0.0.2, 2130706433, 0177.0.0.1,
  37. 127.1 and ::ffff:127.0.0.1 all arrive at loopback and a list of strings only
  38. ever catches whichever one someone thought to write down. ``inet_aton``
  39. comes first because it accepts the legacy octal, decimal and short forms
  40. that ``ip_address`` rejects — the C resolvers behind aiohttp and ffmpeg
  41. accept them, so refusing to understand them here would only mean not seeing
  42. where the request is actually going.
  43. """
  44. host = hostname.lower()
  45. ip: ipaddress.IPv4Address | ipaddress.IPv6Address | None = None
  46. try:
  47. ip = ipaddress.ip_address(socket.inet_aton(host))
  48. except OSError:
  49. try:
  50. ip = ipaddress.ip_address(host)
  51. except ValueError:
  52. ip = None
  53. if ip is None:
  54. # A name, not an address. It is not resolved here on purpose: aiohttp
  55. # and ffmpeg each resolve independently afterwards, so a check here
  56. # decides nothing about where they end up (DNS rebinding), while a
  57. # lookup on every capture would break LAN cameras behind slow or
  58. # intermittent local DNS.
  59. if host == "localhost" or host.endswith(".localhost"):
  60. return "localhost"
  61. if host in ("metadata.google.internal", "metadata.google"):
  62. return "a cloud metadata service"
  63. return None
  64. # ::ffff:127.0.0.1 is loopback wearing an IPv6 spelling.
  65. mapped = getattr(ip, "ipv4_mapped", None)
  66. if mapped is not None:
  67. ip = mapped
  68. if ip.is_loopback:
  69. return "loopback"
  70. if ip.is_unspecified:
  71. return "the unspecified address"
  72. if ip.is_link_local:
  73. return "a link-local address (the cloud metadata range)"
  74. return None
  75. def _sanitize_camera_url(url: str, allowed_schemes: tuple[str, ...] = ("http", "https", "rtsp")) -> str | None:
  76. """Validate and sanitize camera URL, returning a safe reconstructed URL.
  77. This validates that the URL is well-formed, uses an allowed scheme, does not
  78. target the host itself or a cloud metadata service, and returns a URL
  79. reconstructed from the validated components.
  80. Note: This intentionally allows user-provided URLs as that is the
  81. purpose of external camera configuration. Local network IPs are
  82. allowed since cameras are typically on the same LAN.
  83. Args:
  84. url: URL to validate and sanitize
  85. allowed_schemes: Tuple of allowed URL schemes
  86. Returns:
  87. Sanitized URL string if valid, None otherwise
  88. """
  89. try:
  90. parsed = urlparse(url)
  91. if not parsed.scheme or not parsed.netloc:
  92. return None
  93. # Validate scheme against allowlist
  94. scheme = parsed.scheme.lower()
  95. if scheme not in allowed_schemes:
  96. return None
  97. hostname = parsed.hostname or ""
  98. if not hostname:
  99. return None
  100. blocked = _blocked_host_reason(hostname)
  101. if blocked:
  102. logger.warning("Blocked camera URL targeting %s: %s", blocked, hostname)
  103. return None
  104. # Reconstruct URL from validated components to break taint chain
  105. # This creates a new string from validated parts
  106. #
  107. # The credentials are carried across verbatim from netloc rather than
  108. # via parsed.username/.password, which urlparse has already percent-
  109. # decoded: re-emitting those would corrupt any password containing an
  110. # @ or a :. They have to survive at all because most RTSP cameras — and
  111. # a fair number of MJPEG ones — carry their login in the URL, and
  112. # dropping it turns every one of them into an authentication failure.
  113. netloc = parsed.netloc
  114. userinfo = f"{netloc.rsplit('@', 1)[0]}@" if "@" in netloc else ""
  115. # parsed.hostname has already stripped the brackets off an IPv6 literal;
  116. # without them back the result is not a URL any client can parse.
  117. host_str = f"[{hostname}]" if ":" in hostname else hostname
  118. port_str = f":{parsed.port}" if parsed.port else ""
  119. path = parsed.path or ""
  120. query = f"?{parsed.query}" if parsed.query else ""
  121. fragment = f"#{parsed.fragment}" if parsed.fragment else ""
  122. # Build sanitized URL from validated components
  123. sanitized = f"{scheme}://{userinfo}{host_str}{port_str}{path}{query}{fragment}"
  124. return sanitized
  125. except ValueError:
  126. return None
  127. def _validate_camera_url(url: str, allowed_schemes: tuple[str, ...] = ("http", "https", "rtsp")) -> bool:
  128. """Validate camera URL format (legacy wrapper).
  129. Args:
  130. url: URL to validate
  131. allowed_schemes: Tuple of allowed URL schemes
  132. Returns:
  133. True if URL is valid, False otherwise
  134. """
  135. return _sanitize_camera_url(url, allowed_schemes) is not None
  136. def list_usb_cameras() -> list[dict]:
  137. """List available USB cameras (V4L2 devices on Linux).
  138. Returns:
  139. List of dicts with {device: str, name: str, capabilities: list}
  140. """
  141. cameras = []
  142. video_devices = sorted(Path("/dev").glob("video*"))
  143. for device in video_devices:
  144. device_path = str(device)
  145. info = {"device": device_path, "name": device.name, "capabilities": []}
  146. # Try to get device info via v4l2-ctl
  147. v4l2_ctl = shutil.which("v4l2-ctl")
  148. if v4l2_ctl:
  149. import subprocess
  150. try:
  151. result = subprocess.run(
  152. [v4l2_ctl, "-d", device_path, "--info"],
  153. capture_output=True,
  154. text=True,
  155. timeout=5,
  156. )
  157. if result.returncode == 0:
  158. # Parse device name from output
  159. for line in result.stdout.splitlines():
  160. if "Card type" in line:
  161. info["name"] = line.split(":", 1)[1].strip()
  162. elif "Driver name" in line:
  163. info["driver"] = line.split(":", 1)[1].strip()
  164. # Check if device supports video capture
  165. result = subprocess.run(
  166. [v4l2_ctl, "-d", device_path, "--list-formats"],
  167. capture_output=True,
  168. text=True,
  169. timeout=5,
  170. )
  171. if result.returncode == 0 and result.stdout.strip():
  172. info["capabilities"].append("capture")
  173. # Parse available formats
  174. formats = re.findall(r"'(\w+)'", result.stdout)
  175. info["formats"] = list(set(formats))
  176. except (subprocess.TimeoutExpired, Exception) as e:
  177. logger.debug("v4l2-ctl failed for %s: %s", device_path, e)
  178. # Only include devices that look like video capture devices
  179. # Skip metadata devices (typically odd numbered like video1, video3)
  180. try:
  181. device_num = int(device.name.replace("video", ""))
  182. # Even numbered devices are usually capture, odd are metadata
  183. # But also check if we got capabilities
  184. if info.get("capabilities") or device_num % 2 == 0:
  185. cameras.append(info)
  186. except ValueError:
  187. cameras.append(info)
  188. return cameras
  189. def get_ffmpeg_path() -> str | None:
  190. """Get the path to ffmpeg executable."""
  191. # Try shutil.which first
  192. path = shutil.which("ffmpeg")
  193. if path:
  194. return path
  195. # Check common locations (systemd services may have limited PATH)
  196. for common_path in ["/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/opt/homebrew/bin/ffmpeg"]:
  197. if Path(common_path).exists():
  198. return common_path
  199. return None
  200. # In-flight one-shot captures, keyed by (url, camera_type, snapshot_url) —
  201. # the tuple that actually identifies the physical resource being contended
  202. # (#2707 comment thread, following #2705's shape for the built-in path).
  203. #
  204. # V4L2 USB devices allow exactly one open handle, and is_stream_active() /
  205. # try_get_active_buffered_frame() (#2707) only stop a one-shot capturer from
  206. # competing with the fan-out live view. They do nothing for capturer-vs-
  207. # capturer with no viewer attached, where every consumer correctly concludes
  208. # it isn't competing with a viewer and then collides with the others -
  209. # exactly the #2705 report, just for this module's callers instead of
  210. # capture_camera_frame_bytes()'s (Obico polling, the in-print frame bank,
  211. # the finish-photo moment, plate detection, and the notification snapshot
  212. # all reach capture_frame() independently).
  213. #
  214. # snapshot_url is part of the key (not just url/camera_type) because it
  215. # routes to a completely different endpoint (#1177) - two printers that
  216. # share a camera_url but differ only in snapshot_url must not coalesce.
  217. _inflight_captures: dict[tuple[str, str, str | None], asyncio.Task[bytes | None]] = {}
  218. def capture_in_flight(url: str, camera_type: str, snapshot_url: str | None = None) -> bool:
  219. """Return True iff a one-shot capture for this key is running right now.
  220. Mirrors camera.py's capture_in_flight() for the built-in path - for a
  221. caller that needs to know it will JOIN someone else's capture rather
  222. than open its own connection. Ordinary consumers should ignore this:
  223. they want "a recent frame", and capture_frame() already does the right
  224. thing for them.
  225. """
  226. task = _inflight_captures.get((url, camera_type, snapshot_url))
  227. return task is not None and not task.done()
  228. def _discard_inflight_capture(key: tuple[str, str, str | None], task: asyncio.Task) -> None:
  229. """Done-callback: drop the finished task from the in-flight registry.
  230. Guarded on identity so a slow task that finishes after a newer capture
  231. has registered for the same key can't evict its successor.
  232. Also retrieves the exception, if any: the leader normally awaits the
  233. task and would surface it, but a leader whose own caller was cancelled
  234. leaves nobody to collect it, and an unretrieved task exception is
  235. logged by asyncio as a warning with a traceback at an arbitrary later
  236. point otherwise.
  237. """
  238. if _inflight_captures.get(key) is task:
  239. del _inflight_captures[key]
  240. if not task.cancelled() and task.exception() is not None:
  241. logger.debug("In-flight external-camera capture for %s ended in an exception", _log_key(key))
  242. def _log_key(key: tuple[str, str, str | None]) -> str:
  243. """Render an in-flight key for a log line, with credentials redacted.
  244. Unlike camera.py's coalescing — which is keyed by IP address and so has
  245. nothing to hide — these keys carry the camera URL, and an RTSP camera URL
  246. routinely embeds ``user:pass@``. Redact before truncating: slicing first
  247. can cut the URL short of the ``@`` the pattern anchors on and leave the
  248. password in the log, which is why every other URL log in this module does
  249. it in this order.
  250. """
  251. return redact_url_credentials(key[0])[:50] if key[0] else "None"
  252. async def capture_frame(
  253. url: str,
  254. camera_type: str,
  255. timeout: int = 15,
  256. snapshot_url: str | None = None,
  257. ) -> bytes | None:
  258. """Capture single frame from external camera.
  259. Args:
  260. url: Live-stream URL (MJPEG stream, RTSP URL, HTTP snapshot URL, or USB device path).
  261. camera_type: "mjpeg", "rtsp", "snapshot", or "usb".
  262. timeout: Connection timeout in seconds. Applies to this caller's own
  263. wait, including when it joins another caller's capture - call
  264. sites disagree about the value, and a follower must not silently
  265. inherit the leader's deadline in either direction.
  266. snapshot_url: Optional override for single-frame capture. When set, fetched
  267. via plain HTTP GET regardless of `camera_type`. Bypasses MJPEG warm-up
  268. handling on sources that expose a dedicated frame endpoint (e.g. go2rtc's
  269. `/api/frame.jpeg` reliably returns a clean image while the MJPEG stream's
  270. first frame is often the encoder's stale keyframe). #1177.
  271. Returns:
  272. JPEG bytes or None on failure
  273. Concurrent callers for the same (url, camera_type, snapshot_url) share
  274. one capture (#2705-shape fix, filed for the external-camera path as a
  275. follow-up on #2707): the first opens the connection, everyone arriving
  276. while it's in flight awaits the same result. This coalesces; it does
  277. not cache - a call that arrives after the previous capture finished
  278. always captures fresh, since plate detection and the finish-photo path
  279. judge a running print from these frames and a stale one there is worse
  280. than a slow one (#1397).
  281. """
  282. key = (url, camera_type, snapshot_url)
  283. # A follower whose leader fails takes a turn of its own rather than
  284. # inheriting a failure it never had a chance to avoid - by then the
  285. # leader has finished, so there's no connection left to compete with.
  286. # Bounded at two rounds: if the capture we joined AND its replacement
  287. # both failed, a third attempt won't help, and this caller has already
  288. # spent its patience.
  289. for _ in range(2):
  290. leader = _inflight_captures.get(key)
  291. if leader is None or leader.done():
  292. break
  293. try:
  294. frame = await asyncio.wait_for(asyncio.shield(leader), timeout=timeout)
  295. except TimeoutError:
  296. # shield() keeps the capture running for whoever else is still
  297. # waiting on it - giving up is this caller's decision alone.
  298. logger.warning(
  299. "Gave up waiting %ss on the in-flight external-camera capture for %s", timeout, _log_key(key)
  300. )
  301. return None
  302. except asyncio.CancelledError:
  303. # Distinguish "the capture I joined was cancelled" from "I was
  304. # cancelled". Only the former is ours to recover from.
  305. if not leader.cancelled():
  306. raise
  307. logger.info("In-flight external-camera capture for %s was cancelled; capturing our own", _log_key(key))
  308. continue
  309. if frame is not None:
  310. logger.debug(
  311. "Reusing in-flight external-camera capture for %s: %d bytes (no second connection opened)",
  312. _log_key(key),
  313. len(frame),
  314. )
  315. return frame
  316. logger.debug("In-flight external-camera capture for %s failed; capturing our own", _log_key(key))
  317. else:
  318. return None
  319. task = asyncio.create_task(_capture_frame_uncoalesced(url, camera_type, timeout, snapshot_url))
  320. _inflight_captures[key] = task
  321. task.add_done_callback(functools.partial(_discard_inflight_capture, key))
  322. # No wait_for here: this caller IS the capture, and each dispatched
  323. # _capture_* function already enforces `timeout` internally, where it
  324. # can also kill the ffmpeg process - a second deadline on top would
  325. # abandon the subprocess instead of killing it. shield() so a cancelled
  326. # leader (a client navigating away mid-request is routine) doesn't take
  327. # the capture down with it - followers already waiting on it still get
  328. # their frame.
  329. return await asyncio.shield(task)
  330. async def _capture_frame_uncoalesced(
  331. url: str,
  332. camera_type: str,
  333. timeout: int,
  334. snapshot_url: str | None,
  335. ) -> bytes | None:
  336. """Open a connection and capture one frame. See capture_frame().
  337. Callers want that wrapper, not this: it opens a connection
  338. unconditionally, which is the collision #2705/#2707 are about.
  339. Failure is reported as ``None``, never as an exception. That is load-
  340. bearing now that captures are shared: the coalescing wrapper hands one
  341. task's outcome to every caller waiting on it, and it can only give a
  342. follower its own turn for an outcome it can recognise. An exception
  343. escaping here would instead propagate to every follower at once —
  344. turning one caller's failure into N — and none of them would retry.
  345. The per-type helpers below each catch what they expect and return None,
  346. but they catch narrowly (``aiohttp.ClientError``/``OSError``/timeouts),
  347. so this is the structural guarantee rather than one contingent on their
  348. coverage. Mirrors ``_capture_camera_frame_bytes_uncoalesced`` in
  349. camera.py, which ends in the same blanket catch for the same reason.
  350. """
  351. try:
  352. if snapshot_url:
  353. # Redact before truncating — slicing first can cut the URL short of the
  354. # ``@`` the pattern anchors on and leave the password in the log.
  355. logger.debug("capture_frame using snapshot override url=%s...", redact_url_credentials(snapshot_url)[:50])
  356. return await _capture_snapshot(snapshot_url, timeout)
  357. logger.debug(
  358. "capture_frame called: type=%s, url=%s...",
  359. camera_type,
  360. redact_url_credentials(url)[:50] if url else "None",
  361. )
  362. if camera_type == "mjpeg":
  363. return await _capture_mjpeg_frame(url, timeout)
  364. elif camera_type == "rtsp":
  365. return await _capture_rtsp_frame(url, timeout)
  366. elif camera_type == "snapshot":
  367. return await _capture_snapshot(url, timeout)
  368. elif camera_type == "usb":
  369. return await _capture_usb_frame(url, timeout)
  370. else:
  371. logger.warning("Unknown camera type: %s", camera_type)
  372. return None
  373. except asyncio.CancelledError:
  374. # Cancellation is not a capture failure and must stay distinguishable:
  375. # the wrapper checks ``leader.cancelled()`` to decide whether a
  376. # follower may take its own turn.
  377. raise
  378. except Exception:
  379. logger.exception("External camera capture failed for %s", redact_url_credentials(url)[:50] if url else "None")
  380. return None
  381. def _safe_usb_device_path(device: str) -> str | None:
  382. """Rebuild a /dev/videoN path from a validated device number, or None.
  383. Validate device path - must be /dev/videoN format where N is 0-99. This
  384. prevents path traversal by using a strict allowlist approach: the returned
  385. path is built from an integer, which cannot carry a traversal, rather than
  386. from any part of the caller's string.
  387. Returns None if the device does not exist, so a caller cannot hand ffmpeg a
  388. path to something that is not a device node.
  389. """
  390. device_match = re.match(r"^/dev/video(\d{1,2})$", device)
  391. if not device_match:
  392. logger.error("Invalid USB device path format: %s", device)
  393. return None
  394. # Convert to integer to break taint chain - integers cannot contain path traversal
  395. # lgtm[py/path-injection] - device_num is validated integer 0-99
  396. device_num = int(device_match.group(1)) # Safe: regex guarantees 1-2 digits
  397. # Construct safe path from validated integer (completely untainted)
  398. safe_device_path = Path(f"/dev/video{device_num}") # lgtm[py/path-injection]
  399. if not safe_device_path.exists():
  400. logger.error("USB device does not exist: %s", safe_device_path)
  401. return None
  402. return str(safe_device_path) # lgtm[py/path-injection]
  403. async def _capture_usb_frame(device: str, timeout: int) -> bytes | None:
  404. """Capture frame from USB camera using ffmpeg."""
  405. ffmpeg = get_ffmpeg_path()
  406. if not ffmpeg:
  407. logger.error("ffmpeg not found - required for USB camera capture")
  408. return None
  409. safe_device = _safe_usb_device_path(device)
  410. if not safe_device:
  411. return None
  412. # Use the safe path for ffmpeg - this is a hardcoded /dev/videoN path
  413. device = safe_device # lgtm[py/path-injection]
  414. # Use ffmpeg to grab a single frame from USB camera
  415. cmd = [
  416. ffmpeg,
  417. "-f",
  418. "v4l2",
  419. "-i",
  420. device,
  421. "-frames:v",
  422. "1",
  423. "-f",
  424. "image2pipe",
  425. "-vcodec",
  426. "mjpeg",
  427. "-q:v",
  428. "2",
  429. "-",
  430. ]
  431. try:
  432. logger.debug("Running USB capture: %s", " ".join(cmd))
  433. process = await asyncio.create_subprocess_exec(
  434. *cmd,
  435. stdout=asyncio.subprocess.PIPE,
  436. stderr=asyncio.subprocess.PIPE,
  437. )
  438. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  439. if process.returncode != 0:
  440. logger.error("ffmpeg USB capture failed: %s", stderr.decode()[:200])
  441. return None
  442. if not stdout or len(stdout) < 100:
  443. logger.error("ffmpeg returned empty or too small frame from USB camera")
  444. return None
  445. return stdout
  446. except TimeoutError:
  447. logger.warning("USB frame capture timed out after %ss", timeout)
  448. if process:
  449. process.kill()
  450. return None
  451. except OSError as e:
  452. logger.error("USB frame capture failed: %s", e)
  453. return None
  454. async def _capture_mjpeg_frame(url: str, timeout: int) -> bytes | None:
  455. """Extract a single representative frame from an MJPEG stream.
  456. Many MJPEG sources — go2rtc most notably (#1177), and several IP cameras —
  457. emit a "warm-up" frame on the byte that follows connection accept: usually
  458. the last keyframe held in the encoder, which is often black or stale until
  459. the encoder catches up to live content. To return a frame that's actually
  460. representative of the scene we read past the first frame and return the
  461. second; if the connection closes / times out / hits the buffer cap before
  462. a second frame ever arrives we fall back to the first so callers still
  463. get *something* (better than degrading slow / single-frame streams to None,
  464. which would regress every code path that consumed pre-fix behaviour).
  465. Note: this function intentionally makes requests to user-configured URLs.
  466. External camera support requires connecting to user-specified camera
  467. endpoints. URL is sanitized and dangerous destinations are blocked.
  468. """
  469. safe_url = _sanitize_camera_url(url, ("http", "https"))
  470. if not safe_url:
  471. logger.error("Invalid MJPEG URL format: %s...", redact_url_credentials(url)[:50])
  472. return None
  473. jpeg_start = b"\xff\xd8"
  474. jpeg_end = b"\xff\xd9"
  475. first_frame: bytes | None = None # warm-up frame; fallback if no second arrives
  476. buffer = b""
  477. try:
  478. async with (
  479. aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session,
  480. session.get(safe_url) as response,
  481. ):
  482. if response.status != 200:
  483. logger.error("MJPEG stream returned status %s", response.status)
  484. return None
  485. async for chunk in response.content.iter_chunked(8192):
  486. buffer += chunk
  487. # A single chunk can carry multiple frames (e.g. high-FPS sources)
  488. # or a partial frame. Drain every complete frame we already have
  489. # before pulling the next chunk.
  490. while True:
  491. start_idx = buffer.find(jpeg_start)
  492. if start_idx == -1:
  493. # No frame start yet — drop trailing garbage, keep waiting.
  494. break
  495. end_idx = buffer.find(jpeg_end, start_idx + 2)
  496. if end_idx == -1:
  497. # Partial frame; trim already-discarded prefix so the
  498. # buffer stays bounded across long-running streams.
  499. if start_idx > 0:
  500. buffer = buffer[start_idx:]
  501. break
  502. frame = buffer[start_idx : end_idx + 2]
  503. buffer = buffer[end_idx + 2 :]
  504. if first_frame is None:
  505. first_frame = frame # warm-up; keep but don't return yet
  506. continue
  507. return frame # representative second frame
  508. if len(buffer) > 5 * 1024 * 1024: # 5MB limit
  509. logger.warning("MJPEG buffer exceeded 5MB without finding frame")
  510. break # exit chunk loop, fall through to first_frame fallback
  511. except TimeoutError:
  512. logger.warning("MJPEG frame capture timed out after %ss", timeout)
  513. except (aiohttp.ClientError, OSError) as e:
  514. logger.error("MJPEG frame capture failed: %s", e)
  515. # Stream ended / timed out / buffer cap before a second frame arrived.
  516. # Return whatever warm-up frame we managed to read; better an iffy frame
  517. # than None for callers that need *some* image (snapshot UX, plate-detect
  518. # CV, finish photo). None only if no frame ever arrived at all.
  519. return first_frame
  520. async def _capture_rtsp_frame(url: str, timeout: int) -> bytes | None:
  521. """Capture frame from RTSP using ffmpeg.
  522. For rtsps:// URLs, a local TLS proxy is used to avoid GnuTLS issues.
  523. Note: this function intentionally connects to user-configured URLs, the same
  524. as the MJPEG and snapshot paths. The URL is sanitized and dangerous
  525. destinations are blocked before it reaches ffmpeg.
  526. """
  527. ffmpeg = get_ffmpeg_path()
  528. if not ffmpeg:
  529. logger.error("ffmpeg not found - required for RTSP capture")
  530. return None
  531. # ffmpeg's -i accepts every protocol it was built with, so an unchecked URL
  532. # here is a request to any host and scheme the caller names, not merely to a
  533. # camera. Restricting the scheme to RTSP is what keeps this a camera fetch.
  534. safe_url = _sanitize_camera_url(url, ("rtsp", "rtsps"))
  535. if not safe_url:
  536. logger.error("Invalid RTSP URL: %s...", redact_url_credentials(url)[:50])
  537. return None
  538. # If rtsps://, use TLS proxy
  539. proxy_server = None
  540. effective_url = safe_url
  541. if safe_url.lower().startswith("rtsps://"):
  542. try:
  543. from urllib.parse import urlparse
  544. from backend.app.services.camera import create_tls_proxy
  545. parsed = urlparse(safe_url)
  546. target_port = parsed.port or 322
  547. proxy_port, proxy_server = await create_tls_proxy(parsed.hostname, target_port)
  548. userinfo = ""
  549. if parsed.username:
  550. userinfo = parsed.username
  551. if parsed.password:
  552. userinfo += f":{parsed.password}"
  553. userinfo += "@"
  554. # Points at loopback deliberately, and is built after the check
  555. # above rather than re-checked: the destination that mattered was
  556. # the one the caller named, and it has already been vetted.
  557. effective_url = f"rtsp://{userinfo}127.0.0.1:{proxy_port}{parsed.path}"
  558. if parsed.query:
  559. effective_url += f"?{parsed.query}"
  560. except Exception as e:
  561. logger.warning("Failed to create TLS proxy for RTSP capture, falling back: %s", e)
  562. effective_url = safe_url
  563. cmd = [
  564. ffmpeg,
  565. "-rtsp_transport",
  566. "tcp",
  567. # Belt and braces on the scheme check above: a demuxer that follows a
  568. # reference out of the stream cannot leave these protocols either.
  569. "-protocol_whitelist",
  570. _RTSP_PROTOCOL_WHITELIST,
  571. "-i",
  572. effective_url,
  573. "-frames:v",
  574. "1",
  575. "-f",
  576. "image2pipe",
  577. "-vcodec",
  578. "mjpeg",
  579. "-q:v",
  580. "2",
  581. "-",
  582. ]
  583. try:
  584. logger.debug("Running ffmpeg RTSP capture...")
  585. process = await asyncio.create_subprocess_exec(
  586. *cmd,
  587. stdout=asyncio.subprocess.PIPE,
  588. stderr=asyncio.subprocess.PIPE,
  589. )
  590. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  591. logger.debug(
  592. "ffmpeg returned: code=%s, stdout=%s bytes, stderr=%s bytes",
  593. process.returncode,
  594. len(stdout),
  595. len(stderr),
  596. )
  597. if process.returncode != 0:
  598. # ffmpeg echoes the RTSP input URL, which carries the camera password.
  599. logger.error("ffmpeg RTSP capture failed: %s", redact_url_credentials(stderr.decode())[:200])
  600. return None
  601. if not stdout or len(stdout) < 100:
  602. logger.error("ffmpeg returned empty or too small frame")
  603. return None
  604. return stdout
  605. except TimeoutError:
  606. logger.warning("RTSP frame capture timed out after %ss", timeout)
  607. if process:
  608. process.kill()
  609. return None
  610. except OSError as e:
  611. logger.error("RTSP frame capture failed: %s", e)
  612. return None
  613. finally:
  614. if proxy_server:
  615. proxy_server.close()
  616. await proxy_server.wait_closed()
  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 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. # ffmpeg echoes the RTSP input URL, which carries the camera password.
  991. logger.error("ffmpeg RTSP stream failed immediately: %s", redact_url_credentials(stderr.decode())[:300])
  992. return
  993. buffer = b""
  994. jpeg_start = b"\xff\xd8"
  995. jpeg_end = b"\xff\xd9"
  996. while True:
  997. try:
  998. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  999. if not chunk:
  1000. break
  1001. buffer += chunk
  1002. # Extract complete frames
  1003. while True:
  1004. start_idx = buffer.find(jpeg_start)
  1005. if start_idx == -1:
  1006. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  1007. break
  1008. if start_idx > 0:
  1009. buffer = buffer[start_idx:]
  1010. end_idx = buffer.find(jpeg_end, 2)
  1011. if end_idx == -1:
  1012. break
  1013. frame = buffer[: end_idx + 2]
  1014. buffer = buffer[end_idx + 2 :]
  1015. yield frame
  1016. except TimeoutError:
  1017. logger.warning("RTSP stream read timeout")
  1018. break
  1019. except asyncio.CancelledError:
  1020. logger.info("RTSP stream cancelled")
  1021. except OSError as e:
  1022. logger.error("RTSP stream error: %s", e)
  1023. finally:
  1024. if process and process.returncode is None:
  1025. process.terminate()
  1026. try:
  1027. await asyncio.wait_for(process.wait(), timeout=2.0)
  1028. except TimeoutError:
  1029. process.kill()
  1030. await process.wait()
  1031. if proxy_server:
  1032. proxy_server.close()
  1033. await proxy_server.wait_closed()
  1034. async def _stream_usb(
  1035. device: str,
  1036. fps: int,
  1037. *,
  1038. on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
  1039. ) -> AsyncGenerator[bytes, None]:
  1040. """Stream frames from USB camera via ffmpeg."""
  1041. ffmpeg = get_ffmpeg_path()
  1042. if not ffmpeg:
  1043. logger.error("ffmpeg not found - required for USB camera streaming")
  1044. return
  1045. # Same validation as the one-shot path: a prefix check accepted
  1046. # /dev/video/../../<anything that exists>, which -f v4l2 would then refuse
  1047. # rather than the check refusing it.
  1048. safe_device = _safe_usb_device_path(device)
  1049. if not safe_device:
  1050. return
  1051. device = safe_device
  1052. # ffmpeg command to stream from USB camera (v4l2)
  1053. cmd = [
  1054. ffmpeg,
  1055. "-f",
  1056. "v4l2",
  1057. "-framerate",
  1058. str(fps),
  1059. "-i",
  1060. device,
  1061. "-f",
  1062. "mjpeg",
  1063. "-q:v",
  1064. "5",
  1065. "-r",
  1066. str(fps),
  1067. "-",
  1068. ]
  1069. process = None
  1070. try:
  1071. logger.info("Starting USB camera stream from %s at %s fps", device, fps)
  1072. process = await asyncio.create_subprocess_exec(
  1073. *cmd,
  1074. stdout=asyncio.subprocess.PIPE,
  1075. stderr=asyncio.subprocess.PIPE,
  1076. )
  1077. # Register immediately — before the startup probe below — so a process
  1078. # that hangs in open()/ioctl on a still-locked device (rather than
  1079. # exiting with a "busy" error) is still reachable by the stop endpoint /
  1080. # orphan janitor (#2675).
  1081. if on_process is not None:
  1082. on_process(process)
  1083. # Give ffmpeg a moment to start and check for immediate failures
  1084. await asyncio.sleep(0.5)
  1085. if process.returncode is not None:
  1086. stderr = await process.stderr.read()
  1087. logger.error("ffmpeg USB stream failed immediately: %s", stderr.decode()[:300])
  1088. return
  1089. buffer = b""
  1090. jpeg_start = b"\xff\xd8"
  1091. jpeg_end = b"\xff\xd9"
  1092. while True:
  1093. try:
  1094. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  1095. if not chunk:
  1096. break
  1097. buffer += chunk
  1098. # Extract complete frames
  1099. while True:
  1100. start_idx = buffer.find(jpeg_start)
  1101. if start_idx == -1:
  1102. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  1103. break
  1104. if start_idx > 0:
  1105. buffer = buffer[start_idx:]
  1106. end_idx = buffer.find(jpeg_end, 2)
  1107. if end_idx == -1:
  1108. break
  1109. frame = buffer[: end_idx + 2]
  1110. buffer = buffer[end_idx + 2 :]
  1111. yield frame
  1112. except TimeoutError:
  1113. logger.warning("USB stream read timeout")
  1114. break
  1115. except asyncio.CancelledError:
  1116. logger.info("USB stream cancelled")
  1117. except OSError as e:
  1118. logger.error("USB stream error: %s", e)
  1119. finally:
  1120. if process and process.returncode is None:
  1121. process.terminate()
  1122. try:
  1123. await asyncio.wait_for(process.wait(), timeout=2.0)
  1124. except TimeoutError:
  1125. process.kill()
  1126. await process.wait()