external_camera.py 53 KB

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