2 Commits
Author SHA1 Message Date
kiskaadee 09618bef3d feat(capture): add optional host-side JPEG downscaling and recompression
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- Declare pillow in pyproject.toml dependencies and ps.pillow in flake.nix runtimeDeps
- Extend CaptureClient.__init__ with optional max_width and jpeg_quality keyword arguments
- Add _recompress_jpeg helper preserving aspect ratio, never upscaling, defaulting quality to 75 when resizing, and raising TvError(SCREENSHOT_UNAVAILABLE) on corrupt image bytes
- Compute frame_sha256, changed_since_last, and size_bytes on the final delivered image_bytes
- Wire capture_max_width and capture_jpeg_quality into CaptureClient in create_mcp_server()
- Add offline unit tests in tests/test_capture.py and tests/test_server.py
2026-11-19 10:34:31 -05:00
kiskaadee 120d3ecf32 feat(config): add optional capture downscaling and quality settings
- Add capture_max_width (64..3840) and capture_jpeg_quality (1..95) fields to TvConfig
- Validate both fields via _parse_bounded_int in mode="before" validators allowing None
- Parse CAPTURE_MAX_WIDTH and CAPTURE_JPEG_QUALITY in load_config()
- Add unit tests in tests/test_config.py covering defaults, valid bounds, and ConfigError rejections
2026-11-19 10:30:52 -05:00
8 changed files with 367 additions and 2 deletions

No files matched your search

+1
View File
@@ -17,6 +17,7 @@
ps.pydantic ps.pydantic
ps.asyncssh ps.asyncssh
ps.uvicorn ps.uvicorn
ps.pillow
]; ];
testDeps = [ testDeps = [
+1
View File
@@ -13,6 +13,7 @@ dependencies = [
"pydantic", "pydantic",
"asyncssh", "asyncssh",
"uvicorn", "uvicorn",
"pillow",
] ]
[project.scripts] [project.scripts]
+22
View File
@@ -72,6 +72,8 @@ class TvConfig(BaseModel):
mcp_bearer_token: str | None = None mcp_bearer_token: str | None = None
max_volume: int = 40 max_volume: int = 40
enable_raw_ssap: bool = False enable_raw_ssap: bool = False
capture_max_width: int | None = None
capture_jpeg_quality: int | None = None
def __init__(self, **data: Any) -> None: def __init__(self, **data: Any) -> None:
try: try:
@@ -100,6 +102,20 @@ class TvConfig(BaseModel):
def _validate_max_volume(cls, value: Any) -> int: def _validate_max_volume(cls, value: Any) -> int:
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100) return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
@field_validator("capture_max_width", mode="before")
@classmethod
def _validate_capture_max_width(cls, value: Any) -> int | None:
if value is None:
return None
return _parse_bounded_int("CAPTURE_MAX_WIDTH", value, min_val=64, max_val=3840)
@field_validator("capture_jpeg_quality", mode="before")
@classmethod
def _validate_capture_jpeg_quality(cls, value: Any) -> int | None:
if value is None:
return None
return _parse_bounded_int("CAPTURE_JPEG_QUALITY", value, min_val=1, max_val=95)
def _load_dotenv(env_path: Path) -> None: def _load_dotenv(env_path: Path) -> None:
"""Populate unset os.environ keys from a .env file using stdlib only.""" """Populate unset os.environ keys from a .env file using stdlib only."""
@@ -149,6 +165,8 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
tv_ip = _optional_str("TV_IP") or "" tv_ip = _optional_str("TV_IP") or ""
port_raw = _optional_str("PORT") port_raw = _optional_str("PORT")
max_volume_raw = _optional_str("MAX_VOLUME") max_volume_raw = _optional_str("MAX_VOLUME")
capture_max_width_raw = _optional_str("CAPTURE_MAX_WIDTH")
capture_jpeg_quality_raw = _optional_str("CAPTURE_JPEG_QUALITY")
host = _optional_str("HOST") or "127.0.0.1" host = _optional_str("HOST") or "127.0.0.1"
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255" wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
@@ -177,6 +195,10 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
kwargs["port"] = port_raw kwargs["port"] = port_raw
if max_volume_raw is not None: if max_volume_raw is not None:
kwargs["max_volume"] = max_volume_raw kwargs["max_volume"] = max_volume_raw
if capture_max_width_raw is not None:
kwargs["capture_max_width"] = capture_max_width_raw
if capture_jpeg_quality_raw is not None:
kwargs["capture_jpeg_quality"] = capture_jpeg_quality_raw
return TvConfig(**kwargs) return TvConfig(**kwargs)
+8 -1
View File
@@ -160,7 +160,14 @@ def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCP
tv_manager = ( tv_manager = (
manager manager
if manager is not None if manager is not None
else TvManager(config, capture_client=CaptureClient(AsyncSshCaptureTransport(config))) else TvManager(
config,
capture_client=CaptureClient(
AsyncSshCaptureTransport(config),
max_width=config.capture_max_width,
jpeg_quality=config.capture_jpeg_quality,
),
)
) )
@asynccontextmanager @asynccontextmanager
+51 -1
View File
@@ -5,14 +5,51 @@ import hashlib
import os import os
from collections.abc import Awaitable, Callable from collections.abc import Awaitable, Callable
from contextlib import suppress from contextlib import suppress
from io import BytesIO
from typing import Any from typing import Any
import asyncssh import asyncssh
from PIL import Image, UnidentifiedImageError
from lg_smtv_mcp.config import TvConfig from lg_smtv_mcp.config import TvConfig
from lg_smtv_mcp.errors import ErrorCode, TvError from lg_smtv_mcp.errors import ErrorCode, TvError
from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport
_DEFAULT_JPEG_QUALITY = 75
def _recompress_jpeg(
raw_bytes: bytes,
*,
max_width: int | None,
jpeg_quality: int | None,
) -> bytes:
"""Optionally downscale and/or recompress JPEG bytes for inline MCP delivery."""
if max_width is None and jpeg_quality is None:
return raw_bytes
quality = jpeg_quality if jpeg_quality is not None else _DEFAULT_JPEG_QUALITY
try:
with Image.open(BytesIO(raw_bytes)) as opened:
img: Image.Image = opened
width, height = img.size
if max_width is not None and width > max_width:
target_height = max(1, round(height * (max_width / width)))
img = img.resize( # pyright: ignore[reportUnknownMemberType]
(max_width, target_height),
Image.Resampling.LANCZOS,
)
if img.mode != "RGB":
img = img.convert("RGB")
out = BytesIO()
img.save(out, format="JPEG", quality=quality)
return out.getvalue()
except (UnidentifiedImageError, OSError, ValueError, EOFError) as exc:
raise TvError(
ErrorCode.SCREENSHOT_UNAVAILABLE,
f"Failed to process screenshot image: {exc}",
) from exc
class AsyncSshCaptureTransport: class AsyncSshCaptureTransport:
"""SFTP transport for reading and removing Developer Mode screenshot captures.""" """SFTP transport for reading and removing Developer Mode screenshot captures."""
@@ -154,8 +191,16 @@ class AsyncSshCaptureTransport:
class CaptureClient: class CaptureClient:
"""FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP.""" """FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP."""
def __init__(self, transport: CaptureTransport) -> None: def __init__(
self,
transport: CaptureTransport,
*,
max_width: int | None = None,
jpeg_quality: int | None = None,
) -> None:
self._transport = transport self._transport = transport
self._max_width = max_width
self._jpeg_quality = jpeg_quality
self._seq = 0 self._seq = 0
self._last_sha256: str | None = None self._last_sha256: str | None = None
@@ -203,6 +248,11 @@ class CaptureClient:
"Screenshot capture timed out after 6.0s", "Screenshot capture timed out after 6.0s",
) from exc ) from exc
image_bytes = _recompress_jpeg(
image_bytes,
max_width=self._max_width,
jpeg_quality=self._jpeg_quality,
)
frame_sha256 = hashlib.sha256(image_bytes).hexdigest() frame_sha256 = hashlib.sha256(image_bytes).hexdigest()
changed_since_last = self._last_sha256 != frame_sha256 changed_since_last = self._last_sha256 != frame_sha256
self._last_sha256 = frame_sha256 self._last_sha256 = frame_sha256
+131
View File
@@ -3,11 +3,13 @@
import asyncio import asyncio
import hashlib import hashlib
import inspect import inspect
from io import BytesIO
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import asyncssh import asyncssh
import pytest import pytest
from PIL import Image
from lg_smtv_mcp.config import TvConfig from lg_smtv_mcp.config import TvConfig
from lg_smtv_mcp.errors import ErrorCode, TvError from lg_smtv_mcp.errors import ErrorCode, TvError
@@ -522,3 +524,132 @@ async def test_capture_client_maps_key_import_error_to_screenshot_unavailable()
await client.capture_frame(ssap_request) await client.capture_frame(ssap_request)
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
assert "Passphrase must be specified" in exc_info.value.message assert "Passphrase must be specified" in exc_info.value.message
def _make_jpeg(
width: int,
height: int,
*,
color: tuple[int, int, int] = (25, 80, 160),
quality: int = 95,
) -> bytes:
buf = BytesIO()
img = Image.new("RGB", (width, height), color=color)
# Draw varied pixels so JPEG recompression has realistic entropy differences.
for x in range(0, width, 8):
img.putpixel((x, x % height), ((x * 7) % 255, (x * 13) % 255, 200))
img.save(buf, format="JPEG", quality=quality)
return buf.getvalue()
async def test_capture_client_passes_raw_bytes_unchanged_when_no_resize_or_quality() -> None:
raw = b"raw-unprocessed-bytes"
client = CaptureClient(FakeCaptureTransport(image_bytes=raw))
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
result = await client.capture_frame(ssap_request)
assert result.image_bytes == raw
assert result.size_bytes == len(raw)
assert result.frame_sha256 == hashlib.sha256(raw).hexdigest()
async def test_capture_client_downscales_preserving_aspect_ratio_with_default_quality_75() -> None:
raw = _make_jpeg(1920, 1080, quality=95)
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=640)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
result = await client.capture_frame(ssap_request)
with Image.open(BytesIO(result.image_bytes)) as img:
assert img.format == "JPEG"
assert img.size == (640, 360)
assert result.size_bytes == len(result.image_bytes)
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
assert result.image_bytes != raw
async def test_capture_client_never_upscales_when_width_at_or_below_max_width() -> None:
raw = _make_jpeg(800, 600, quality=95)
client = CaptureClient(
FakeCaptureTransport(image_bytes=raw),
max_width=1280,
jpeg_quality=80,
)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
result = await client.capture_frame(ssap_request)
with Image.open(BytesIO(result.image_bytes)) as img:
assert img.format == "JPEG"
assert img.size == (800, 600)
async def test_capture_client_recompresses_at_native_resolution_when_only_quality_set() -> None:
raw = _make_jpeg(1280, 720, quality=95)
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), jpeg_quality=30)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
result = await client.capture_frame(ssap_request)
with Image.open(BytesIO(result.image_bytes)) as img:
assert img.format == "JPEG"
assert img.size == (1280, 720)
assert result.size_bytes < len(raw)
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
async def test_capture_client_hashes_and_tracks_changes_on_final_delivered_bytes() -> None:
raw = _make_jpeg(1280, 720, quality=95)
client = CaptureClient(
FakeCaptureTransport(image_bytes=raw),
max_width=640,
jpeg_quality=75,
)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
first = await client.capture_frame(ssap_request)
second = await client.capture_frame(ssap_request)
assert first.frame_sha256 != hashlib.sha256(raw).hexdigest()
assert first.frame_sha256 == hashlib.sha256(first.image_bytes).hexdigest()
assert first.changed_since_last is True
assert second.changed_since_last is False
@pytest.mark.parametrize(
"kwargs",
[
{"max_width": 640},
{"jpeg_quality": 75},
{"max_width": 640, "jpeg_quality": 75},
],
)
async def test_capture_client_raises_screenshot_unavailable_on_corrupt_image_bytes(
kwargs: dict[str, int],
) -> None:
client = CaptureClient(FakeCaptureTransport(image_bytes=b"not-a-valid-jpeg"), **kwargs)
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = (uri, payload)
return {"returnValue": True}
with pytest.raises(TvError) as exc_info:
await client.capture_frame(ssap_request)
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
+56
View File
@@ -22,6 +22,8 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
"MCP_BEARER_TOKEN", "MCP_BEARER_TOKEN",
"MAX_VOLUME", "MAX_VOLUME",
"ENABLE_RAW_SSAP", "ENABLE_RAW_SSAP",
"CAPTURE_MAX_WIDTH",
"CAPTURE_JPEG_QUALITY",
): ):
monkeypatch.delenv(key, raising=False) monkeypatch.delenv(key, raising=False)
@@ -74,6 +76,8 @@ def test_load_config_uses_expected_defaults_when_optional_vars_unset(
assert cfg.allowed_hosts == () assert cfg.allowed_hosts == ()
assert cfg.tv_mac is None assert cfg.tv_mac is None
assert cfg.mcp_bearer_token is None assert cfg.mcp_bearer_token is None
assert cfg.capture_max_width is None
assert cfg.capture_jpeg_quality is None
def test_dotenv_fallback_does_not_overwrite_existing_env( def test_dotenv_fallback_does_not_overwrite_existing_env(
@@ -108,6 +112,12 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"), ({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"), ({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"), ({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "63"}, "CAPTURE_MAX_WIDTH"),
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "3841"}, "CAPTURE_MAX_WIDTH"),
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "wide"}, "CAPTURE_MAX_WIDTH"),
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "0"}, "CAPTURE_JPEG_QUALITY"),
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "96"}, "CAPTURE_JPEG_QUALITY"),
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "high"}, "CAPTURE_JPEG_QUALITY"),
], ],
) )
def test_load_config_rejects_invalid_env_values_with_config_error( def test_load_config_rejects_invalid_env_values_with_config_error(
@@ -136,6 +146,14 @@ def test_load_config_rejects_invalid_env_values_with_config_error(
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"), ({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"), ({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"), ({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
({"tv_ip": "192.0.2.10", "capture_max_width": 63}, "CAPTURE_MAX_WIDTH"),
({"tv_ip": "192.0.2.10", "capture_max_width": 3841}, "CAPTURE_MAX_WIDTH"),
({"tv_ip": "192.0.2.10", "capture_max_width": 1280.5}, "CAPTURE_MAX_WIDTH"),
({"tv_ip": "192.0.2.10", "capture_max_width": True}, "CAPTURE_MAX_WIDTH"),
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 0}, "CAPTURE_JPEG_QUALITY"),
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 96}, "CAPTURE_JPEG_QUALITY"),
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 75.5}, "CAPTURE_JPEG_QUALITY"),
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": False}, "CAPTURE_JPEG_QUALITY"),
], ],
) )
def test_tv_config_rejects_invalid_direct_arguments_with_config_error( def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
@@ -210,3 +228,41 @@ def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_
cfg = load_config(env_path=tmp_path / "missing.env") cfg = load_config(env_path=tmp_path / "missing.env")
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF" assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"
@pytest.mark.parametrize(
("width_env", "quality_env", "expected_width", "expected_quality"),
[
("64", "1", 64, 1),
("3840", "95", 3840, 95),
(" 1280 ", " 75 ", 1280, 75),
("", " ", None, None),
],
)
def test_load_config_parses_capture_max_width_and_jpeg_quality(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
width_env: str,
quality_env: str,
expected_width: int | None,
expected_quality: int | None,
) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
monkeypatch.setenv("CAPTURE_MAX_WIDTH", width_env)
monkeypatch.setenv("CAPTURE_JPEG_QUALITY", quality_env)
cfg = load_config(env_path=tmp_path / "missing.env")
assert cfg.capture_max_width == expected_width
assert cfg.capture_jpeg_quality == expected_quality
def test_tv_config_accepts_explicit_none_and_valid_capture_bounds() -> None:
cfg_none = TvConfig(tv_ip="192.0.2.10", capture_max_width=None, capture_jpeg_quality=None)
assert cfg_none.capture_max_width is None
assert cfg_none.capture_jpeg_quality is None
cfg_bounds = TvConfig(tv_ip="192.0.2.10", capture_max_width=1280, capture_jpeg_quality=80)
assert cfg_bounds.capture_max_width == 1280
assert cfg_bounds.capture_jpeg_quality == 80
+97
View File
@@ -556,3 +556,100 @@ async def test_server_create_mcp_server_wires_default_capture_client(
assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"] assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"]
assert len(sftp_sessions) == 1 assert len(sftp_sessions) == 1
assert sftp_sessions[0].closed is True assert sftp_sessions[0].closed is True
async def test_server_create_mcp_server_wires_capture_downscaling_config(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from io import BytesIO
from PIL import Image
import lg_smtv_mcp.server as server_mod
from lg_smtv_mcp.tv_core.capture import CaptureClient
config = TvConfig(
tv_ip="192.0.2.10",
client_key_path=tmp_path / ".client_key.json",
capture_max_width=640,
capture_jpeg_quality=60,
)
captured: dict[str, Any] = {}
remote_files: dict[str, bytes] = {}
class DummyManager:
async def start(self) -> None:
return None
async def close(self) -> None:
return None
class FakeSftp:
async def listdir(self, path: str) -> list[str]:
_ = path
return []
def open(self, path: str, mode: str = "r") -> Any:
_ = mode
class FakeFile:
async def __aenter__(self) -> FakeFile:
return self
async def __aexit__(self, *_exc: object) -> None:
return None
async def read(self) -> bytes:
return remote_files[path]
return FakeFile()
async def remove(self, path: str) -> None:
remote_files.pop(path, None)
async def exit(self) -> None:
return None
class FakeSshConnection:
async def start_sftp_client(self) -> FakeSftp:
return FakeSftp()
def close(self) -> None:
return None
async def wait_closed(self) -> None:
return None
def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager:
captured["config"] = cfg
captured["kwargs"] = kwargs
return DummyManager()
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
_ = kwargs
return FakeSshConnection()
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
monkeypatch.setattr(asyncssh, "connect", fake_connect)
server_mod.create_mcp_server(config)
capture_client = captured["kwargs"]["capture_client"]
assert isinstance(capture_client, CaptureClient)
buf = BytesIO()
Image.new("RGB", (1920, 1080), color=(30, 60, 90)).save(buf, format="JPEG", quality=95)
large_jpeg = buf.getvalue()
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
_ = uri
remote_files[payload["path"]] = large_jpeg
return {"returnValue": True}
try:
result = await capture_client.capture_frame(ssap_request)
finally:
await capture_client.close()
with Image.open(BytesIO(result.image_bytes)) as img:
assert img.format == "JPEG"
assert img.size == (640, 360)