-
Notifications
You must be signed in to change notification settings - Fork 1
Improve TurboJPEG detection on Windows and document fallback behavior #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| """TurboJPEG discovery helpers with Windows DLL fallbacks.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import os | ||
| from pathlib import Path | ||
| from typing import Optional, Tuple | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
| try: | ||
| from turbojpeg import TurboJPEG, TJPF_RGB | ||
| except ImportError: # pragma: no cover - exercised via create_turbojpeg | ||
| TurboJPEG = None | ||
| TJPF_RGB = None | ||
|
|
||
|
|
||
| def _candidate_library_paths() -> list[Optional[str]]: | ||
| """Return candidate libjpeg-turbo library paths to try in priority order.""" | ||
| candidates: list[Optional[str]] = [] | ||
|
|
||
| explicit = os.getenv("FASTSTACK_TURBOJPEG_LIB") or os.getenv("TURBOJPEG_LIB") | ||
| if explicit: | ||
| candidates.append(explicit) | ||
| candidates.append(None) | ||
|
|
||
| if os.name == "nt": | ||
| common_roots = [ | ||
| os.getenv("FASTSTACK_TURBOJPEG_ROOT"), | ||
| os.getenv("SystemDrive", "C:") + os.sep, | ||
| os.getenv("ProgramFiles"), | ||
| os.getenv("ProgramFiles(x86)"), | ||
| ] | ||
| suffixes = [ | ||
| ("libjpeg-turbo", "bin", "turbojpeg.dll"), | ||
| ("libjpeg-turbo64", "bin", "turbojpeg.dll"), | ||
| ("libjpeg-turbo-gcc64", "bin", "turbojpeg.dll"), | ||
| ("TurboJPEG", "bin", "turbojpeg.dll"), | ||
| ("bin", "turbojpeg.dll"), | ||
| ] | ||
| for root in common_roots: | ||
| if not root: | ||
| continue | ||
| for suffix in suffixes: | ||
| candidates.append(str(Path(root).joinpath(*suffix))) | ||
|
|
||
| local_app_data = os.getenv("LOCALAPPDATA") | ||
| if local_app_data: | ||
| candidates.append( | ||
| str( | ||
| Path(local_app_data) | ||
| / "Programs" | ||
| / "libjpeg-turbo" | ||
| / "bin" | ||
| / "turbojpeg.dll" | ||
| ) | ||
| ) | ||
|
|
||
| for path_dir in os.getenv("PATH", "").split(os.pathsep): | ||
| if path_dir: | ||
| candidates.append(str(Path(path_dir) / "turbojpeg.dll")) | ||
|
|
||
| unique: list[Optional[str]] = [] | ||
| seen: set[str] = set() | ||
| for candidate in candidates: | ||
| key = "__default__" if candidate is None else os.path.normcase(candidate) | ||
| if key in seen: | ||
| continue | ||
| seen.add(key) | ||
| unique.append(candidate) | ||
| return unique | ||
|
|
||
|
|
||
| def create_turbojpeg() -> Tuple[Optional["TurboJPEG"], bool]: | ||
| """Create a TurboJPEG decoder if possible.""" | ||
| if TurboJPEG is None: | ||
| log.warning("PyTurboJPEG not found. Falling back to Pillow for JPEG decoding.") | ||
| return None, False | ||
|
|
||
| failures: list[str] = [] | ||
| for candidate in _candidate_library_paths(): | ||
| try: | ||
| decoder = TurboJPEG() if candidate is None else TurboJPEG(candidate) | ||
| except Exception as exc: | ||
| source = "default loader" if candidate is None else candidate | ||
| failures.append(f"{source}: {exc}") | ||
| continue | ||
|
|
||
| if candidate is None: | ||
| log.info("PyTurboJPEG is available. Using it for JPEG decoding.") | ||
| else: | ||
| log.info("Loaded TurboJPEG library from %s", candidate) | ||
| return decoder, True | ||
|
|
||
| for failure in failures: | ||
| log.debug("TurboJPEG load attempt failed: %s", failure) | ||
| log.warning( | ||
| "TurboJPEG initialization failed (%d location(s) tried). " | ||
| "Falling back to Pillow for JPEG decoding.", | ||
| len(failures), | ||
| ) | ||
| return None, False | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import importlib | ||
| import logging | ||
| from types import SimpleNamespace | ||
|
|
||
|
|
||
| def test_create_turbojpeg_prefers_explicit_env_path(monkeypatch): | ||
| turbo = importlib.import_module("faststack.imaging.turbo") | ||
|
|
||
| calls = [] | ||
|
|
||
| def fake_decoder(path=None): | ||
| calls.append(path) | ||
| if path == "C:/turbo/bin/turbojpeg.dll": | ||
| return SimpleNamespace(source=path) | ||
| raise RuntimeError(f"boom:{path}") | ||
|
|
||
| monkeypatch.setattr(turbo, "TurboJPEG", fake_decoder) | ||
| monkeypatch.setenv("FASTSTACK_TURBOJPEG_LIB", "C:/turbo/bin/turbojpeg.dll") | ||
|
|
||
| decoder, available = turbo.create_turbojpeg() | ||
|
|
||
| assert available is True | ||
| assert decoder.source == "C:/turbo/bin/turbojpeg.dll" | ||
| assert calls == ["C:/turbo/bin/turbojpeg.dll"] | ||
|
|
||
|
|
||
| def test_create_turbojpeg_retries_default_loader_after_bad_env_override(monkeypatch): | ||
| turbo = importlib.import_module("faststack.imaging.turbo") | ||
|
|
||
| calls = [] | ||
|
|
||
| def fake_decoder(path=None): | ||
| calls.append(path) | ||
| if path == "/bad/turbojpeg.so": | ||
| raise RuntimeError("bad override") | ||
| if path is None: | ||
| return SimpleNamespace(source="default") | ||
| raise RuntimeError(f"unexpected path:{path}") | ||
|
|
||
| monkeypatch.setattr(turbo, "TurboJPEG", fake_decoder) | ||
| monkeypatch.setattr(turbo.os, "name", "posix") | ||
| monkeypatch.setenv("FASTSTACK_TURBOJPEG_LIB", "/bad/turbojpeg.so") | ||
| monkeypatch.delenv("TURBOJPEG_LIB", raising=False) | ||
|
|
||
| decoder, available = turbo.create_turbojpeg() | ||
|
|
||
| assert available is True | ||
| assert decoder.source == "default" | ||
| assert calls == ["/bad/turbojpeg.so", None] | ||
|
|
||
|
|
||
| def test_all_candidates_fail_emits_one_warning(monkeypatch, caplog): | ||
| """When all locations fail, exactly one warning is emitted (not one per candidate).""" | ||
| turbo = importlib.import_module("faststack.imaging.turbo") | ||
|
|
||
| def fake_decoder(path=None): | ||
| raise RuntimeError(f"boom:{path}") | ||
|
|
||
| monkeypatch.setattr(turbo, "TurboJPEG", fake_decoder) | ||
| monkeypatch.setattr( | ||
| turbo, | ||
| "_candidate_library_paths", | ||
| lambda: [None, "C:/one/turbojpeg.dll", "C:/two/turbojpeg.dll"], | ||
| ) | ||
|
|
||
| with caplog.at_level(logging.WARNING): | ||
| decoder, available = turbo.create_turbojpeg() | ||
|
|
||
| assert decoder is None | ||
| assert available is False | ||
|
|
||
| warning_records = [ | ||
| r for r in caplog.records if r.levelno == logging.WARNING | ||
| ] | ||
| assert len(warning_records) == 1 | ||
| assert "Falling back to Pillow" in warning_records[0].message | ||
| assert "3 location(s) tried" in warning_records[0].message | ||
|
|
||
|
|
||
| def test_all_candidates_fail_details_at_debug(monkeypatch, caplog): | ||
| """Per-candidate failure details are available at DEBUG level.""" | ||
| turbo = importlib.import_module("faststack.imaging.turbo") | ||
|
|
||
| def fake_decoder(path=None): | ||
| raise RuntimeError(f"boom:{path}") | ||
|
|
||
| monkeypatch.setattr(turbo, "TurboJPEG", fake_decoder) | ||
| monkeypatch.setattr( | ||
| turbo, | ||
| "_candidate_library_paths", | ||
| lambda: [None, "C:/one/turbojpeg.dll"], | ||
| ) | ||
|
|
||
| with caplog.at_level(logging.DEBUG): | ||
| turbo.create_turbojpeg() | ||
|
|
||
| debug_records = [ | ||
| r for r in caplog.records if r.levelno == logging.DEBUG | ||
| ] | ||
| debug_text = " ".join(r.message for r in debug_records) | ||
| assert "default loader" in debug_text | ||
| assert "C:/one/turbojpeg.dll" in debug_text | ||
|
|
||
|
|
||
| def test_missing_turbojpeg_package_emits_one_warning(monkeypatch, caplog): | ||
| """When the turbojpeg package is not installed, exactly one warning is emitted.""" | ||
| turbo = importlib.import_module("faststack.imaging.turbo") | ||
|
|
||
| monkeypatch.setattr(turbo, "TurboJPEG", None) | ||
|
|
||
| with caplog.at_level(logging.WARNING): | ||
| decoder, available = turbo.create_turbojpeg() | ||
|
|
||
| assert decoder is None | ||
| assert available is False | ||
|
|
||
| warning_records = [ | ||
| r for r in caplog.records if r.levelno == logging.WARNING | ||
| ] | ||
| assert len(warning_records) == 1 | ||
| assert "PyTurboJPEG not found" in warning_records[0].message | ||
| assert "Pillow" in warning_records[0].message |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.