From b6dc775bca424f69af063b2ac1bff029f61c9c75 Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:47:09 -0800 Subject: [PATCH 1/7] Guard backend discovery by operating system Service discovery instantiates every installed backend on every platform. Check the operating system before touching a platform's native bindings, and register the Apple video backend through a lightweight wrapper that only loads the AVFoundation bridge on macOS. Run the example consumer as a named module, and drop ROUTING.md now that the README carries the routing contract. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- ROUTING.md | 166 ------------------ example-consumer/pom.xml | 1 + .../src/main/java/demo/DecodeDemo.java | 8 +- .../src/main/java/module-info.java | 4 + .../imageio/apple/AppleImageBackend.java | 8 +- .../apple/internal/AppleVideoBackend.java | 83 +++++++++ .../src/main/java/module-info.java | 4 +- ...ub.ghosthack.imageio.common.RoutingBackend | 2 +- ....imageio.video.VideoFrameExtractorProvider | 2 +- .../windows/WindowsVideoFrameExtractor.java | 5 +- .../imageio/windows/WindowsImageBackend.java | 8 +- 11 files changed, 114 insertions(+), 177 deletions(-) delete mode 100644 ROUTING.md create mode 100644 example-consumer/src/main/java/module-info.java create mode 100644 imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/internal/AppleVideoBackend.java diff --git a/ROUTING.md b/ROUTING.md deleted file mode 100644 index 43bb6d6..0000000 --- a/ROUTING.md +++ /dev/null @@ -1,166 +0,0 @@ -# ImageIO routing principles - -Status: implemented. This document defines the routing contract used by the -backend service and routing SPI implementation. - -## Core principle - -The host Java runtime is the baseline. With no imageio-native backend modules -installed, ImageIO behaves exactly as supplied by that runtime. - -Adding a backend module is an explicit opt-in to that backend. If exactly one -installed backend can decode an input, that backend owns the input, including -formats that the JDK can also decode. - -For example, adding the Windows module means WIC owns every input that WIC can -actually decode. If WIC can decode a JPEG, the JPEG is routed to WIC rather than -the JDK reader. Applications that want the JDK reader for a particular -intersection can explicitly route that format back to the host. - -## Principles - -1. **Preserve the host by default.** With no added backend capable of decoding - an input, the routing SPI declines it and the host ImageIO implementation - proceeds normally. -2. **Module presence is authorization.** Adding a backend module opts into all - formats that backend can actually decode. There is no implicit - "supplemental formats only" mode. -3. **A single added backend overrides the JDK.** If one installed backend is - capable, it owns the input even when a host JDK reader is also capable. -4. **Capability is input-specific.** Declaring support for a format or container - only makes a backend a candidate. A lightweight probe must confirm that the - backend on this machine can open the actual input. This accounts for optional - Windows codecs and for different codecs inside the same video container. -5. **Non-intersecting capability sets do not collide.** A format supported by - only one added backend belongs to that backend without consulting collision - policy. -6. **Intersections have one deterministic owner.** When multiple added backends - are capable, a portable/software-codec backend wins by default over a - platform-native backend. This is a predictability and portability policy, - not a claim that one implementation is inherently more secure. -7. **Applications control intersections explicitly.** A small, application-owned - Java configuration can select a different backend—or the host JDK—for any - intersecting format. -8. **Routing is not decode-time fallback.** The router filters candidates using - capability probes, selects exactly one owner, and invokes it once. If the - selected decoder subsequently fails, its error is returned; the router does - not silently retry another implementation. -9. **Configuration is stable.** Application routing must be installed before - the first routed ImageIO operation. The configuration freezes on first use, - making behavior independent of class-loading or SPI-registration timing. -10. **Direct backend APIs bypass routing.** Calling a WIC, Media Foundation, - FFmpeg, libvips, or ImageMagick API directly always invokes that backend. - -## Ownership algorithm - -For an input `x` with detected format `f`: - -```text -candidates = installed backends - that declare f - and whose lightweight probe accepts x - -if candidates is empty: - decline x // host JDK behavior - -if policy explicitly selects host for f: - decline x // host JDK behavior - -if policy selects backend b for f and b is in candidates: - select b - -if candidates contains exactly one backend: - select that backend // overrides the JDK - -select the deterministic default: - portable/software before platform-native - stable backend ID as the tie-breaker within a class -``` - -An explicit backend preference only resolves among capable candidates. It never -forces an unavailable backend to decode an unsupported input. Unknown backend -IDs in application configuration should fail fast as configuration errors. - -## Examples - -The JPEG/FFmpeg combination is intentionally illustrative; it defines the -routing semantics independently of the formats implemented by today's modules. - -Assume the host JDK, Windows/WIC, and FFmpeg can all decode JPEG: - -| Installed modules | Application rule | JPEG owner | -|---|---|---| -| None | None | Host JDK | -| Windows | None | Windows/WIC | -| FFmpeg | None | FFmpeg | -| Windows + FFmpeg | None | FFmpeg (portable/software default) | -| Windows + FFmpeg | `jpeg -> windows` | Windows/WIC | -| Windows + FFmpeg | `jpeg -> host` | Host JDK | - -If the Windows module is installed but WIC's probe rejects a particular JPEG, -WIC is not a candidate for that input. Another capable added backend owns it, -or the router declines it and leaves it to the host. - -For non-intersecting formats: - -```text -Windows supports HEIC, FFmpeg does not -> Windows owns HEIC -FFmpeg supports MKV, Windows does not -> FFmpeg owns MKV -Neither supports a PNG input -> host ImageIO handles PNG -``` - -## Application-owned routing file - -The application may keep all intersection choices in one minimal Java file: - -```java -public final class AppImageIoRouting { - private AppImageIoRouting() {} - - public static void install() { - ImageIoRouting.configure(routes -> routes - .prefer("jpeg", "windows") - .prefer("heic", "windows") - .prefer("mkv", "ffmpeg") - .preferHost("png")); - } -} -``` - -The application calls it once during startup, before its first ImageIO -operation: - -```java -AppImageIoRouting.install(); -``` - -Configuration is explicit Java code rather than registration-order tricks, -system-property priority lists, or magically discovered application classes. - -## Registration model - -Backend modules should register backend services, not mutually competing -`ImageReaderSpi` implementations. - -One routing SPI per media category owns integration with ImageIO: - -```text -ImageIO - | - v -routing SPI - | - +-- detect the format once - +-- discover installed backend services - +-- run lightweight capability probes - +-- resolve ownership - `-- delegate to exactly one backend -``` - -The routing SPI is ordered before host readers, but returns `false` whenever no -added backend owns the input. Consequently it affects a host format only when -an installed backend has positively claimed that particular input. - -Backend-to-backend `IIORegistry.setOrdering()`, shared format advertisements on -every backend SPI, global priority properties, and decode-time retry chains are -not part of this design. diff --git a/example-consumer/pom.xml b/example-consumer/pom.xml index 7e7b1ab..1d03fae 100644 --- a/example-consumer/pom.xml +++ b/example-consumer/pom.xml @@ -66,6 +66,7 @@ maven-surefire-plugin 3.3.1 + --enable-native-access=ALL-UNNAMED diff --git a/example-consumer/src/main/java/demo/DecodeDemo.java b/example-consumer/src/main/java/demo/DecodeDemo.java index 6eb937f..99beebb 100644 --- a/example-consumer/src/main/java/demo/DecodeDemo.java +++ b/example-consumer/src/main/java/demo/DecodeDemo.java @@ -15,14 +15,18 @@ *

* Usage: *

- * java --enable-native-access=ALL-UNNAMED -jar example-consumer.jar photo.heic clip.mp4
+ * java --module-path lib \
+ *      --enable-native-access=io.github.ghosthack.imageio.apple,io.github.ghosthack.imageio.video.apple \
+ *      --module io.github.ghosthack.imageio.example/demo.DecodeDemo photo.heic clip.mp4
  * 
*/ public class DecodeDemo { public static void main(String[] args) throws IOException { if (args.length == 0) { - System.out.println("Usage: java --enable-native-access=ALL-UNNAMED -jar example-consumer.jar ..."); + System.out.println("Usage: java --module-path lib \\"); + System.out.println(" --enable-native-access= \\"); + System.out.println(" --module io.github.ghosthack.imageio.example/demo.DecodeDemo ..."); System.out.println(); System.out.println("Supports images (HEIC, AVIF, WEBP, JP2, RAW, ...) and video poster frames (MP4, MOV, ...)"); System.out.println(); diff --git a/example-consumer/src/main/java/module-info.java b/example-consumer/src/main/java/module-info.java new file mode 100644 index 0000000..733ff98 --- /dev/null +++ b/example-consumer/src/main/java/module-info.java @@ -0,0 +1,4 @@ +module io.github.ghosthack.imageio.example { + requires io.github.ghosthack.imageio; + requires io.github.ghosthack.imageio.video; +} diff --git a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleImageBackend.java b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleImageBackend.java index feac10b..dacc4ae 100644 --- a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleImageBackend.java +++ b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleImageBackend.java @@ -5,10 +5,14 @@ import javax.imageio.ImageReader; import javax.imageio.spi.ImageReaderSpi; +import java.util.Locale; /** Apple ImageIO backend service consumed by the common routing SPI. */ public final class AppleImageBackend implements ImageDecoderBackend { + private static final boolean IS_MACOS = System.getProperty("os.name", "") + .toLowerCase(Locale.ROOT).contains("mac"); + @Override public String id() { return "apple"; @@ -26,12 +30,12 @@ public io.github.ghosthack.imageio.common.FormatRegistry formats() { @Override public boolean isAvailable() { - return AppleNative.IS_MACOS; + return IS_MACOS; } @Override public boolean canDecode(byte[] header, int length) { - return AppleNative.canDecode(header, length); + return IS_MACOS && AppleNative.canDecode(header, length); } @Override diff --git a/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/internal/AppleVideoBackend.java b/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/internal/AppleVideoBackend.java new file mode 100644 index 0000000..ad1f3c3 --- /dev/null +++ b/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/internal/AppleVideoBackend.java @@ -0,0 +1,83 @@ +package io.github.ghosthack.imageio.video.apple.internal; + +import io.github.ghosthack.imageio.common.RoutingBackend; +import io.github.ghosthack.imageio.video.apple.AppleVideoFrameExtractor; +import io.github.ghosthack.imageio.video.VideoFrameExtractorProvider; +import io.github.ghosthack.imageio.video.VideoInfo; + +import java.awt.Dimension; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Locale; +import java.util.Set; + +/** + * Lightweight Apple video service that avoids initializing the native FFM + * bridge when service discovery runs on another operating system. + */ +public final class AppleVideoBackend implements VideoFrameExtractorProvider { + + private static final boolean IS_MACOS = System.getProperty("os.name", "") + .toLowerCase(Locale.ROOT).contains("mac"); + + private static final Set FORMATS = Set.of("mp4", "mov", "m4v", "3gp"); + + @Override + public String id() { + return "apple"; + } + + @Override + public RoutingBackend.Kind kind() { + return RoutingBackend.Kind.PLATFORM_NATIVE; + } + + @Override + public boolean isAvailable() { + return IS_MACOS && delegate().isAvailable(); + } + + @Override + public Set formats() { + return FORMATS; + } + + @Override + public boolean canDecode(Path videoFile) { + return IS_MACOS && delegate().canDecode(videoFile); + } + + @Override + public BufferedImage extractFrame(Path videoFile, Duration time) + throws IOException { + return delegate().extractFrame(videoFile, time); + } + + @Override + public BufferedImage extractFrame( + Path videoFile, Duration time, Dimension renderSize) + throws IOException { + return delegate().extractFrame(videoFile, time, renderSize); + } + + @Override + public boolean supportsRenderSizeReduction() { + return IS_MACOS && delegate().supportsRenderSizeReduction(); + } + + @Override + public VideoInfo getInfo(Path videoFile) throws IOException { + return delegate().getInfo(videoFile); + } + + private static AppleVideoFrameExtractor delegate() { + return Holder.INSTANCE; + } + + private static final class Holder { + private static final AppleVideoFrameExtractor INSTANCE = + new AppleVideoFrameExtractor(); + } +} diff --git a/imageio-native-video-apple/src/main/java/module-info.java b/imageio-native-video-apple/src/main/java/module-info.java index 5cf8adc..ca99644 100644 --- a/imageio-native-video-apple/src/main/java/module-info.java +++ b/imageio-native-video-apple/src/main/java/module-info.java @@ -7,7 +7,7 @@ exports io.github.ghosthack.imageio.video.apple; provides io.github.ghosthack.imageio.common.RoutingBackend - with io.github.ghosthack.imageio.video.apple.AppleVideoFrameExtractor; + with io.github.ghosthack.imageio.video.apple.internal.AppleVideoBackend; provides io.github.ghosthack.imageio.video.VideoFrameExtractorProvider - with io.github.ghosthack.imageio.video.apple.AppleVideoFrameExtractor; + with io.github.ghosthack.imageio.video.apple.internal.AppleVideoBackend; } diff --git a/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.common.RoutingBackend b/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.common.RoutingBackend index 3cdd7ad..9209fcc 100644 --- a/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.common.RoutingBackend +++ b/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.common.RoutingBackend @@ -1 +1 @@ -io.github.ghosthack.imageio.video.apple.AppleVideoFrameExtractor +io.github.ghosthack.imageio.video.apple.internal.AppleVideoBackend diff --git a/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.video.VideoFrameExtractorProvider b/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.video.VideoFrameExtractorProvider index 3cdd7ad..9209fcc 100644 --- a/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.video.VideoFrameExtractorProvider +++ b/imageio-native-video-apple/src/main/resources/META-INF/services/io.github.ghosthack.imageio.video.VideoFrameExtractorProvider @@ -1 +1 @@ -io.github.ghosthack.imageio.video.apple.AppleVideoFrameExtractor +io.github.ghosthack.imageio.video.apple.internal.AppleVideoBackend diff --git a/imageio-native-video-windows/src/main/java/io/github/ghosthack/imageio/video/windows/WindowsVideoFrameExtractor.java b/imageio-native-video-windows/src/main/java/io/github/ghosthack/imageio/video/windows/WindowsVideoFrameExtractor.java index 18585f9..b7035e7 100644 --- a/imageio-native-video-windows/src/main/java/io/github/ghosthack/imageio/video/windows/WindowsVideoFrameExtractor.java +++ b/imageio-native-video-windows/src/main/java/io/github/ghosthack/imageio/video/windows/WindowsVideoFrameExtractor.java @@ -25,6 +25,9 @@ */ public class WindowsVideoFrameExtractor implements VideoFrameExtractorProvider { + private static final boolean IS_WINDOWS = System.getProperty("os.name", "") + .toLowerCase(Locale.ROOT).contains("windows"); + @Override public String id() { return "windows"; @@ -37,7 +40,7 @@ public Kind kind() { @Override public boolean isAvailable() { - return MediaFoundation.isAvailable(); + return IS_WINDOWS && MediaFoundation.isAvailable(); } @Override diff --git a/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/WindowsImageBackend.java b/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/WindowsImageBackend.java index 5c66abb..a3e84c8 100644 --- a/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/WindowsImageBackend.java +++ b/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/WindowsImageBackend.java @@ -6,10 +6,14 @@ import javax.imageio.ImageReader; import javax.imageio.spi.ImageReaderSpi; +import java.util.Locale; /** Windows Imaging Component backend service consumed by the common router. */ public final class WindowsImageBackend implements ImageDecoderBackend { + private static final boolean IS_WINDOWS = System.getProperty("os.name", "") + .toLowerCase(Locale.ROOT).contains("windows"); + @Override public String id() { return "windows"; @@ -27,12 +31,12 @@ public io.github.ghosthack.imageio.common.FormatRegistry formats() { @Override public boolean isAvailable() { - return WIC.isAvailable(); + return IS_WINDOWS && WIC.isAvailable(); } @Override public boolean canDecode(byte[] header, int length) { - return WIC.canDecode(header, length); + return IS_WINDOWS && WIC.canDecode(header, length); } @Override From 844aa4aba8c0d3efe5fba7b2c02d930680670f1e Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:49:28 -0800 Subject: [PATCH 2/7] Route every reader from the input it is given The routing SPIs kept the decision made in canDecodeInput in a thread-local and handed it to the next createReaderInstance call. A caller that probed one input and then asked for a reader by format name received the backend chosen for the earlier input. Always return a deferred reader that selects its owner from the input passed to setInput. RoutingImageReader now reports the owning backend and forwards listeners and abort to the backend reader. The video reader re-routes on each input unless it was bound to a backend. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- README.md | 11 +- .../imageio/apple/AppleImageReaderTest.java | 76 +++++++++++- .../imageio/common/RoutingImageReader.java | 117 ++++++++++++++++-- .../imageio/common/RoutingImageReaderSpi.java | 21 ++-- .../common/RoutingImageReaderSpiTest.java | 23 ++++ .../imageio/video/NativeVideoReader.java | 13 +- .../video/VideoRoutingImageReaderSpi.java | 23 ++-- .../imageio/video/NativeVideoReaderTest.java | 42 +++++++ .../imageio/windows/WicImageReaderTest.java | 4 +- 9 files changed, 284 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 038f93d..c6f6898 100644 --- a/README.md +++ b/README.md @@ -294,7 +294,7 @@ ImageIO v routing SPI | - +-- detect the format once + +-- detect the format +-- discover installed backend services +-- run lightweight capability probes +-- resolve ownership @@ -305,6 +305,13 @@ The routing SPI is ordered before host readers, but returns `false` whenever no added backend owns the input. Consequently it affects a host format only when an installed backend has positively claimed that particular input. +Readers handed out by the routing SPI are always `RoutingImageReader` +instances. Each one resolves its owner from the input passed to `setInput`, +so a reader obtained by format name, suffix, or MIME type, or reused for a +second input, is routed exactly like one obtained from +`ImageIO.getImageReaders(input)`. `RoutingImageReader.backendId()` reports +which backend owns the current input. + Backend-to-backend `IIORegistry.setOrdering()`, shared format advertisements on every backend SPI, global priority properties, and decode-time retry chains are not part of this design. @@ -469,7 +476,7 @@ ImageIO.read(file) ▼ RoutingImageReaderSpi one SPI for all still-image backends │ - ├── detect format once + ├── detect format ├── discover installed backend services ├── probe actual input capability └── resolve exactly one owner diff --git a/imageio-native-apple/src/test/java/io/github/ghosthack/imageio/apple/AppleImageReaderTest.java b/imageio-native-apple/src/test/java/io/github/ghosthack/imageio/apple/AppleImageReaderTest.java index 9dc9782..11337d8 100644 --- a/imageio-native-apple/src/test/java/io/github/ghosthack/imageio/apple/AppleImageReaderTest.java +++ b/imageio-native-apple/src/test/java/io/github/ghosthack/imageio/apple/AppleImageReaderTest.java @@ -119,8 +119,10 @@ void pngInputUsesAppleReader() throws IOException { Iterator readers = ImageIO.getImageReaders(iis); assertTrue(readers.hasNext()); ImageReader reader = readers.next(); - assertInstanceOf(AppleImageReader.class, reader); + RoutingImageReader routed = + assertInstanceOf(RoutingImageReader.class, reader); reader.setInput(iis); + assertEquals("apple", routed.backendId()); BufferedImage img = reader.read(0); assertNotNull(img, "PNG should still be readable"); assertEquals(8, img.getWidth()); @@ -128,6 +130,78 @@ void pngInputUsesAppleReader() throws IOException { } } + // ── Routing follows the input that is set, not an earlier probe ───── + + @Test + void readerCreatedByNameIgnoresAnEarlierProbe() throws IOException { + // Probe a PNG and deliberately never create a reader for it. + try (InputStream is = getClass().getClassLoader().getResourceAsStream("test8x8.png"); + ImageInputStream iis = ImageIO.createImageInputStream(is)) { + assertTrue(ImageIO.getImageReaders(iis).hasNext()); + } + + ImageReader reader = ImageIO.getImageReadersByFormatName("heic").next(); + try (InputStream is = getClass().getClassLoader().getResourceAsStream("test8x8.heic"); + ImageInputStream iis = ImageIO.createImageInputStream(is)) { + RoutingImageReader routed = + assertInstanceOf(RoutingImageReader.class, reader); + reader.setInput(iis); + assertEquals("apple", routed.backendId()); + assertEquals(8, reader.read(0).getWidth()); + } finally { + reader.dispose(); + } + } + + @Test + void routedReaderReroutesWhenInputChanges() throws IOException { + ImageReader reader = ImageIO.getImageReadersByFormatName("png").next(); + try { + for (String resource : new String[]{"test8x8.png", "test8x8.webp"}) { + try (InputStream is = getClass().getClassLoader().getResourceAsStream(resource); + ImageInputStream iis = ImageIO.createImageInputStream(is)) { + reader.setInput(iis); + assertEquals(8, reader.getWidth(0), resource); + assertEquals(8, reader.read(0).getHeight(), resource); + } + } + } finally { + reader.dispose(); + } + } + + @Test + void progressListenersReachTheBackendReader() throws IOException { + java.util.concurrent.atomic.AtomicInteger completed = + new java.util.concurrent.atomic.AtomicInteger(); + javax.imageio.event.IIOReadProgressListener listener = + new javax.imageio.event.IIOReadProgressListener() { + @Override public void sequenceStarted(ImageReader source, int minIndex) {} + @Override public void sequenceComplete(ImageReader source) {} + @Override public void imageStarted(ImageReader source, int imageIndex) {} + @Override public void imageProgress(ImageReader source, float percentageDone) {} + @Override public void imageComplete(ImageReader source) { + completed.incrementAndGet(); + } + @Override public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {} + @Override public void thumbnailProgress(ImageReader source, float percentageDone) {} + @Override public void thumbnailComplete(ImageReader source) {} + @Override public void readAborted(ImageReader source) {} + }; + try (InputStream is = getClass().getClassLoader().getResourceAsStream("test8x8.png"); + ImageInputStream iis = ImageIO.createImageInputStream(is)) { + ImageReader reader = ImageIO.getImageReaders(iis).next(); + try { + reader.addIIOReadProgressListener(listener); + reader.setInput(iis); + reader.read(0); + assertEquals(1, completed.get()); + } finally { + reader.dispose(); + } + } + } + @Test void sourceRenderSizeUsesReducedDecodePath() throws IOException { try (InputStream is = getClass().getClassLoader().getResourceAsStream("test8x8.png"); diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReader.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReader.java index 13ec674..c3a1bde 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReader.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReader.java @@ -4,23 +4,42 @@ import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; +import javax.imageio.event.IIOReadProgressListener; +import javax.imageio.event.IIOReadUpdateListener; +import javax.imageio.event.IIOReadWarningListener; import javax.imageio.metadata.IIOMetadata; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Iterator; /** - * Deferred reader used when a caller creates the routing SPI by format name - * rather than by probing an input first. + * Reader returned by the routing SPI. It selects the owning backend from the + * input that is actually set and delegates every operation to that backend's + * reader. + * + *

Listeners registered here are forwarded to the backend reader, so the + * events they receive name that reader as their source.

*/ public final class RoutingImageReader extends ImageReader { private ImageReader delegate; + private String backendId; RoutingImageReader(RoutingImageReaderSpi provider) { super(provider); } + /** + * Returns the ID of the backend that owns the current input, such as + * {@code apple} or {@code vips}. + * + * @throws IIOException if no installed backend owns the input + */ + public String backendId() throws IOException { + delegate(); + return backendId; + } + @Override public int getNumImages(boolean allowSearch) throws IOException { return delegate().getNumImages(allowSearch); @@ -64,29 +83,109 @@ public BufferedImage read(int imageIndex, ImageReadParam param) throws IOExcepti @Override public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) { super.setInput(input, seekForwardOnly, ignoreMetadata); - if (delegate != null) { - delegate.dispose(); - delegate = null; - } + releaseDelegate(); } @Override public void dispose() { + releaseDelegate(); + super.dispose(); + } + + @Override + public synchronized void abort() { + super.abort(); + if (delegate != null) delegate.abort(); + } + + // ── Listener forwarding ───────────────────────────────────────────── + + @Override + public void addIIOReadProgressListener(IIOReadProgressListener listener) { + super.addIIOReadProgressListener(listener); + if (delegate != null) delegate.addIIOReadProgressListener(listener); + } + + @Override + public void removeIIOReadProgressListener(IIOReadProgressListener listener) { + super.removeIIOReadProgressListener(listener); + if (delegate != null) delegate.removeIIOReadProgressListener(listener); + } + + @Override + public void removeAllIIOReadProgressListeners() { + super.removeAllIIOReadProgressListeners(); + if (delegate != null) delegate.removeAllIIOReadProgressListeners(); + } + + @Override + public void addIIOReadWarningListener(IIOReadWarningListener listener) { + super.addIIOReadWarningListener(listener); + if (delegate != null) delegate.addIIOReadWarningListener(listener); + } + + @Override + public void removeIIOReadWarningListener(IIOReadWarningListener listener) { + super.removeIIOReadWarningListener(listener); + if (delegate != null) delegate.removeIIOReadWarningListener(listener); + } + + @Override + public void removeAllIIOReadWarningListeners() { + super.removeAllIIOReadWarningListeners(); + if (delegate != null) delegate.removeAllIIOReadWarningListeners(); + } + + @Override + public void addIIOReadUpdateListener(IIOReadUpdateListener listener) { + super.addIIOReadUpdateListener(listener); + if (delegate != null) delegate.addIIOReadUpdateListener(listener); + } + + @Override + public void removeIIOReadUpdateListener(IIOReadUpdateListener listener) { + super.removeIIOReadUpdateListener(listener); + if (delegate != null) delegate.removeIIOReadUpdateListener(listener); + } + + @Override + public void removeAllIIOReadUpdateListeners() { + super.removeAllIIOReadUpdateListeners(); + if (delegate != null) delegate.removeAllIIOReadUpdateListeners(); + } + + // ── Delegate lifecycle ────────────────────────────────────────────── + + private void releaseDelegate() { if (delegate != null) { delegate.dispose(); delegate = null; } - super.dispose(); + backendId = null; } private ImageReader delegate() throws IOException { if (delegate != null) return delegate; + if (getInput() == null) { + throw new IllegalStateException("No input set"); + } ImageRouting.Decision decision = ImageRouting.select(getInput()); if (decision == null) { throw new IIOException("No imageio-native backend owns this input"); } - delegate = decision.backend().createReader(getOriginatingProvider()); - delegate.setInput(getInput(), isSeekForwardOnly(), isIgnoringMetadata()); + ImageReader reader = decision.backend().createReader(getOriginatingProvider()); + if (progressListeners != null) { + progressListeners.forEach(reader::addIIOReadProgressListener); + } + if (warningListeners != null) { + warningListeners.forEach(reader::addIIOReadWarningListener); + } + if (updateListeners != null) { + updateListeners.forEach(reader::addIIOReadUpdateListener); + } + reader.setInput(getInput(), isSeekForwardOnly(), isIgnoringMetadata()); + delegate = reader; + backendId = decision.backend().id(); return delegate; } } diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpi.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpi.java index 25c29b1..197d40d 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpi.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpi.java @@ -18,8 +18,6 @@ */ public final class RoutingImageReaderSpi extends ImageReaderSpi { - private static final ThreadLocal PENDING = new ThreadLocal<>(); - public RoutingImageReaderSpi() { this(Metadata.discover()); } @@ -36,22 +34,17 @@ private RoutingImageReaderSpi(Metadata metadata) { @Override public boolean canDecodeInput(Object source) throws IOException { - ImageRouting.Decision decision = ImageRouting.select(source); - if (decision == null) { - PENDING.remove(); - return false; - } - PENDING.set(decision); - return true; + return ImageRouting.select(source) != null; } + /** + * Always returns a deferred reader. Ownership is resolved from the input + * the caller actually sets, never from an earlier probe, so a reader + * obtained by format name, suffix, or MIME type cannot inherit the + * decision made for a different input. + */ @Override public ImageReader createReaderInstance(Object extension) { - ImageRouting.Decision decision = PENDING.get(); - PENDING.remove(); - if (decision != null) { - return decision.backend().createReader(this); - } return new RoutingImageReader(this); } diff --git a/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpiTest.java b/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpiTest.java index cbec8e6..be7914a 100644 --- a/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpiTest.java +++ b/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/RoutingImageReaderSpiTest.java @@ -6,6 +6,8 @@ import java.io.ByteArrayInputStream; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class RoutingImageReaderSpiTest { @@ -28,4 +30,25 @@ void routedReaderAdvertisesSourceRenderSizeBeforeInputIsSet() { reader.dispose(); } } + + @Test + void providerAlwaysCreatesTheDeferredRoutingReader() throws Exception { + RoutingImageReaderSpi provider = new RoutingImageReaderSpi(); + byte[] png = {(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10}; + try (var input = new MemoryCacheImageInputStream(new ByteArrayInputStream(png))) { + provider.canDecodeInput(input); + } + assertInstanceOf(RoutingImageReader.class, provider.createReaderInstance(null)); + } + + @Test + void routedReaderRequiresInputBeforeResolvingABackend() { + RoutingImageReader reader = + new RoutingImageReader(new RoutingImageReaderSpi()); + try { + assertThrows(IllegalStateException.class, reader::backendId); + } finally { + reader.dispose(); + } + } } diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java index 7b295a1..be623cb 100644 --- a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java +++ b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java @@ -21,8 +21,9 @@ * {@link ImageReader} that extracts the poster frame from a video file. *

* This is a concrete class (not abstract) that delegates to a - * {@link VideoFrameExtractorProvider} for actual frame extraction. Each - * video backend's SPI creates an instance of this class with its provider. + * {@link VideoFrameExtractorProvider} for actual frame extraction. The + * routing SPI creates instances that select the owning backend from each + * input; callers may also bind a reader to one backend. *

* Supports a single image (the poster frame at t=0). For time-based * extraction or multi-frame access, use {@link VideoFrameExtractor} directly. @@ -36,17 +37,22 @@ public class NativeVideoReader extends ImageReader { private static final long MAX_INTERMEDIATE_BYTES = Long.getLong( "imageio.native.maxIntermediateBytes", 512L * 1024 * 1024); + /** Backend fixed by the caller, or {@code null} to route per input. */ + private final VideoFrameExtractorProvider fixedProvider; private VideoFrameExtractorProvider provider; private volatile VideoInfo cachedInfo; + /** Creates a reader bound to one backend for every input. */ public NativeVideoReader(ImageReaderSpi originatingProvider, VideoFrameExtractorProvider extractorProvider) { super(originatingProvider); + this.fixedProvider = extractorProvider; this.provider = extractorProvider; } + /** Creates a reader that selects the owning backend for each input. */ public NativeVideoReader(ImageReaderSpi originatingProvider) { - super(originatingProvider); + this(originatingProvider, null); } @Override @@ -118,6 +124,7 @@ public IIOMetadata getImageMetadata(int imageIndex) { public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) { super.setInput(input, seekForwardOnly, ignoreMetadata); cachedInfo = null; + provider = fixedProvider; } @Override diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoRoutingImageReaderSpi.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoRoutingImageReaderSpi.java index 4997db9..ab0c502 100644 --- a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoRoutingImageReaderSpi.java +++ b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoRoutingImageReaderSpi.java @@ -13,8 +13,6 @@ /** The single ImageIO provider for all video poster-frame backends. */ public final class VideoRoutingImageReaderSpi extends ImageReaderSpi { - private static final ThreadLocal PENDING = new ThreadLocal<>(); - public VideoRoutingImageReaderSpi() { super("imageio-native", "2.0", VideoFormatRegistry.FORMAT_NAMES, @@ -30,27 +28,20 @@ public VideoRoutingImageReaderSpi() { @Override public boolean canDecodeInput(Object source) throws IOException { if (!(source instanceof io.github.ghosthack.imageio.common.PathAwareImageInputStream stream)) { - PENDING.remove(); return false; } String format = VideoFormatDetector.detectFormat(stream); - VideoRouting.Decision decision = format == null - ? null : VideoRouting.select(stream.getPath(), format); - if (decision == null) { - PENDING.remove(); - return false; - } - PENDING.set(decision); - return true; + return format != null + && VideoRouting.select(stream.getPath(), format) != null; } + /** + * Always returns a reader that routes from the input the caller sets, + * never from an earlier probe of a different input. + */ @Override public ImageReader createReaderInstance(Object extension) { - VideoRouting.Decision decision = PENDING.get(); - PENDING.remove(); - return decision == null - ? new NativeVideoReader(this) - : new NativeVideoReader(this, decision.backend()); + return new NativeVideoReader(this); } @Override diff --git a/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/NativeVideoReaderTest.java b/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/NativeVideoReaderTest.java index db14841..4986be8 100644 --- a/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/NativeVideoReaderTest.java +++ b/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/NativeVideoReaderTest.java @@ -20,6 +20,48 @@ class NativeVideoReaderTest { + @Test + void routingProviderCreatesReaderThatRoutesPerInput() throws IOException { + Path file = Files.createTempFile("imageio-native-video-reader-", ".mp4"); + try (PathAwareImageInputStream input = + new PathAwareImageInputStream(file.toFile())) { + NativeVideoReader reader = (NativeVideoReader) + new VideoRoutingImageReaderSpi().createReaderInstance(null); + try { + reader.setInput(input); + // An empty file is not a video, so routing must decline it + // rather than reuse a backend chosen for some earlier input. + assertThrows(IOException.class, () -> reader.getWidth(0)); + } finally { + reader.dispose(); + } + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void boundReaderKeepsItsBackendAcrossInputs() throws IOException { + Path file = Files.createTempFile("imageio-native-video-reader-", ".mp4"); + try { + NativeVideoReader reader = + new NativeVideoReader(null, new TestProvider()); + try { + for (int i = 0; i < 2; i++) { + try (PathAwareImageInputStream input = + new PathAwareImageInputStream(file.toFile())) { + reader.setInput(input); + assertEquals(reader.getWidth(0), reader.read(0).getWidth()); + } + } + } finally { + reader.dispose(); + } + } finally { + Files.deleteIfExists(file); + } + } + @Test void readAppliesImageReadParamToExtractedFrame() throws IOException { Path file = Files.createTempFile("imageio-native-video-reader-", ".mp4"); diff --git a/imageio-native-windows/src/test/java/io/github/ghosthack/imageio/windows/WicImageReaderTest.java b/imageio-native-windows/src/test/java/io/github/ghosthack/imageio/windows/WicImageReaderTest.java index e092cf3..b2a1cbd 100644 --- a/imageio-native-windows/src/test/java/io/github/ghosthack/imageio/windows/WicImageReaderTest.java +++ b/imageio-native-windows/src/test/java/io/github/ghosthack/imageio/windows/WicImageReaderTest.java @@ -136,8 +136,10 @@ void pngInputUsesWicReader() throws IOException { Iterator readers = ImageIO.getImageReaders(iis); assertTrue(readers.hasNext()); ImageReader reader = readers.next(); - assertInstanceOf(WicImageReader.class, reader); + RoutingImageReader routed = + assertInstanceOf(RoutingImageReader.class, reader); reader.setInput(iis); + assertEquals("windows", routed.backendId()); BufferedImage img = reader.read(0); assertNotNull(img, "PNG should still be readable"); assertEquals(8, img.getWidth()); From 789ef5d6bbedd6e99990dbe2bf696e38302b46c1 Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:51:49 -0800 Subject: [PATCH 3/7] Apply EXIF orientation in the libvips and ImageMagick backends Apple and WIC return display-oriented images, but libvips and ImageMagick returned the stored orientation. Because portable backends win intersections by default, installing either one un-rotated phone photos. libvips also disagreed with itself: reduced decodes go through vips_thumbnail, which rotates, while full decodes did not. Rotate full, cropped, and reduced decodes in both backends and report display-oriented dimensions from the size queries. libvips reopens an image with random access when it needs a transform, since rotation cannot be streamed. The per-call downcall handle for the sequential loader is now created once. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- README.md | 10 +- .../imageio/magick/MagickNative.java | 40 +++++- .../imageio/magick/MagickImageReaderTest.java | 93 +++++++++++++ .../ghosthack/imageio/vips/VipsNative.java | 129 +++++++++++++----- .../imageio/vips/VipsImageReaderTest.java | 90 ++++++++++++ 5 files changed, 320 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index c6f6898..5b0a8c5 100644 --- a/README.md +++ b/README.md @@ -530,7 +530,7 @@ render sizes. Override the limit in bytes with ### EXIF orientation -Images from phones and cameras often carry an EXIF orientation tag (values 1-8) that describes how the sensor image should be rotated or flipped for correct display. Both backends apply this transform automatically during decode so the returned `BufferedImage` is always display-ready. +Images from phones and cameras often carry an EXIF orientation tag (values 1-8) that describes how the sensor image should be rotated or flipped for correct display. Every still-image backend applies this transform automatically during decode, so the returned `BufferedImage` is display-ready and the same input has the same orientation whichever backend owns it. | EXIF value | Transform | |------------|-----------| @@ -547,9 +547,13 @@ Images from phones and cameras often carry an EXIF orientation tag (values 1-8) **Windows (WIC):** Reads the EXIF orientation tag via `IWICMetadataQueryReader`, then inserts an `IWICBitmapFlipRotator` between the frame decoder and the format converter. The flip-rotator is a zero-copy coordinate remap -- it transforms pixel coordinates during `CopyPixels` rather than allocating a second buffer. For orientation 1 (no rotation), the flip-rotator is skipped entirely. -Both `getSize()` and `decode()` are orientation-aware: dimensions are swapped for orientations 5-8 (90/270 rotations), so width and height always reflect the display-oriented image. +**libvips:** Applies `vips_autorot` to full and cropped decodes; `vips_thumbnail` already rotates reduced decodes. Upright images stream with sequential access, while an image that needs a transform is opened with random access because rotation cannot be streamed. -**Performance impact:** Negligible. Both platforms apply the transform as part of the existing decode pipeline with no extra buffer allocations or pixel copies. The macOS path creates a small options dictionary per decode call; the Windows flip-rotator is a zero-copy coordinate remap. Orientation 1 (the common case for non-phone images) skips the transform entirely. +**ImageMagick:** Calls `MagickAutoOrientImage` after reading and before any resize or crop. + +Size queries and decodes are orientation-aware on every backend: dimensions are swapped for orientations 5-8 (90/270 rotations), so width and height always reflect the display-oriented image. + +**Performance impact:** Negligible on the platform backends. Both platforms apply the transform as part of the existing decode pipeline with no extra buffer allocations or pixel copies. The macOS path creates a small options dictionary per decode call; the Windows flip-rotator is a zero-copy coordinate remap. Orientation 1 (the common case for non-phone images) skips the transform entirely. libvips and ImageMagick rotate in memory, so a rotated image costs one extra pass there. ## Project structure diff --git a/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/MagickNative.java b/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/MagickNative.java index a0086fb..1e27ca0 100644 --- a/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/MagickNative.java +++ b/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/MagickNative.java @@ -60,6 +60,8 @@ private MagickNative() {} private static final MethodHandle MagickPingImageBlob; private static final MethodHandle MagickGetImageWidth; private static final MethodHandle MagickGetImageHeight; + private static final MethodHandle MagickGetImageOrientation; + private static final MethodHandle MagickAutoOrientImage; private static final MethodHandle MagickSetImageAlphaChannel; private static final MethodHandle MagickResizeImage; private static final MethodHandle MagickExportImagePixels; @@ -100,6 +102,10 @@ private MagickNative() {} FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)); MagickGetImageHeight = downcall("MagickGetImageHeight", FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)); + MagickGetImageOrientation = downcall("MagickGetImageOrientation", + FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)); + MagickAutoOrientImage = downcall("MagickAutoOrientImage", + FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)); MagickSetImageAlphaChannel = downcall("MagickSetImageAlphaChannel", FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_INT)); @@ -138,6 +144,8 @@ private MagickNative() {} MagickPingImageBlob = null; MagickGetImageWidth = null; MagickGetImageHeight = null; + MagickGetImageOrientation = null; + MagickAutoOrientImage = null; MagickSetImageAlphaChannel = null; MagickResizeImage = null; MagickExportImagePixels = null; @@ -193,7 +201,7 @@ static int[] getSize(byte[] imageData) throws IOException { int h = (int) (long) MagickGetImageHeight.invokeExact(wand); if (w <= 0 || h <= 0) throw new IIOException("Invalid image dimensions: " + w + "x" + h); - return new int[]{w, h}; + return orientedSize(wand, w, h); } finally { destroyWand(wand); } @@ -222,7 +230,7 @@ static int[] getSizeFromPath(String path) throws IOException { int h = (int) (long) MagickGetImageHeight.invokeExact(wand); if (w <= 0 || h <= 0) throw new IIOException("Invalid image dimensions: " + w + "x" + h); - return new int[]{w, h}; + return orientedSize(wand, w, h); } finally { destroyWand(wand); } @@ -267,6 +275,7 @@ private static BufferedImage decode( if (rc != MagickTrue) throw new IIOException("ImageMagick read failed: " + errorMessage(arena, wand)); + autoOrient(arena, wand); resize(wand, renderSize); return exportPixels(arena, wand, request); } finally { @@ -313,6 +322,7 @@ private static BufferedImage decodeFromPath( throw new IIOException("ImageMagick read failed for: " + path + " — " + errorMessage(arena, wand)); + autoOrient(arena, wand); resize(wand, renderSize); return exportPixels(arena, wand, request); } finally { @@ -327,6 +337,32 @@ private static BufferedImage decodeFromPath( // ── Internal ──────────────────────────────────────────────────────── + /** + * Returns display-oriented dimensions: EXIF orientations 5-8 (the + * MagickCore {@code LeftTop} .. {@code LeftBottom} values) transpose the + * stored image, so width and height are swapped. + */ + private static int[] orientedSize(MemorySegment wand, int w, int h) + throws Throwable { + int orientation = (int) MagickGetImageOrientation.invokeExact(wand); + return orientation >= 5 && orientation <= 8 + ? new int[]{h, w} + : new int[]{w, h}; + } + + /** + * Applies the EXIF orientation so the decoded pixels are display-ready, + * matching the platform-native backends. + */ + private static void autoOrient(Arena arena, MemorySegment wand) + throws Throwable { + int rc = (int) MagickAutoOrientImage.invokeExact(wand); + if (rc != MagickTrue) { + throw new IIOException("ImageMagick auto-orient failed: " + + errorMessage(arena, wand)); + } + } + private static void resize(MemorySegment wand, Dimension renderSize) throws Throwable { if (renderSize == null) { diff --git a/imageio-native-magick/src/test/java/io/github/ghosthack/imageio/magick/MagickImageReaderTest.java b/imageio-native-magick/src/test/java/io/github/ghosthack/imageio/magick/MagickImageReaderTest.java index 6b63d92..112b765 100644 --- a/imageio-native-magick/src/test/java/io/github/ghosthack/imageio/magick/MagickImageReaderTest.java +++ b/imageio-native-magick/src/test/java/io/github/ghosthack/imageio/magick/MagickImageReaderTest.java @@ -14,6 +14,8 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -150,6 +152,97 @@ void combinesNativeRenderAndSpatialSelection() throws IOException { assertEquals(2, result.getHeight()); } + // ── EXIF orientation ──────────────────────────────────────────────── + // test-orient6.jpg is stored 4x8 with EXIF orientation 6 (rotate 90° CW). + // Display-oriented it is 8x4: Blue(TL) Red(TR) / White(BL) Green(BR). + + @Test + void sizeQueriesReportDisplayOrientation() throws IOException { + assumeMagick(); + byte[] data = loadResource("test-orient6.jpg"); + assertArrayEquals(new int[]{8, 4}, MagickNative.getSize(data)); + + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, data); + assertArrayEquals(new int[]{8, 4}, + MagickNative.getSizeFromPath(file.toString())); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void fullDecodeAppliesExifOrientation() throws IOException { + assumeMagick(); + byte[] data = loadResource("test-orient6.jpg"); + assertDisplayOriented(MagickNative.decode(data), 8, 4); + + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, data); + assertDisplayOriented( + MagickNative.decodeFromPath(file.toString()), 8, 4); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void renderSizedDecodeMatchesFullDecodeOrientation() throws IOException { + assumeMagick(); + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, loadResource("test-orient6.jpg")); + assertDisplayOriented(MagickNative.decodeFromPath( + file.toString(), new Dimension(16, 8)), 16, 8); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void sourceRegionIsSelectedInDisplayOrientation() throws IOException { + assumeMagick(); + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, loadResource("test-orient6.jpg")); + ImageReadParam param = + ImageReadParamSupport.createDefaultReadParam(); + // Right half of the 8x4 display image: Red over Green. + param.setSourceRegion(new Rectangle(4, 0, 4, 4)); + NativeDecodeRequest request = + NativeDecodeRequest.from(param, 8, 4); + + BufferedImage region = MagickNative.decodeFromPath(file.toString(), request); + + assertEquals(4, region.getWidth()); + assertEquals(4, region.getHeight()); + TestPixels.assertColourClose( + "region top (red)", 0xFFFF0000, region.getRGB(2, 0), 70); + TestPixels.assertColourClose( + "region bottom (green)", 0xFF00FF00, region.getRGB(2, 3), 70); + } finally { + Files.deleteIfExists(file); + } + } + + private static void assertDisplayOriented( + BufferedImage image, int width, int height) { + assertEquals(width, image.getWidth(), "display width"); + assertEquals(height, image.getHeight(), "display height"); + int right = width - 1; + int bottom = height - 1; + TestPixels.assertColourClose( + "top-left (blue)", 0xFF0000FF, image.getRGB(0, 0), 70); + TestPixels.assertColourClose( + "top-right (red)", 0xFFFF0000, image.getRGB(right, 0), 70); + TestPixels.assertColourClose( + "bottom-left (white)", 0xFFFFFFFF, image.getRGB(0, bottom), 70); + TestPixels.assertColourClose( + "bottom-right (green)", 0xFF00FF00, image.getRGB(right, bottom), 70); + } + // ── Helpers ───────────────────────────────────────────────────────── private byte[] loadResource(String name) throws IOException { diff --git a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java index 1e46911..43fb46d 100644 --- a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java +++ b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java @@ -51,12 +51,15 @@ private VipsNative() {} // vips private static final MethodHandle vips_init; private static final MethodHandle vips_image_new_from_file; + private static final MethodHandle vips_image_new_from_file_access; private static final MethodHandle vips_image_new_from_buffer; private static final MethodHandle vips_thumbnail; private static final MethodHandle vips_extract_area; private static final MethodHandle vips_image_get_width; private static final MethodHandle vips_image_get_height; private static final MethodHandle vips_image_get_bands; + private static final MethodHandle vips_image_get_orientation; + private static final MethodHandle vips_autorot; private static final MethodHandle vips_image_hasalpha; private static final MethodHandle vips_colourspace; private static final MethodHandle vips_premultiply; @@ -95,6 +98,13 @@ private VipsNative() {} Linker.Option.firstVariadicArg(1)); // vips_image_new_from_buffer(void*, size_t, const char* option_string, ...) — variadic + // vips_image_new_from_file(path, "access", VipsAccess, NULL) + vips_image_new_from_file_access = LINKER.downcallHandle( + LOOKUP.find("vips_image_new_from_file").orElseThrow(), + FunctionDescriptor.of(ValueLayout.ADDRESS, + ValueLayout.ADDRESS, ValueLayout.ADDRESS, + ValueLayout.JAVA_INT, ValueLayout.ADDRESS), + Linker.Option.firstVariadicArg(1)); vips_image_new_from_buffer = LINKER.downcallHandle( LOOKUP.find("vips_image_new_from_buffer").orElseThrow(), FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, @@ -131,6 +141,14 @@ private VipsNative() {} FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)); vips_image_get_bands = downcall("vips_image_get_bands", FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)); + vips_image_get_orientation = downcall("vips_image_get_orientation", + FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)); + vips_autorot = LINKER.downcallHandle( + LOOKUP.find("vips_autorot").orElseThrow(), + FunctionDescriptor.of(ValueLayout.JAVA_INT, + ValueLayout.ADDRESS, ValueLayout.ADDRESS, + ValueLayout.ADDRESS), + Linker.Option.firstVariadicArg(2)); vips_image_hasalpha = downcall("vips_image_hasalpha", FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)); @@ -197,12 +215,15 @@ private VipsNative() {} } else { vips_init = null; vips_image_new_from_file = null; + vips_image_new_from_file_access = null; vips_image_new_from_buffer = null; vips_thumbnail = null; vips_extract_area = null; vips_image_get_width = null; vips_image_get_height = null; vips_image_get_bands = null; + vips_image_get_orientation = null; + vips_autorot = null; vips_image_hasalpha = null; vips_colourspace = null; vips_premultiply = null; @@ -261,7 +282,7 @@ static int[] getSize(byte[] imageData) throws IOException { int h = (int) vips_image_get_height.invokeExact(img); if (w <= 0 || h <= 0) throw new IIOException("Invalid image dimensions: " + w + "x" + h); - return new int[]{w, h}; + return transposes(img) ? new int[]{h, w} : new int[]{w, h}; } finally { g_object_unref.invokeExact(img); } @@ -288,7 +309,7 @@ static int[] getSizeFromPath(String path) throws IOException { int h = (int) vips_image_get_height.invokeExact(img); if (w <= 0 || h <= 0) throw new IIOException("Invalid image dimensions: " + w + "x" + h); - return new int[]{w, h}; + return transposes(img) ? new int[]{h, w} : new int[]{w, h}; } finally { g_object_unref.invokeExact(img); } @@ -310,6 +331,7 @@ static BufferedImage decode(byte[] imageData) throws IOException { buf, (long) imageData.length, MemorySegment.NULL, MemorySegment.NULL); if (MemorySegment.NULL.equals(img)) throw new IIOException("vips load failed: " + errorMessage()); + img = orient(arena, img); try { return decodeFromVipsImage(arena, img); } finally { @@ -329,23 +351,7 @@ static BufferedImage decode(byte[] imageData) throws IOException { static BufferedImage decodeFromPath(String path) throws IOException { if (!AVAILABLE) throw new IIOException("libvips is not available"); try (Arena arena = Arena.ofConfined()) { - MemorySegment accessKey = arena.allocateFrom("access", StandardCharsets.UTF_8); - MemorySegment cpath = arena.allocateFrom(path, StandardCharsets.UTF_8); - - // Load with sequential access hint for streaming performance. - // vips_image_new_from_file is variadic: (path, "access", int, NULL) - // We need a specific descriptor for this particular variadic invocation. - MethodHandle loadWithAccess = LINKER.downcallHandle( - LOOKUP.find("vips_image_new_from_file").orElseThrow(), - FunctionDescriptor.of(ValueLayout.ADDRESS, - ValueLayout.ADDRESS, ValueLayout.ADDRESS, - ValueLayout.JAVA_INT, ValueLayout.ADDRESS), - Linker.Option.firstVariadicArg(1)); - - MemorySegment img = (MemorySegment) loadWithAccess.invokeExact( - cpath, accessKey, VIPS_ACCESS_SEQUENTIAL, MemorySegment.NULL); - if (MemorySegment.NULL.equals(img)) - throw new IIOException("vips load failed for: " + path + " — " + errorMessage()); + MemorySegment img = loadOrientedFile(arena, path); try { return decodeFromVipsImage(arena, img); } finally { @@ -510,28 +516,77 @@ private static MemorySegment loadForRequest( return output.get(ValueLayout.ADDRESS, 0); } + return loadOrientedFile(arena, path); + } + + // ── EXIF orientation ──────────────────────────────────────────────── + + /** Returns the EXIF orientation (1-8); 1 when the image carries none. */ + private static int orientation(MemorySegment img) throws Throwable { + int orientation = (int) vips_image_get_orientation.invokeExact(img); + return orientation >= 1 && orientation <= 8 ? orientation : 1; + } + + /** Orientations 5-8 transpose the stored image, swapping width and height. */ + private static boolean transposes(MemorySegment img) throws Throwable { + return orientation(img) >= 5; + } + + /** + * Applies the EXIF orientation so pixels are display-ready, matching + * {@code vips_thumbnail} and the platform-native backends. + *

+ * Takes ownership of {@code img}: the returned image replaces it and is + * the only reference the caller must release. + */ + private static MemorySegment orient(Arena arena, MemorySegment img) + throws Throwable { + if (orientation(img) == 1) { + return img; + } + try { + MemorySegment output = arena.allocate(ValueLayout.ADDRESS); + int rc = (int) vips_autorot.invokeExact( + img, output, MemorySegment.NULL); + if (rc != 0) { + throw new IIOException("vips autorot failed: " + errorMessage()); + } + return output.get(ValueLayout.ADDRESS, 0); + } finally { + g_object_unref.invokeExact(img); + } + } + + /** + * Opens a file and returns it display-oriented. Upright images stream + * with sequential access; rotation needs random access, so an image with + * a non-identity orientation is reopened without the sequential hint. + * The caller owns the returned image. + */ + private static MemorySegment loadOrientedFile(Arena arena, String path) + throws Throwable { + MemorySegment cpath = arena.allocateFrom(path, StandardCharsets.UTF_8); MemorySegment accessKey = arena.allocateFrom("access", StandardCharsets.UTF_8); - MethodHandle loadWithAccess = LINKER.downcallHandle( - LOOKUP.find("vips_image_new_from_file").orElseThrow(), - FunctionDescriptor.of( - ValueLayout.ADDRESS, - ValueLayout.ADDRESS, - ValueLayout.ADDRESS, - ValueLayout.JAVA_INT, - ValueLayout.ADDRESS), - Linker.Option.firstVariadicArg(1)); - MemorySegment image = (MemorySegment) loadWithAccess.invokeExact( - cpath, - accessKey, - VIPS_ACCESS_SEQUENTIAL, - MemorySegment.NULL); - if (MemorySegment.NULL.equals(image)) { + MemorySegment img = + (MemorySegment) vips_image_new_from_file_access.invokeExact( + cpath, accessKey, VIPS_ACCESS_SEQUENTIAL, + MemorySegment.NULL); + if (MemorySegment.NULL.equals(img)) { + throw new IIOException( + "vips load failed for: " + path + " — " + errorMessage()); + } + if (orientation(img) == 1) { + return img; + } + g_object_unref.invokeExact(img); + img = (MemorySegment) vips_image_new_from_file.invokeExact( + cpath, MemorySegment.NULL); + if (MemorySegment.NULL.equals(img)) { throw new IIOException( - "vips load failed for: " + path - + " — " + errorMessage()); + "vips load failed for: " + path + " — " + errorMessage()); } - return image; + return orient(arena, img); } // ── Internal decode pipeline ──────────────────────────────────────── diff --git a/imageio-native-vips/src/test/java/io/github/ghosthack/imageio/vips/VipsImageReaderTest.java b/imageio-native-vips/src/test/java/io/github/ghosthack/imageio/vips/VipsImageReaderTest.java index 7246be4..64e66ea 100644 --- a/imageio-native-vips/src/test/java/io/github/ghosthack/imageio/vips/VipsImageReaderTest.java +++ b/imageio-native-vips/src/test/java/io/github/ghosthack/imageio/vips/VipsImageReaderTest.java @@ -177,6 +177,96 @@ void combinesNativeRenderAndSpatialSelection() throws IOException { } } + // ── EXIF orientation ──────────────────────────────────────────────── + // test-orient6.jpg is stored 4x8 with EXIF orientation 6 (rotate 90° CW). + // Display-oriented it is 8x4: Blue(TL) Red(TR) / White(BL) Green(BR). + + @Test + void sizeQueriesReportDisplayOrientation() throws IOException { + assumeVips(); + byte[] data = loadResource("test-orient6.jpg"); + assertArrayEquals(new int[]{8, 4}, VipsNative.getSize(data)); + + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, data); + assertArrayEquals(new int[]{8, 4}, + VipsNative.getSizeFromPath(file.toString())); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void fullDecodeAppliesExifOrientation() throws IOException { + assumeVips(); + byte[] data = loadResource("test-orient6.jpg"); + assertDisplayOriented(VipsNative.decode(data), 8, 4); + + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, data); + assertDisplayOriented( + VipsNative.decodeFromPath(file.toString()), 8, 4); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void renderSizedDecodeMatchesFullDecodeOrientation() throws IOException { + assumeVips(); + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, loadResource("test-orient6.jpg")); + assertDisplayOriented(VipsNative.decodeFromPath(file.toString(), 16, 8), 16, 8); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void sourceRegionIsSelectedInDisplayOrientation() throws IOException { + assumeVips(); + Path file = Files.createTempFile("imageio-native-orient-", ".jpg"); + try { + Files.write(file, loadResource("test-orient6.jpg")); + ImageReadParam param = + ImageReadParamSupport.createDefaultReadParam(); + // Right half of the 8x4 display image: Red over Green. + param.setSourceRegion(new Rectangle(4, 0, 4, 4)); + NativeDecodeRequest request = + NativeDecodeRequest.from(param, 8, 4); + + BufferedImage region = VipsNative.decodeFromPath(file.toString(), request); + + assertEquals(4, region.getWidth()); + assertEquals(4, region.getHeight()); + TestPixels.assertColourClose( + "region top (red)", 0xFFFF0000, region.getRGB(2, 0), 70); + TestPixels.assertColourClose( + "region bottom (green)", 0xFF00FF00, region.getRGB(2, 3), 70); + } finally { + Files.deleteIfExists(file); + } + } + + private static void assertDisplayOriented( + BufferedImage image, int width, int height) { + assertEquals(width, image.getWidth(), "display width"); + assertEquals(height, image.getHeight(), "display height"); + int right = width - 1; + int bottom = height - 1; + TestPixels.assertColourClose( + "top-left (blue)", 0xFF0000FF, image.getRGB(0, 0), 70); + TestPixels.assertColourClose( + "top-right (red)", 0xFFFF0000, image.getRGB(right, 0), 70); + TestPixels.assertColourClose( + "bottom-left (white)", 0xFFFFFFFF, image.getRGB(0, bottom), 70); + TestPixels.assertColourClose( + "bottom-right (green)", 0xFF00FF00, image.getRGB(right, bottom), 70); + } + // ── Helpers ───────────────────────────────────────────────────────── private byte[] loadResource(String name) throws IOException { From 125abb96b901f8fe8b2f8573d881422847e16b06 Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:56:32 -0800 Subject: [PATCH 4/7] Return displayed frames and sizes from the video backends AVFoundation applies the track's preferred transform when it extracts a frame, but the reported size was the stored one, so a portrait video reported 32x16 and returned a 16x32 frame. FFmpeg ignored the display matrix altogether and returned the frame sideways, and a seek returned the keyframe before the requested time rather than the frame at it. Report the displayed size on both backends, rotate FFmpeg frames by the display matrix, and decode forward from the keyframe to the requested time. Drain an autorelease pool around the AVFoundation calls so long-lived Java threads do not accumulate assets and generators. Add rotated and long-GOP fixtures with their generator scripts. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- README.md | 7 + .../video/apple/AppleVideoFrameExtractor.java | 142 +++++++++++---- .../apple/AppleVideoFrameExtractorTest.java | 29 +++ .../test/resources/test-video-long-gop.mp4 | Bin 0 -> 1913 bytes .../src/test/resources/test-video-rotated.mp4 | Bin 0 -> 2700 bytes .../ffmpeg/FFmpegVideoFrameExtractor.java | 171 +++++++++++++++--- .../ffmpeg/FFmpegVideoFrameExtractorTest.java | 71 ++++++++ scripts/generate-video-long-gop.sh | 27 +++ scripts/generate-video-rotated.sh | 36 ++++ 9 files changed, 421 insertions(+), 62 deletions(-) create mode 100644 imageio-native-video-common/src/test/resources/test-video-long-gop.mp4 create mode 100644 imageio-native-video-common/src/test/resources/test-video-rotated.mp4 create mode 100755 scripts/generate-video-long-gop.sh create mode 100755 scripts/generate-video-rotated.sh diff --git a/README.md b/README.md index 5b0a8c5..f368624 100644 --- a/README.md +++ b/README.md @@ -432,6 +432,13 @@ BufferedImage frame = VideoFrameExtractor.extractFrame( VideoInfo info = VideoFrameExtractor.getInfo(Path.of("clip.mp4")); ``` +The AVFoundation and FFmpeg backends return frames as displayed: the +container's rotation (the metadata phones record for portrait video) is +applied, and `VideoInfo` reports the displayed width and height, so it always +matches the extracted frame. With FFmpeg, a frame requested at a time is the +first frame at or after it, decoded forward from the preceding keyframe; +AVFoundation picks a frame within its seek tolerance of the requested time. + | Module | Platform | Native API | Containers | |--------|----------|------------|------------| | `imageio-native-video-apple` | macOS | AVFoundation (AVAssetImageGenerator) | MP4, MOV, M4V, 3GP | diff --git a/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractor.java b/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractor.java index 1f8ecf2..6722498 100644 --- a/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractor.java +++ b/imageio-native-video-apple/src/main/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractor.java @@ -68,6 +68,17 @@ private static UnsupportedOperationException unavailable() { private static final MethodHandle msgSend_ptr_ptr; /** (id, SEL) → BOOL */ private static final MethodHandle msgSend_ret_bool; + /** (id, SEL) → CGAffineTransform */ + private static final MethodHandle msgSend_ret_transform; + + /** CGAffineTransform: six CGFloat members {@code a, b, c, d, tx, ty}. */ + private static final StructLayout CGAFFINETRANSFORM = MemoryLayout.structLayout( + ValueLayout.JAVA_DOUBLE.withName("a"), + ValueLayout.JAVA_DOUBLE.withName("b"), + ValueLayout.JAVA_DOUBLE.withName("c"), + ValueLayout.JAVA_DOUBLE.withName("d"), + ValueLayout.JAVA_DOUBLE.withName("tx"), + ValueLayout.JAVA_DOUBLE.withName("ty")); static { if (AVAILABLE) { @@ -80,11 +91,14 @@ private static UnsupportedOperationException unavailable() { ValueLayout.ADDRESS, ValueLayout.ADDRESS)); msgSend_ret_bool = CoreFoundation.msgSend(FunctionDescriptor.of(ValueLayout.JAVA_BYTE, ValueLayout.ADDRESS, ValueLayout.ADDRESS)); + msgSend_ret_transform = CoreFoundation.msgSend(FunctionDescriptor.of(CGAFFINETRANSFORM, + ValueLayout.ADDRESS, ValueLayout.ADDRESS)); } else { msgSend = null; msgSend_ptr = null; msgSend_ptr_ptr = null; msgSend_ret_bool = null; + msgSend_ret_transform = null; } } @@ -98,49 +112,84 @@ public boolean isAvailable() { @Override public boolean canDecode(Path videoFile) { if (!AVAILABLE || videoFile == null) return false; + MemorySegment pool = CoreFoundation.autoreleasePoolPush(); + try (Arena arena = Arena.ofConfined()) { + MemorySegment track = playableVideoTrack(arena, videoFile); + return !MemorySegment.NULL.equals(track); + } catch (Throwable ignored) { + return false; + } finally { + CoreFoundation.autoreleasePoolPop(pool); + } + } + /** + * Returns the first video track of a playable asset, or {@code NULL}. + *

+ * The asset, track array, and track are autoreleased Objective-C objects: + * callers must hold an autorelease pool and must not use the track after + * draining it. + */ + private static MemorySegment playableVideoTrack(Arena arena, Path videoFile) + throws Throwable { + String absPath = videoFile.toAbsolutePath().toString(); + MemorySegment cfPath = CoreFoundation.cfStringCreate(arena, absPath); + if (MemorySegment.NULL.equals(cfPath)) return MemorySegment.NULL; + try { + MemorySegment url = + (MemorySegment) msgSend_ptr.invokeExact( + CoreFoundation.objcGetClass(arena, "NSURL"), + CoreFoundation.selRegisterName(arena, "fileURLWithPath:"), + cfPath); + if (MemorySegment.NULL.equals(url)) return MemorySegment.NULL; + MemorySegment asset = + (MemorySegment) msgSend_ptr_ptr.invokeExact( + CoreFoundation.objcGetClass(arena, "AVURLAsset"), + CoreFoundation.selRegisterName(arena, "URLAssetWithURL:options:"), + url, + MemorySegment.NULL); + if (MemorySegment.NULL.equals(asset)) return MemorySegment.NULL; + byte playable = + (byte) msgSend_ret_bool.invokeExact( + asset, CoreFoundation.selRegisterName(arena, "isPlayable")); + if (playable == 0) return MemorySegment.NULL; + MemorySegment tracks = + (MemorySegment) msgSend_ptr.invokeExact( + asset, + CoreFoundation.selRegisterName(arena, "tracksWithMediaType:"), + CoreFoundation.loadConstPtr("AVMediaTypeVideo")); + if (MemorySegment.NULL.equals(tracks)) return MemorySegment.NULL; + return (MemorySegment) msgSend.invokeExact( + tracks, CoreFoundation.selRegisterName(arena, "firstObject")); + } finally { + CoreFoundation.cfRelease(cfPath); + } + } + + /** + * Returns whether the track's preferred transform turns the picture by an + * odd number of quarter turns, so that the displayed frame has the stored + * width and height swapped. The frame generator applies that transform, + * while the track's natural size does not include it. + */ + private static boolean displayTransposed(Path videoFile) { + MemorySegment pool = CoreFoundation.autoreleasePoolPush(); try (Arena arena = Arena.ofConfined()) { - String absPath = videoFile.toAbsolutePath().toString(); - MemorySegment cfPath = CoreFoundation.cfStringCreate(arena, absPath); - if (MemorySegment.NULL.equals(cfPath)) return false; - - try { - MemorySegment url = - (MemorySegment) msgSend_ptr.invokeExact( - CoreFoundation.objcGetClass(arena, "NSURL"), - CoreFoundation.selRegisterName(arena, "fileURLWithPath:"), - cfPath); - if (MemorySegment.NULL.equals(url)) return false; - - MemorySegment asset = - (MemorySegment) msgSend_ptr_ptr.invokeExact( - CoreFoundation.objcGetClass(arena, "AVURLAsset"), - CoreFoundation.selRegisterName(arena, "URLAssetWithURL:options:"), - url, - MemorySegment.NULL); - if (MemorySegment.NULL.equals(asset)) return false; - - byte playable = - (byte) msgSend_ret_bool.invokeExact( - asset, CoreFoundation.selRegisterName(arena, "isPlayable")); - if (playable == 0) return false; - - MemorySegment tracks = - (MemorySegment) msgSend_ptr.invokeExact( - asset, - CoreFoundation.selRegisterName(arena, "tracksWithMediaType:"), - CoreFoundation.loadConstPtr("AVMediaTypeVideo")); - if (MemorySegment.NULL.equals(tracks)) return false; - - MemorySegment firstTrack = - (MemorySegment) msgSend.invokeExact( - tracks, CoreFoundation.selRegisterName(arena, "firstObject")); - return !MemorySegment.NULL.equals(firstTrack); - } finally { - CoreFoundation.cfRelease(cfPath); - } + MemorySegment track = playableVideoTrack(arena, videoFile); + if (MemorySegment.NULL.equals(track)) return false; + MemorySegment transform = + (MemorySegment) msgSend_ret_transform.invokeExact( + (SegmentAllocator) arena, track, + CoreFoundation.selRegisterName(arena, "preferredTransform")); + double a = transform.get(ValueLayout.JAVA_DOUBLE, 0); + double b = transform.get(ValueLayout.JAVA_DOUBLE, 8); + if (a == 0 && b == 0) return false; + long quarterTurns = Math.round(Math.toDegrees(Math.atan2(b, a)) / 90.0); + return (quarterTurns & 1) != 0; } catch (Throwable ignored) { return false; + } finally { + CoreFoundation.autoreleasePoolPop(pool); } } @@ -159,12 +208,18 @@ public BufferedImage extractFrame( // a square box on the longer requested edge never undershoots the // render size, and renderToSize makes the result exact. int maxEdge = renderSize != null ? Math.max(renderSize.width, renderSize.height) : 0; + // The binding creates autoreleased AVFoundation objects. Java threads + // have no autorelease pool, so drain one here; the decoded pixels + // are copied into the arena and do not depend on it. + MemorySegment pool = CoreFoundation.autoreleasePoolPush(); try (Arena arena = Arena.ofConfined()) { DecodedImage frame = AVFoundation.extractFrame( arena, videoFile.toAbsolutePath().toString(), time.toMillis(), maxEdge); return ImageReadParamSupport.renderToSize(toBufferedImage(frame), renderSize); } catch (RuntimeException e) { throw new IOException("Video frame extraction failed for time " + time, e); + } finally { + CoreFoundation.autoreleasePoolPop(pool); } } @@ -177,12 +232,19 @@ public boolean supportsRenderSizeReduction() { public VideoInfo getInfo(Path videoFile) throws IOException { if (!AVAILABLE) throw unavailable(); + MemorySegment pool = CoreFoundation.autoreleasePoolPush(); try (Arena arena = Arena.ofConfined()) { var info = AVFoundation.getVideoInfo(arena, videoFile.toAbsolutePath().toString()); - return new VideoInfo(info.width(), info.height(), + // Report the displayed size, which is what extractFrame returns. + boolean transposed = displayTransposed(videoFile); + return new VideoInfo( + transposed ? info.height() : info.width(), + transposed ? info.width() : info.height(), Duration.ofMillis(info.durationMillis()), null, info.frameRate()); } catch (RuntimeException e) { throw new IOException("Video info extraction failed", e); + } finally { + CoreFoundation.autoreleasePoolPop(pool); } } diff --git a/imageio-native-video-apple/src/test/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractorTest.java b/imageio-native-video-apple/src/test/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractorTest.java index 04f4497..1e63d7a 100644 --- a/imageio-native-video-apple/src/test/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractorTest.java +++ b/imageio-native-video-apple/src/test/java/io/github/ghosthack/imageio/video/apple/AppleVideoFrameExtractorTest.java @@ -56,6 +56,35 @@ private Path extractResource(String name) throws IOException { return target; } + // ── Display rotation ──────────────────────────────────────────────── + // test-video-rotated.mp4 is stored 32x16 (Red | Blue) with a display + // matrix that turns it 90° clockwise: displayed 16x32, Red over Blue. + + @Test + void rotatedVideoReportsTheDisplayedSize() throws IOException { + AppleVideoFrameExtractor extractor = new AppleVideoFrameExtractor(); + Path video = extractResource("test-video-rotated.mp4"); + + var info = extractor.getInfo(video); + BufferedImage frame = extractor.extractFrame(video, Duration.ZERO); + + assertEquals(16, info.width()); + assertEquals(32, info.height()); + assertEquals(info.width(), frame.getWidth()); + assertEquals(info.height(), frame.getHeight()); + TestPixels.assertColourClose("top (red)", RED, frame.getRGB(8, 4), TOLERANCE); + TestPixels.assertColourClose("bottom (blue)", BLUE, frame.getRGB(8, 27), TOLERANCE); + } + + @Test + void uprightVideoSizeIsUnchanged() throws IOException { + AppleVideoFrameExtractor extractor = new AppleVideoFrameExtractor(); + var info = extractor.getInfo(extractResource("test-video-3s.mp4")); + + assertEquals(16, info.width()); + assertEquals(16, info.height()); + } + private Path testVideo() throws IOException { return extractResource("test-video-3s.mp4"); } diff --git a/imageio-native-video-common/src/test/resources/test-video-long-gop.mp4 b/imageio-native-video-common/src/test/resources/test-video-long-gop.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a07e7d4a37aa844e14f0036e58e821913a81250b GIT binary patch literal 1913 zcma)6J!~9B6rQu=fK4PKC4dVP1`!ZN?!3EapAW+-HcrSDAfPAqN9LNAi3bDa6^#-ODT*Zp+Etmg~EJqZ`U@Kkr?gF`{upx{mi_% zV~p{(?k9d4hm4Iel9-m*aLh27GZ`BnhH<>X7z@G;&xJfT#-A|u%mY?p^c{_VZJ<7} zUpiu*hQ?6GcUp-Kj34SwmUH|VF^`74C&!6Ar{+BmCz_01maa}AXJnA-Op{fb$IW7m z*`ezT*m&rkJp1cV_t*#DW}aow4OAY3ZTPM%Fv(lk#|;s=fh11pN$5vyfQuVp7W8=8 zm)((V##NFyG{}B#T?KrEOZQXV3V;@oB8l~sn1;1uh zta`;XEFSo+o>iM08MAfz-~h4$)=KH^ovDML+4F0VdzW^u;aRXVwA_5F@hLB{32*nK zT@Lp7M5GBM<)?YErB!~plRsilV>;E@#SH;>@MUa=2R{TpEh6k5B*8*|K*`}Cq_&fsC|4FvbFAN0eL%=nIzlG#~%tFml8=r zy*wOcfAkt({Y=Lc@I_Z-&U7IR9c!awCO*T${^_=ocxvNchG60J-Ln%12jQdZzkc(} zUgN8KSAODqul)W8wUw8-6D!Hh+B{cP%d&W@I$ty91q_V}2($0qyndrR$Cq!dfayvH zhLt$!2ePfXWf;}6Wmxl2dRixov$LC#6kX54P4Qrl&VYfr(00tIp05gse_WFKa`inEVk6MrDK zIdAgRk&$%PDOeVOZbiw|!(KVf!;0-W+S`t5^ANvBNtIz^Th)reyHt;DRBC_;1?pKrGQk3#lP&fJb;ie)93Ne@<_+*Z!ViXA)F5f~I;y8t@{*w4X`y*VNe`2v9p%fqFskGo6k+81>;`TY;9 z)OeHy8?F`}g92<9V5b24IoM(a;00L9^K7l=dA0^wp4;!#+0@rJSn1r%sOas&W2XT7 WIT*46@B%CqV6^~);yl|65B~v98k$4^ literal 0 HcmV?d00001 diff --git a/imageio-native-video-common/src/test/resources/test-video-rotated.mp4 b/imageio-native-video-common/src/test/resources/test-video-rotated.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..02d1069039292c9cb9350b2befb6911bd064a641 GIT binary patch literal 2700 zcmeHH&x;&I6t0;uA;g75*}xuFt;8sM*y-u+ogK$z8=`B>9u&M7B#4vh?waj(`qx&~ z%+BPrNRTCp2!bc?;z5WP1O9+L2;RI1l0cBvgT#xHzhM1d&y2gq+&#F(RK2g>``%Yo zud0VJ#=B-z#5zwIt1`0at{4PPS~MNTYVW3bK46R`=^zSW54GAo#P6{Rqu)XM#{}*N z<`)i_4?|V#Gn{V;9K9(N7a#=VfR#?7U30DLv&* zC%UChbs-I7ff!H22hY9=_bPk+yE3yLg^8MIut6NkDJFXv^L$-oVIqlB`7w>NF2L*{ zEk!3=CMr80j$`wolEk4#@tM9#_!w6{(#B7KZ)u~a7ebs*>C#}S9o8IsIF7vzNS#{c z%q!rxT+3}+j_vX!_J?k(IS!WNTv^0ASZkFRcTevB!p>~K-u=3Q0@kRCwc76ebHfTd z7X5H)aT`ge3!w{GTAuo>Z`7o=t(%NdXLH(=bq6dtPtvc@Ipn(U13kwJJwg)3jtV`;vXO*=r}0pR9a03A9VN02 z={YSPL@G~32dNG>N+wCHf!f1%7#L84%@kuOMR+aGq~|(|Sg|X#=@hyb7obiAHj7T) z?P_Vfy30+ZkU>I8p7%tAN$0?)lQ_U$rVg8Ds$3(8Q(Ik|KFk#AmJU?<=Eo>dlZ@3F?`kKJI^8_q6!+ikO%5BJ8bcPgjIfBlPHcIl@! zd-TLh{x * Implements the full decode pipeline: open → find stream → seek → decode → * pixel format conversion → {@link BufferedImage}. + *

+ * Frames are returned as displayed: the stream's display matrix (the rotation + * phones record for portrait video) is applied, and {@link #getInfo} reports + * the displayed size. A seek decodes forward from the preceding keyframe to + * the first frame at or after the requested time. */ public class FFmpegVideoFrameExtractor implements VideoFrameExtractorProvider { private static final int EXPECTED_AVFORMAT_MAJOR = 62; // FFmpeg 8.x private static final int AVSEEK_FLAG_BACKWARD = 1; + + /** {@code AV_PKT_DATA_DISPLAYMATRIX}: nine 16.16 fixed-point int32 values. */ + private static final int AV_PKT_DATA_DISPLAYMATRIX = 5; + /** + * {@code AVPacketSideData} is {@code { uint8_t *data; size_t size; enum type; }}. + * The bindings expose only the array pointer, so entries are read by offset. + */ + private static final long SIDE_DATA_ENTRY_BYTES = 24; + private static final long SIDE_DATA_SIZE_OFFSET = 8; + private static final long SIDE_DATA_TYPE_OFFSET = 16; private static final int AVERROR_EAGAIN = isMac() ? -35 : -11; private static final boolean AVAILABLE = detectAvailability(); @@ -162,6 +177,7 @@ public BufferedImage extractFrame( .reinterpret(AVFormatContext.layout().byteSize()); MemorySegment ppCodecCtx = arena.allocate(ValueLayout.ADDRESS); MemorySegment ppFrame = arena.allocate(ValueLayout.ADDRESS); + MemorySegment ppNextFrame = arena.allocate(ValueLayout.ADDRESS); MemorySegment ppPacket = arena.allocate(ValueLayout.ADDRESS); MemorySegment swsCtx = MemorySegment.NULL; @@ -199,6 +215,7 @@ public BufferedImage extractFrame( throw new IOException("av_frame_alloc failed"); frame = frame.reinterpret(AVFrame.layout().byteSize()); ppFrame.set(ValueLayout.ADDRESS, 0, frame); + int quarterTurns = displayQuarterTurns(codecpar); MemorySegment packet = FFmpeg.av_packet_alloc(); if (MemorySegment.NULL.equals(packet)) @@ -206,34 +223,61 @@ public BufferedImage extractFrame( packet = packet.reinterpret(AVPacket.layout().byteSize()); ppPacket.set(ValueLayout.ADDRESS, 0, packet); + long targetTs = FFmpeg.AV_NOPTS_VALUE(); if (!time.isZero()) { MemorySegment timeBase = AVStream.time_base(stream); int tbNum = AVRational.num(timeBase); int tbDen = AVRational.den(timeBase); if (tbNum > 0 && tbDen > 0) { long targetMicros = time.toNanos() / 1_000; - long targetTs = Math.multiplyExact(targetMicros, tbDen) + targetTs = Math.multiplyExact(targetMicros, tbDen) / ((long) tbNum * FFmpeg.AV_TIME_BASE()); + long startTime = AVStream.start_time(stream); + if (startTime != FFmpeg.AV_NOPTS_VALUE()) { + targetTs += startTime; + } check(FFmpeg.av_seek_frame( fmtCtx, streamIdx, targetTs, AVSEEK_FLAG_BACKWARD), "av_seek_frame"); } } - boolean gotFrame = decodeFrame(fmtCtx, codecCtx, frame, packet, streamIdx); - if (!gotFrame) + boolean[] drained = {false}; + if (!receiveFrame(fmtCtx, codecCtx, frame, packet, streamIdx, drained)) throw new IOException("Failed to decode any frame from " + videoFile); + // The seek lands on the keyframe at or before the target. + // Decode forward to the first frame at or after it; if the + // stream ends first, keep the last frame that decoded. + if (targetTs != FFmpeg.AV_NOPTS_VALUE() + && precedes(frame, targetTs)) { + MemorySegment next = FFmpeg.av_frame_alloc(); + if (MemorySegment.NULL.equals(next)) + throw new IOException("av_frame_alloc failed"); + next = next.reinterpret(AVFrame.layout().byteSize()); + ppNextFrame.set(ValueLayout.ADDRESS, 0, next); + while (precedes(frame, targetTs) + && receiveFrame(fmtCtx, codecCtx, next, packet, streamIdx, drained)) { + MemorySegment previous = frame; + frame = next; + next = previous; + FFmpeg.av_frame_unref(next); + } + } + int width = AVFrame.width(frame); int height = AVFrame.height(frame); int frameFormat = AVFrame.format(frame); if (width <= 0 || height <= 0) throw new IOException("Invalid frame dimensions: " + width + "x" + height); - int outputWidth = - renderSize != null ? renderSize.width : width; - int outputHeight = - renderSize != null ? renderSize.height : height; + // The render size describes the displayed frame; scale in + // the stored orientation and rotate afterwards. + boolean transposed = (quarterTurns & 1) != 0; + int outputWidth = renderSize == null ? width + : transposed ? renderSize.height : renderSize.width; + int outputHeight = renderSize == null ? height + : transposed ? renderSize.width : renderSize.height; swsCtx = FFmpeg.sws_getContext( width, height, frameFormat, outputWidth, outputHeight, FFmpeg.AV_PIX_FMT_BGRA(), @@ -272,10 +316,12 @@ public BufferedImage extractFrame( int a = dstBuf.get(ValueLayout.JAVA_BYTE, offset + 3) & 0xFF; dest[i] = (a << 24) | (r << 16) | (g << 8) | b; } - return result; + return rotateClockwise(result, quarterTurns); } finally { if (!MemorySegment.NULL.equals(swsCtx)) FFmpeg.sws_freeContext(swsCtx); + if (ppNextFrame.get(ValueLayout.ADDRESS, 0).address() != 0) + FFmpeg.av_frame_free(ppNextFrame); if (ppPacket.get(ValueLayout.ADDRESS, 0).address() != 0) FFmpeg.av_packet_free(ppPacket); if (ppFrame.get(ValueLayout.ADDRESS, 0).address() != 0) @@ -331,8 +377,11 @@ public VideoInfo getInfo(Path videoFile) throws IOException { MemorySegment codecpar = AVStream.codecpar(stream) .reinterpret(AVCodecParameters.layout().byteSize()); - int width = AVCodecParameters.width(codecpar); - int height = AVCodecParameters.height(codecpar); + boolean transposed = (displayQuarterTurns(codecpar) & 1) != 0; + int storedWidth = AVCodecParameters.width(codecpar); + int storedHeight = AVCodecParameters.height(codecpar); + int width = transposed ? storedHeight : storedWidth; + int height = transposed ? storedWidth : storedHeight; int codecId = AVCodecParameters.codec_id(codecpar); MemorySegment frameRate = AVStream.r_frame_rate(stream); @@ -356,27 +405,40 @@ public VideoInfo getInfo(Path videoFile) throws IOException { } } - private static boolean decodeFrame( + /** + * Receives the next decoded frame of the selected stream, feeding the + * decoder packets as it asks for them. + * + * @param drained single-element flag recording that the demuxer reached + * the end and the decoder has been flushed + * @return {@code false} once the decoder has no more frames + */ + private static boolean receiveFrame( MemorySegment fmtCtx, MemorySegment codecCtx, MemorySegment frame, MemorySegment packet, - int streamIdx) throws IOException { + int streamIdx, + boolean[] drained) throws IOException { while (true) { - int readResult = FFmpeg.av_read_frame(fmtCtx, packet); - if (readResult < 0) { + int receiveResult = FFmpeg.avcodec_receive_frame(codecCtx, frame); + if (receiveResult == 0) return true; + if (receiveResult == FFmpeg.AVERROR_EOF()) return false; + if (receiveResult != AVERROR_EAGAIN) + throw new IOException("avcodec_receive_frame failed: " + receiveResult); + if (drained[0]) return false; + + if (FFmpeg.av_read_frame(fmtCtx, packet) < 0) { int sendResult = FFmpeg.avcodec_send_packet(codecCtx, MemorySegment.NULL); if (sendResult < 0 && sendResult != FFmpeg.AVERROR_EOF()) throw new IOException("avcodec_send_packet flush failed: " + sendResult); - int receiveResult = FFmpeg.avcodec_receive_frame(codecCtx, frame); - return receiveResult == 0; + drained[0] = true; + continue; } - if (AVPacket.stream_index(packet) != streamIdx) { FFmpeg.av_packet_unref(packet); continue; } - int sendResult; try { sendResult = FFmpeg.avcodec_send_packet(codecCtx, packet); @@ -385,12 +447,77 @@ private static boolean decodeFrame( } if (sendResult < 0) throw new IOException("avcodec_send_packet failed: " + sendResult); + } + } - int receiveResult = FFmpeg.avcodec_receive_frame(codecCtx, frame); - if (receiveResult == 0) return true; - if (receiveResult != AVERROR_EAGAIN && receiveResult != FFmpeg.AVERROR_EOF()) - throw new IOException("avcodec_receive_frame failed: " + receiveResult); + /** Returns whether a frame is presented strictly before the target. */ + private static boolean precedes(MemorySegment frame, long targetTs) { + long pts = AVFrame.pts(frame); + return pts != FFmpeg.AV_NOPTS_VALUE() && pts < targetTs; + } + + /** + * Returns the clockwise quarter turns (0-3) the stream's display matrix + * asks for, or 0 when the stream has none. + *

+ * Mirrors {@code av_display_rotation_get}, whose result is the + * counter-clockwise angle; players rotate the picture by its negation. + */ + private static int displayQuarterTurns(MemorySegment codecpar) { + int count = AVCodecParameters.nb_coded_side_data(codecpar); + MemorySegment entries = AVCodecParameters.coded_side_data(codecpar); + if (count <= 0 || MemorySegment.NULL.equals(entries)) return 0; + entries = entries.reinterpret(count * SIDE_DATA_ENTRY_BYTES); + for (int i = 0; i < count; i++) { + long entry = i * SIDE_DATA_ENTRY_BYTES; + int type = entries.get( + ValueLayout.JAVA_INT, entry + SIDE_DATA_TYPE_OFFSET); + long size = entries.get( + ValueLayout.JAVA_LONG, entry + SIDE_DATA_SIZE_OFFSET); + if (type != AV_PKT_DATA_DISPLAYMATRIX || size < 9 * 4) continue; + MemorySegment matrix = entries.get(ValueLayout.ADDRESS, entry) + .reinterpret(9 * 4); + double m0 = matrix.getAtIndex(ValueLayout.JAVA_INT, 0) / 65536.0; + double m1 = matrix.getAtIndex(ValueLayout.JAVA_INT, 1) / 65536.0; + double m3 = matrix.getAtIndex(ValueLayout.JAVA_INT, 3) / 65536.0; + double m4 = matrix.getAtIndex(ValueLayout.JAVA_INT, 4) / 65536.0; + double scaleX = Math.hypot(m0, m3); + double scaleY = Math.hypot(m1, m4); + if (scaleX == 0 || scaleY == 0) return 0; + double clockwiseDegrees = + Math.toDegrees(Math.atan2(m1 / scaleY, m0 / scaleX)); + long turns = Math.round(clockwiseDegrees / 90.0); + return (int) (((turns % 4) + 4) % 4); + } + return 0; + } + + /** Rotates an image clockwise by the given number of quarter turns. */ + private static BufferedImage rotateClockwise( + BufferedImage source, int quarterTurns) { + if (quarterTurns == 0) return source; + int w = source.getWidth(); + int h = source.getHeight(); + boolean transposed = (quarterTurns & 1) != 0; + int outW = transposed ? h : w; + int outH = transposed ? w : h; + BufferedImage result = new BufferedImage( + outW, outH, BufferedImage.TYPE_INT_ARGB_PRE); + int[] src = ((DataBufferInt) source.getRaster().getDataBuffer()).getData(); + int[] dst = ((DataBufferInt) result.getRaster().getDataBuffer()).getData(); + for (int y = 0; y < outH; y++) { + for (int x = 0; x < outW; x++) { + int sx; + int sy; + switch (quarterTurns) { + case 1 -> { sx = y; sy = h - 1 - x; } + case 2 -> { sx = w - 1 - x; sy = h - 1 - y; } + default -> { sx = w - 1 - y; sy = x; } + } + dst[y * outW + x] = src[sy * w + sx]; + } } + return result; } private static void check(int result, String operation) throws IOException { diff --git a/imageio-native-video-ffmpeg/src/test/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractorTest.java b/imageio-native-video-ffmpeg/src/test/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractorTest.java index e257a71..e87e984 100644 --- a/imageio-native-video-ffmpeg/src/test/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractorTest.java +++ b/imageio-native-video-ffmpeg/src/test/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractorTest.java @@ -144,6 +144,77 @@ void getInfoFromBframeVideo() throws Exception { assertEquals("h264", info.codec()); } + // ── Display rotation ──────────────────────────────────────────────── + // test-video-rotated.mp4 is stored 32x16 (Red | Blue) with a display + // matrix that turns it 90° clockwise: displayed 16x32, Red over Blue. + + @Test + void rotatedVideoReportsAndReturnsTheDisplayedFrame() throws Exception { + assumeFFmpeg(); + Path video = extractResource("test-video-rotated.mp4"); + + VideoInfo info = extractor.getInfo(video); + BufferedImage frame = extractor.extractFrame(video, Duration.ZERO); + + assertEquals(16, info.width()); + assertEquals(32, info.height()); + assertEquals(info.width(), frame.getWidth()); + assertEquals(info.height(), frame.getHeight()); + assertDominantColorAt(frame, 8, 4, 0, "red"); + assertDominantColorAt(frame, 8, 27, 2, "blue"); + } + + @Test + void rotatedVideoRenderSizeDescribesTheDisplayedFrame() throws Exception { + assumeFFmpeg(); + BufferedImage frame = extractor.extractFrame( + extractResource("test-video-rotated.mp4"), + Duration.ZERO, + new Dimension(8, 16)); + + assertEquals(8, frame.getWidth()); + assertEquals(16, frame.getHeight()); + assertDominantColorAt(frame, 4, 2, 0, "red"); + assertDominantColorAt(frame, 4, 13, 2, "blue"); + } + + // ── Seek accuracy ─────────────────────────────────────────────────── + // test-video-long-gop.mp4 has a single keyframe at t=0 and changes + // colour every second: Red, Green, Blue. + + @Test + void seekDecodesForwardFromTheKeyframeToTheRequestedTime() throws Exception { + assumeFFmpeg(); + Path video = extractResource("test-video-long-gop.mp4"); + + assertDominantColor( + extractor.extractFrame(video, Duration.ofMillis(500)), 0, "red"); + assertDominantColor( + extractor.extractFrame(video, Duration.ofMillis(1500)), 1, "green"); + assertDominantColor( + extractor.extractFrame(video, Duration.ofMillis(2500)), 2, "blue"); + } + + @Test + void seekPastTheEndReturnsTheLastFrame() throws Exception { + assumeFFmpeg(); + BufferedImage frame = extractor.extractFrame( + extractResource("test-video-long-gop.mp4"), Duration.ofSeconds(30)); + + assertDominantColor(frame, 2, "blue"); + } + + private static void assertDominantColorAt( + BufferedImage frame, int x, int y, int channel, String name) { + int argb = frame.getRGB(x, y); + int[] channels = {(argb >>> 16) & 0xFF, (argb >>> 8) & 0xFF, argb & 0xFF}; + assertTrue(channels[channel] > 200, + "Expected dominant " + name + " at " + x + "," + y + + " but got 0x" + Integer.toHexString(argb)); + assertTrue(channels[(channel + 1) % 3] < 80); + assertTrue(channels[(channel + 2) % 3] < 80); + } + private static void assertDominantColor(BufferedImage frame, int channel, String name) { int argb = frame.getRGB(frame.getWidth() / 2, frame.getHeight() / 2); int[] channels = {(argb >>> 16) & 0xFF, (argb >>> 8) & 0xFF, argb & 0xFF}; diff --git a/scripts/generate-video-long-gop.sh b/scripts/generate-video-long-gop.sh new file mode 100755 index 0000000..67c5a29 --- /dev/null +++ b/scripts/generate-video-long-gop.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# +# Generates the long-GOP video test fixture used to verify that a seek +# returns the frame at the requested time rather than the preceding keyframe. +# +# Requires: ffmpeg with libx264 +# +# Output: 16x16, 3 seconds @ 10fps, H.264 baseline, ONE keyframe (at t=0). +# 0s-1s: Solid Red, 1s-2s: Solid Green, 2s-3s: Solid Blue +# +# A backend that stops at the keyframe returns Red for every requested time. +# +set -euo pipefail + +OUT="imageio-native-video-common/src/test/resources/test-video-long-gop.mp4" + +ffmpeg -y -loglevel error \ + -f lavfi -i "color=c=red:size=16x16:rate=10:d=1" \ + -f lavfi -i "color=c=lime:size=16x16:rate=10:d=1" \ + -f lavfi -i "color=c=blue:size=16x16:rate=10:d=1" \ + -filter_complex "[0:v][1:v][2:v]concat=n=3:v=1:a=0" \ + -c:v libx264 -profile:v baseline -g 300 -keyint_min 300 -sc_threshold 0 \ + -pix_fmt yuv420p -movflags +faststart \ + "$OUT" + +echo "Generated: $OUT ($(wc -c < "$OUT" | tr -d ' ') bytes)" +echo "Verify: ffprobe -v quiet -select_streams v -show_entries frame=pict_type,pts_time -of compact $OUT" diff --git a/scripts/generate-video-rotated.sh b/scripts/generate-video-rotated.sh new file mode 100755 index 0000000..e71fc08 --- /dev/null +++ b/scripts/generate-video-rotated.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# +# Generates the rotated (portrait) video test fixture. +# +# Requires: ffmpeg with libx264 +# +# Output: stored 32x16, 1 second @ 30fps, H.264, with a display matrix that +# rotates the picture 90 degrees clockwise for display (ffprobe reports +# rotation=-90, the same metadata phones write for portrait recordings). +# +# Stored frame (32x16): Red | Blue +# Displayed frame (16x32): Red on top, Blue on the bottom +# +# Backends must report 16x32 and return the displayed frame. +# +set -euo pipefail + +OUT="imageio-native-video-common/src/test/resources/test-video-rotated.mp4" +TMP="$(mktemp -t rotated-src).mp4" +trap 'rm -f "$TMP"' EXIT + +ffmpeg -y -loglevel error \ + -f lavfi -i "color=c=red:size=16x16:rate=30:d=1" \ + -f lavfi -i "color=c=blue:size=16x16:rate=30:d=1" \ + -filter_complex "[0:v][1:v]hstack=inputs=2" \ + -c:v libx264 -profile:v baseline -g 1 -pix_fmt yuv420p \ + -movflags +faststart \ + "$TMP" + +ffmpeg -y -loglevel error \ + -display_rotation -90 -i "$TMP" \ + -c copy -movflags +faststart \ + "$OUT" + +echo "Generated: $OUT ($(wc -c < "$OUT" | tr -d ' ') bytes)" +echo "Verify: ffprobe -v quiet -show_entries stream=width,height:stream_side_data=rotation -of compact $OUT" From 0fb2a7096314e8a5d8ebfeb52ed1a69994447fae Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:59:00 -0800 Subject: [PATCH 5/7] Tighten format detection and share decode limits TIFF-based RAW formats were recognised by searching the first 4 KB for "DNG", "Nikon", or "SONY", case-insensitively. A plain TIFF exported from a camera JPEG, or one whose text happened to contain those letters, was classified as RAW and bypassed any routing preference for TIFF. Read the first IFD instead: DNG by its version tag, NEF and ARW only when the make matches and the first IFD is a preview of sub-IFD data. Let a codec brand win over the generic HEIF brands so an AVIF or HEIC file with a mif1 major brand keeps its codec's format, and share one still-image brand list with video detection so Canon CR3 and JPEG XL are no longer offered to video backends. Audio-only MP4 is skipped. Read imageio.native.maxPixels in one place. libvips previously hard-coded the limit, and the video reader kept its own copy of the intermediate-size limit. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- README.md | 5 + .../ghosthack/imageio/apple/AppleNative.java | 19 +-- .../imageio/common/FormatDetector.java | 123 +++++++++++++++--- .../imageio/common/NativeLimits.java | 47 +++++++ .../imageio/common/FormatDetectorTest.java | 98 ++++++++++++++ .../imageio/common/NativeLimitsTest.java | 43 ++++++ .../imageio/video/NativeVideoReader.java | 13 +- .../imageio/video/VideoFormatDetector.java | 32 ++--- .../video/VideoFormatDetectorTest.java | 11 ++ .../ghosthack/imageio/vips/VipsNative.java | 8 +- 10 files changed, 332 insertions(+), 67 deletions(-) create mode 100644 imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/NativeLimits.java create mode 100644 imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/NativeLimitsTest.java diff --git a/README.md b/README.md index f368624..9e74e3d 100644 --- a/README.md +++ b/README.md @@ -535,6 +535,11 @@ processing and the worst-case thumbnail surfaces used for exact Apple/WIC render sizes. Override the limit in bytes with `-Dimageio.native.maxIntermediateBytes=`. +Independently of read parameters, the Apple and libvips backends refuse to +decode an image larger than 256 megapixels, which guards against corrupt or +hostile files that declare huge dimensions. Override the limit with +`-Dimageio.native.maxPixels=`. + ### EXIF orientation Images from phones and cameras often carry an EXIF orientation tag (values 1-8) that describes how the sensor image should be rotated or flipped for correct display. Every still-image backend applies this transform automatically during decode, so the returned `BufferedImage` is display-ready and the same input has the same orientation whichever backend owns it. diff --git a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleNative.java b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleNative.java index e0cc847..f3bbd12 100644 --- a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleNative.java +++ b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/AppleNative.java @@ -1,6 +1,7 @@ package io.github.ghosthack.imageio.apple; import io.github.ghosthack.imageio.common.ImageReadParamSupport; +import io.github.ghosthack.imageio.common.NativeLimits; import io.github.ghosthack.panama.media.cgimage.CGImageSource; import io.github.ghosthack.panama.media.corefoundation.CoreFoundation; @@ -51,12 +52,6 @@ static String unavailableMessage(String offMacMessage) { : offMacMessage; } - /** - * Maximum number of pixels (width * height) we are willing to decode. - * Prevents OOM on malicious/corrupt images declaring huge dimensions. - * Default: 256 megapixels (e.g. 16384 x 16384). - */ - static final long MAX_PIXELS = Long.getLong("imageio.native.maxPixels", 256L * 1024 * 1024); // ── Helper: read an int property from a CFDictionary ──────────────── @@ -156,13 +151,11 @@ private static BufferedImage decodeFromSource( if (rawW <= 0 || rawH <= 0) throw new javax.imageio.IIOException("Invalid image dimensions: " + rawW + "x" + rawH); - long decodedPixels = renderSize != null - ? (long) renderSize.width * renderSize.height - : (long) rawW * rawH; - if (decodedPixels > MAX_PIXELS) - throw new javax.imageio.IIOException( - "Decoded image too large: " + decodedPixels - + " pixels exceeds limit of " + MAX_PIXELS); + if (renderSize != null) { + NativeLimits.requireDecodable(renderSize.width, renderSize.height); + } else { + NativeLimits.requireDecodable(rawW, rawH); + } int maxDim = renderSize != null ? Math.max(renderSize.width, renderSize.height) diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java index ca1d7c8..ced82fd 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java @@ -147,45 +147,132 @@ && containsAscii(h, Math.min(len, 512), "_width")) return null; } + // ── ISO BMFF brands ───────────────────────────────────────────────── + + private static final Set HEIC_BRANDS = Set.of( + "heic", "heix", "heim", "heis", "hevc", "hevx", "hevm", "hevs"); + private static final Set HEIF_BRANDS = Set.of("mif1", "mif2"); + private static final Set AVIF_BRANDS = Set.of("avif", "avis"); + private static final Set JPEG2000_BRANDS = Set.of("jp2 ", "jpx ", "jpm "); + private static final Set JXL_BRANDS = Set.of("jxl "); + private static final Set CR3_BRANDS = Set.of("crx ", "cr3 "); + + /** + * Returns whether an ISO BMFF {@code ftyp} brand identifies a still-image + * container (HEIF family, AVIF, JPEG 2000, JPEG XL, Canon CR3). + *

+ * Video detection uses this to leave image containers to the still-image + * router, so both routers share one list. + * + * @param brand four-character brand code, including trailing spaces + */ + public static boolean isStillImageBrand(String brand) { + return specificIsoBmffFormat(brand) != null + || HEIF_BRANDS.contains(brand); + } + + private static String specificIsoBmffFormat(String brand) { + if (HEIC_BRANDS.contains(brand)) return "heic"; + if (AVIF_BRANDS.contains(brand)) return "avif"; + if (JPEG2000_BRANDS.contains(brand)) return "jpeg2000"; + if (JXL_BRANDS.contains(brand)) return "jxl"; + if (CR3_BRANDS.contains(brand)) return "cr3"; + return null; + } + + /** + * Classifies an {@code ftyp} box from its major and compatible brands. + * A codec-specific brand anywhere in the box wins over the generic HEIF + * structural brands, so an AVIF or HEIC file whose major brand is + * {@code mif1} is still reported by its codec. + */ private static String detectIsoBmff(byte[] h, int len) { int boxSize = ((h[0] & 0xFF) << 24) | ((h[1] & 0xFF) << 16) | ((h[2] & 0xFF) << 8) | (h[3] & 0xFF); int limit = boxSize == 0 ? len : Math.min(boxSize, len); + boolean genericHeif = false; + // Major brand at 8, then compatible brands after the minor version. for (int off = 8; off + 4 <= limit; off += off == 8 ? 8 : 4) { String brand = new String(h, off, 4, StandardCharsets.US_ASCII); - if (Set.of("heic", "heix", "heim", "heis", "hevc", "hevx", - "hevm", "hevs").contains(brand)) return "heic"; - if (Set.of("mif1", "mif2").contains(brand)) return "heif"; - if (Set.of("avif", "avis").contains(brand)) return "avif"; - if (Set.of("jp2 ", "jpx ", "jpm ").contains(brand)) return "jpeg2000"; - if ("jxl ".equals(brand)) return "jxl"; - if (Set.of("crx ", "cr3 ").contains(brand)) return "cr3"; + String format = specificIsoBmffFormat(brand); + if (format != null) return format; + genericHeif |= HEIF_BRANDS.contains(brand); } - return null; + return genericHeif ? "heif" : null; } + // ── TIFF family ───────────────────────────────────────────────────── + + private static final int TIFF_TAG_NEW_SUBFILE_TYPE = 0x00FE; + private static final int TIFF_TAG_MAKE = 0x010F; + private static final int TIFF_TAG_SUB_IFDS = 0x014A; + private static final int TIFF_TAG_DNG_VERSION = 0xC612; + + /** + * Separates TIFF-based camera RAW from plain TIFF using the first IFD. + *

+ * A camera make alone is not enough: a TIFF exported from a camera JPEG + * keeps the make. NEF and ARW are recognised only when the first IFD is + * also a reduced-resolution preview that points at sub-IFDs holding the + * sensor data. Anything else is reported as plain TIFF; a backend that + * can decode the RAW payload still claims it through its own probe. + */ private static String detectTiffFamily(byte[] h, int len) { if (len >= 12 && h[8] == 'C' && h[9] == 'R' && u(h[10]) == 2 && h[11] == 0) return "cr2"; - if (containsTiffTag(h, len, 0xC612)) return "dng"; - int scan = Math.min(len, 4096); - if (containsAscii(h, scan, "DNG")) return "dng"; - if (containsAscii(h, scan, "Nikon")) return "nef"; - if (containsAscii(h, scan, "SONY")) return "arw"; + if (findTiffEntry(h, len, TIFF_TAG_DNG_VERSION) >= 0) return "dng"; + + String make = tiffAscii(h, len, TIFF_TAG_MAKE); + if (make != null && firstIfdIsRawPreview(h, len)) { + String upper = make.toUpperCase(java.util.Locale.ROOT); + if (upper.startsWith("NIKON")) return "nef"; + if (upper.startsWith("SONY")) return "arw"; + } return "tiff"; } - private static boolean containsTiffTag(byte[] h, int len, int wantedTag) { - if (len < 8) return false; + private static boolean firstIfdIsRawPreview(byte[] h, int len) { + if (findTiffEntry(h, len, TIFF_TAG_SUB_IFDS) < 0) return false; + int entry = findTiffEntry(h, len, TIFF_TAG_NEW_SUBFILE_TYPE); + if (entry < 0) return false; + boolean little = h[0] == 'I'; + int type = unsignedShort(h, entry + 2, little); + long value = type == 3 + ? unsignedShort(h, entry + 8, little) + : unsignedInt(h, entry + 8, little); + return (value & 1) != 0; + } + + /** Reads an ASCII tag of the first IFD when its value lies in the prefix. */ + private static String tiffAscii(byte[] h, int len, int tag) { + int entry = findTiffEntry(h, len, tag); + if (entry < 0) return null; + boolean little = h[0] == 'I'; + if (unsignedShort(h, entry + 2, little) != 2) return null; + long count = unsignedInt(h, entry + 4, little); + if (count <= 0 || count > 256) return null; + long start = count <= 4 ? entry + 8 : unsignedInt(h, entry + 8, little); + if (start < 0 || start + count > len) return null; + int length = (int) count; + while (length > 0 && h[(int) start + length - 1] == 0) length--; + return new String(h, (int) start, length, StandardCharsets.US_ASCII); + } + + /** + * Returns the offset of a tag's 12-byte entry in the first IFD, or -1 when + * the tag is absent or the entry lies beyond the prefix. + */ + private static int findTiffEntry(byte[] h, int len, int wantedTag) { + if (len < 8) return -1; boolean little = h[0] == 'I'; long offset = unsignedInt(h, 4, little); - if (offset < 0 || offset + 2 > len) return false; + if (offset < 0 || offset + 2 > len) return -1; int entries = unsignedShort(h, (int) offset, little); int position = (int) offset + 2; for (int i = 0; i < entries && position + 12 <= len; i++, position += 12) { - if (unsignedShort(h, position, little) == wantedTag) return true; + if (unsignedShort(h, position, little) == wantedTag) return position; } - return false; + return -1; } private static int unsignedShort(byte[] h, int offset, boolean little) { diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/NativeLimits.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/NativeLimits.java new file mode 100644 index 0000000..df718b6 --- /dev/null +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/NativeLimits.java @@ -0,0 +1,47 @@ +package io.github.ghosthack.imageio.common; + +import javax.imageio.IIOException; + +/** + * Decode limits shared by every backend, so one setting bounds a decode + * whichever backend owns the input. + */ +public final class NativeLimits { + + /** System property holding the maximum decoded pixel count. */ + public static final String MAX_PIXELS_PROPERTY = "imageio.native.maxPixels"; + + /** Default limit: 256 megapixels, for example 16384 x 16384. */ + public static final long DEFAULT_MAX_PIXELS = 256L * 1024 * 1024; + + private NativeLimits() {} + + /** + * Returns the largest pixel count (width times height) a backend may + * decode, from {@value #MAX_PIXELS_PROPERTY}. + */ + public static long maxPixels() { + return Long.getLong(MAX_PIXELS_PROPERTY, DEFAULT_MAX_PIXELS); + } + + /** + * Rejects an image whose decoded size exceeds {@link #maxPixels()}, + * protecting against corrupt or hostile inputs that declare huge + * dimensions. + * + * @throws IIOException if the dimensions are not positive or exceed the limit + */ + public static void requireDecodable(long width, long height) + throws IIOException { + if (width <= 0 || height <= 0) { + throw new IIOException( + "Invalid image dimensions: " + width + "x" + height); + } + long limit = maxPixels(); + if (width > limit / height) { + throw new IIOException( + "Image too large: " + width + "x" + height + + " exceeds " + MAX_PIXELS_PROPERTY + "=" + limit); + } + } +} diff --git a/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/FormatDetectorTest.java b/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/FormatDetectorTest.java index db719f4..9cd5677 100644 --- a/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/FormatDetectorTest.java +++ b/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/FormatDetectorTest.java @@ -6,6 +6,8 @@ import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNull; class FormatDetectorTest { @@ -38,6 +40,102 @@ void wbmpDoesNotParticipateInPrefixBasedRouting() { new byte[]{0, 0, 3, 0}, 4)); } + @Test + void codecBrandWinsOverGenericHeifMajorBrand() { + assertEquals("avif", FormatDetector.detectFormat(ftyp("mif1", "miaf", "avif"), 28)); + assertEquals("heic", FormatDetector.detectFormat(ftyp("mif1", "heic"), 24)); + assertEquals("heif", FormatDetector.detectFormat(ftyp("mif1", "miaf"), 24)); + } + + @Test + void detectsCanonCr3AndSharesItWithVideoDetection() { + assertEquals("cr3", FormatDetector.detectFormat(ftyp("crx ", "isom"), 24)); + assertTrue(FormatDetector.isStillImageBrand("crx ")); + assertTrue(FormatDetector.isStillImageBrand("mif1")); + assertFalse(FormatDetector.isStillImageBrand("isom")); + } + + // ── TIFF family ───────────────────────────────────────────────────── + + @Test + void plainTiffFromACameraIsNotMistakenForRaw() { + // A TIFF exported from a camera JPEG keeps the make but its first + // IFD is the full image, with no sub-IFDs. + byte[] nikonTiff = tiff("NIKON CORPORATION", false, false); + byte[] sonyTiff = tiff("SONY", false, false); + + assertEquals("tiff", FormatDetector.detectFormat(nikonTiff, nikonTiff.length)); + assertEquals("tiff", FormatDetector.detectFormat(sonyTiff, sonyTiff.length)); + } + + @Test + void textThatHappensToContainDngIsStillTiff() { + byte[] described = tiff("Landing page, ending credits (dng)", false, false); + + assertEquals("tiff", FormatDetector.detectFormat(described, described.length)); + } + + @Test + void detectsRawWhenTheFirstIfdIsAPreviewOfSubIfdData() { + byte[] nef = tiff("NIKON CORPORATION", true, false); + byte[] arw = tiff("SONY", true, false); + + assertEquals("nef", FormatDetector.detectFormat(nef, nef.length)); + assertEquals("arw", FormatDetector.detectFormat(arw, arw.length)); + } + + @Test + void detectsDngFromItsVersionTag() { + byte[] dng = tiff("Leica Camera AG", false, true); + + assertEquals("dng", FormatDetector.detectFormat(dng, dng.length)); + } + + /** + * Builds a little-endian TIFF prefix whose first IFD carries a Make tag + * and, optionally, the preview-plus-sub-IFD shape of a RAW file or a + * DNGVersion tag. + */ + private static byte[] tiff(String make, boolean rawPreview, boolean dngVersion) { + byte[] makeBytes = (make + "\0").getBytes(StandardCharsets.US_ASCII); + int entries = 1 + (rawPreview ? 2 : 0) + (dngVersion ? 1 : 0); + int ifdEnd = 8 + 2 + entries * 12 + 4; + ByteBuffer buffer = ByteBuffer.allocate(ifdEnd + makeBytes.length + 16) + .order(java.nio.ByteOrder.LITTLE_ENDIAN); + buffer.put((byte) 'I').put((byte) 'I').putShort((short) 0x2A).putInt(8); + buffer.putShort((short) entries); + if (rawPreview) { + // NewSubfileType = 1 (reduced-resolution image) + buffer.putShort((short) 0x00FE).putShort((short) 4).putInt(1).putInt(1); + } + // Make (ASCII), stored after the IFD + buffer.putShort((short) 0x010F).putShort((short) 2) + .putInt(makeBytes.length).putInt(ifdEnd); + if (rawPreview) { + // SubIFDs: one offset + buffer.putShort((short) 0x014A).putShort((short) 4).putInt(1).putInt(ifdEnd); + } + if (dngVersion) { + buffer.putShort((short) 0xC612).putShort((short) 1).putInt(4).putInt(0x00000401); + } + buffer.putInt(0); + buffer.put(makeBytes); + return buffer.array(); + } + + private static byte[] ftyp(String major, String... compatible) { + int size = 16 + compatible.length * 4; + byte[] header = new byte[size]; + ByteBuffer.wrap(header).putInt(0, size); + System.arraycopy("ftyp".getBytes(StandardCharsets.US_ASCII), 0, header, 4, 4); + System.arraycopy(major.getBytes(StandardCharsets.US_ASCII), 0, header, 8, 4); + for (int i = 0; i < compatible.length; i++) { + System.arraycopy(compatible[i].getBytes(StandardCharsets.US_ASCII), 0, + header, 16 + i * 4, 4); + } + return header; + } + private static byte[] ftyp(String brand) { byte[] header = new byte[20]; ByteBuffer.wrap(header).putInt(0, 20); diff --git a/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/NativeLimitsTest.java b/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/NativeLimitsTest.java new file mode 100644 index 0000000..44b8359 --- /dev/null +++ b/imageio-native-common/src/test/java/io/github/ghosthack/imageio/common/NativeLimitsTest.java @@ -0,0 +1,43 @@ +package io.github.ghosthack.imageio.common; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import javax.imageio.IIOException; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NativeLimitsTest { + + @AfterEach + void clearOverride() { + System.clearProperty(NativeLimits.MAX_PIXELS_PROPERTY); + } + + @Test + void defaultsTo256Megapixels() { + assertEquals(256L * 1024 * 1024, NativeLimits.maxPixels()); + assertDoesNotThrow(() -> NativeLimits.requireDecodable(16384, 16384)); + assertThrows(IIOException.class, + () -> NativeLimits.requireDecodable(16385, 16384)); + } + + @Test + void honoursThePropertyOnEveryCall() { + System.setProperty(NativeLimits.MAX_PIXELS_PROPERTY, "100"); + + assertDoesNotThrow(() -> NativeLimits.requireDecodable(10, 10)); + assertThrows(IIOException.class, + () -> NativeLimits.requireDecodable(11, 10)); + } + + @Test + void rejectsNonPositiveAndOverflowingDimensions() { + assertThrows(IIOException.class, + () -> NativeLimits.requireDecodable(0, 10)); + assertThrows(IIOException.class, + () -> NativeLimits.requireDecodable(Integer.MAX_VALUE, Integer.MAX_VALUE)); + } +} diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java index be623cb..c543682 100644 --- a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java +++ b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/NativeVideoReader.java @@ -4,7 +4,6 @@ import io.github.ghosthack.imageio.common.NativeDecodeRequest; import io.github.ghosthack.imageio.common.NativeDecodeResult; -import javax.imageio.IIOException; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; @@ -34,9 +33,6 @@ */ public class NativeVideoReader extends ImageReader { - private static final long MAX_INTERMEDIATE_BYTES = Long.getLong( - "imageio.native.maxIntermediateBytes", 512L * 1024 * 1024); - /** Backend fixed by the caller, or {@code null} to route per input. */ private final VideoFrameExtractorProvider fixedProvider; private VideoFrameExtractorProvider provider; @@ -157,14 +153,7 @@ private void guardIntermediateAllocation(ImageReadParam param) width = info.width(); height = info.height(); } - if ((long) width * height > MAX_INTERMEDIATE_BYTES / 4L) { - throw new IIOException( - "Read parameters require a full " - + width + "x" + height - + " intermediate, exceeding imageio.native." - + "maxIntermediateBytes=" - + MAX_INTERMEDIATE_BYTES); - } + ImageReadParamSupport.validateIntermediateDimensions(width, height); } private void checkIndex(int imageIndex) throws IOException { diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoFormatDetector.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoFormatDetector.java index fbabe34..3f0b9ff 100644 --- a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoFormatDetector.java +++ b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/VideoFormatDetector.java @@ -1,5 +1,7 @@ package io.github.ghosthack.imageio.video; +import io.github.ghosthack.imageio.common.FormatDetector; + import javax.imageio.stream.ImageInputStream; import java.io.IOException; import java.io.InputStream; @@ -22,28 +24,20 @@ *

* ISO BMFF containers are also used for still images (HEIC, AVIF). To avoid * claiming image files as video, {@link #detectVideoISOBMFF} checks the ftyp major - * brand and compatible brands against a set of known image brands and rejects - * the match if any image brand is found. + * brand and compatible brands against the still-image brands known to + * {@link FormatDetector#isStillImageBrand} and rejects the match if any is + * found. Audio-only major brands are rejected as well. */ public final class VideoFormatDetector { private VideoFormatDetector() {} /** - * ISO BMFF brands that identify still-image containers. - * If the ftyp box declares any of these (as major or compatible brand), - * the file is an image — not a video — and must not be claimed. + * ISO BMFF major brands of audio-only files. They share the MP4 + * container but never hold a video track. */ - private static final Set IMAGE_BRANDS = Set.of( - // HEIF / HEIC - "heic", "heix", "heim", "heis", - "hevc", "hevx", "hevm", "hevs", - "mif1", "mif2", - // AVIF - "avif", "avis", - // JPEG 2000 - "jp2 ", "jpx ", "jpm " - ); + private static final Set AUDIO_BRANDS = Set.of( + "M4A ", "M4B ", "M4P "); /** * Known QuickTime/MPEG-4 atom types that appear at the start of MOV/MP4 files. @@ -101,7 +95,8 @@ static String detectFormat(byte[] header, int length) { * Returns {@code true} if the header is an ISO BMFF container (has {@code ftyp} * at offset 4) and none of its brands identify it as a still-image format. *

- * This prevents HEIC, AVIF, and JPEG 2000 files from being claimed as video. + * This prevents HEIC, AVIF, JPEG 2000, JPEG XL, and Canon CR3 files from + * being claimed as video. */ private static String detectVideoISOBMFF(byte[] h, int n) { // Must have ftyp signature at offset 4..7 @@ -116,14 +111,15 @@ private static String detectVideoISOBMFF(byte[] h, int n) { // Major brand at offset 8..11 String major = new String(h, 8, 4, StandardCharsets.US_ASCII); - if (IMAGE_BRANDS.contains(major)) return null; + if (FormatDetector.isStillImageBrand(major)) return null; + if (AUDIO_BRANDS.contains(major)) return null; // Compatible brands start at offset 16 (after 4-byte minor_version) // boxSize == 0 means "box extends to end of file" per ISO 14496-12 int limit = (boxSize == 0) ? n : Math.min(boxSize, n); for (int off = 16; off + 4 <= limit; off += 4) { String compat = new String(h, off, 4, StandardCharsets.US_ASCII); - if (IMAGE_BRANDS.contains(compat)) return null; + if (FormatDetector.isStillImageBrand(compat)) return null; } if (major.startsWith("3g")) return "3gp"; diff --git a/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/VideoFormatDetectorTest.java b/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/VideoFormatDetectorTest.java index 9973e18..89cf9bd 100644 --- a/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/VideoFormatDetectorTest.java +++ b/imageio-native-video-common/src/test/java/io/github/ghosthack/imageio/video/VideoFormatDetectorTest.java @@ -50,6 +50,17 @@ void rejectsAvifFtyp() throws IOException { assertFalse(probe(h), "AVIF should NOT be detected as video"); } + @Test + void rejectsCanonCr3AndJpegXlFtyp() throws IOException { + assertFalse(probe(makeFtyp("crx ", 20)), "Canon CR3 should NOT be detected as video"); + assertFalse(probe(makeFtyp("jxl ", 20)), "JPEG XL should NOT be detected as video"); + } + + @Test + void rejectsAudioOnlyFtyp() throws IOException { + assertFalse(probe(makeFtyp("M4A ", 20)), "M4A audio should NOT be detected as video"); + } + @Test void rejectsMif1Ftyp() throws IOException { byte[] h = makeFtyp("mif1", 20); diff --git a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java index 43fb46d..8d6dca8 100644 --- a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java +++ b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/VipsNative.java @@ -1,6 +1,7 @@ package io.github.ghosthack.imageio.vips; import io.github.ghosthack.imageio.common.NativeDecodeRequest; +import io.github.ghosthack.imageio.common.NativeLimits; import javax.imageio.IIOException; import java.awt.Dimension; @@ -36,8 +37,6 @@ private VipsNative() {} private static final int VIPS_ACCESS_SEQUENTIAL = 1; private static final int VIPS_SIZE_FORCE = 3; - /** Maximum total pixel count to prevent OOM (same as the platform-native backends). */ - private static final long MAX_PIXELS = 256L * 1024 * 1024; // ── Library loading ───────────────────────────────────────────────── @@ -603,10 +602,7 @@ private static BufferedImage decodeFromVipsImage(Arena arena, MemorySegment img) if (w <= 0 || h <= 0) throw new IIOException("Invalid image dimensions: " + w + "x" + h); - long totalPixels = (long) w * h; - if (totalPixels > MAX_PIXELS) - throw new IIOException("Image too large: " + w + "x" + h + " (" + totalPixels - + " pixels exceeds limit of " + MAX_PIXELS + ")"); + NativeLimits.requireDecodable(w, h); boolean hasAlpha = ((int) vips_image_hasalpha.invokeExact(img)) != 0; From baf23b4a6187cde04726adbb90d0890f7424832b Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:12:32 -0800 Subject: [PATCH 6/7] Remove unused public API Drop FormatDetector.matchesFtyp and matchesWebP, which nothing has called since routing moved to the single format detector; the javaNative flag on FormatRegistry.Format, which no code reads; and the deprecated, unregistered PathAware stream aliases in video-common, superseded by the ones in common. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- .../imageio/apple/FormatRegistry.java | 104 +++++++++--------- .../imageio/common/FormatDetector.java | 76 +------------ .../imageio/common/FormatRegistry.java | 5 +- .../imageio/magick/FormatRegistry.java | 60 +++++----- .../video/PathAwareImageInputStream.java | 23 ---- .../video/PathAwareImageInputStreamSpi.java | 70 ------------ .../imageio/vips/FormatRegistry.java | 42 +++---- .../imageio/windows/FormatRegistry.java | 70 ++++++------ 8 files changed, 143 insertions(+), 307 deletions(-) delete mode 100644 imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java delete mode 100644 imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java diff --git a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java index 84130b9..4471726 100644 --- a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java +++ b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java @@ -22,82 +22,82 @@ private FormatRegistry() {} /** All known Apple ImageIO source formats with metadata. */ private static final List ALL_FORMATS = List.of( // ── Java-native formats (built-in readers already exist) ──────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), - new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), + new Format(a("GIF","gif"), a("gif"), a("image/gif")), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), // ── Supplemental: formats Java cannot decode natively ─────────── // HEIF family - new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), - new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), + new Format(a("HEIC","heic"), a("heic"), a("image/heic")), + new Format(a("HEIF","heif"), a("heif"), a("image/heif")), // AV1 image - new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), + new Format(a("AVIF","avif"), a("avif"), a("image/avif")), // WebP - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), // JPEG 2000 - new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000"), false), + new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000")), // JPEG XL - new Format(a("JXL","jxl","JPEGXL"), a("jxl"), a("image/jxl"), false), + new Format(a("JXL","jxl","JPEGXL"), a("jxl"), a("image/jxl")), // Adobe PSD - new Format(a("PSD","psd"), a("psd"), a("image/vnd.adobe.photoshop"), false), + new Format(a("PSD","psd"), a("psd"), a("image/vnd.adobe.photoshop")), // Icons / cursors - new Format(a("ICO","ico"), a("ico"), a("image/x-icon"), false), - new Format(a("ICNS","icns"), a("icns"), a("image/x-icns"), false), - new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap"), false), + new Format(a("ICO","ico"), a("ico"), a("image/x-icon")), + new Format(a("ICNS","icns"), a("icns"), a("image/x-icns")), + new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap")), // HDR / scientific - new Format(a("EXR","exr"), a("exr"), a("image/x-exr"), false), - new Format(a("RADIANCE","hdr","rgbe"), a("hdr","pic","rgbe"), a("image/vnd.radiance"), false), + new Format(a("EXR","exr"), a("exr"), a("image/x-exr")), + new Format(a("RADIANCE","hdr","rgbe"), a("hdr","pic","rgbe"), a("image/vnd.radiance")), // Legacy / niche - new Format(a("TGA","tga"), a("tga","targa"), a("image/x-tga"), false), - new Format(a("SGI","sgi"), a("sgi","rgb","bw"), a("image/x-sgi"), false), - new Format(a("PBM","pbm","PGM","pgm","PPM","ppm"), a("pbm","pgm","ppm"),a("image/x-portable-bitmap"), false), - new Format(a("PICT","pict"), a("pict","pct"), a("image/x-pict"), false), - new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds"), false), - new Format(a("MPO","mpo"), a("mpo"), a("image/mpo"), false), - new Format(a("DICOM","dcm"), a("dcm","dicom"), a("application/dicom"), false), + new Format(a("TGA","tga"), a("tga","targa"), a("image/x-tga")), + new Format(a("SGI","sgi"), a("sgi","rgb","bw"), a("image/x-sgi")), + new Format(a("PBM","pbm","PGM","pgm","PPM","ppm"), a("pbm","pgm","ppm"),a("image/x-portable-bitmap")), + new Format(a("PICT","pict"), a("pict","pct"), a("image/x-pict")), + new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds")), + new Format(a("MPO","mpo"), a("mpo"), a("image/mpo")), + new Format(a("DICOM","dcm"), a("dcm","dicom"), a("application/dicom")), // GPU textures - new Format(a("KTX","ktx"), a("ktx"), a("image/ktx"), false), - new Format(a("KTX2","ktx2"), a("ktx2"), a("image/ktx2"), false), - new Format(a("ASTC","astc"), a("astc"), a("image/astc"), false), - new Format(a("PVR","pvr"), a("pvr"), a("image/x-pvr"), false), - new Format(a("ATX","atx"), a("atx"), a("image/x-atx"), false), + new Format(a("KTX","ktx"), a("ktx"), a("image/ktx")), + new Format(a("KTX2","ktx2"), a("ktx2"), a("image/ktx2")), + new Format(a("ASTC","astc"), a("astc"), a("image/astc")), + new Format(a("PVR","pvr"), a("pvr"), a("image/x-pvr")), + new Format(a("ATX","atx"), a("atx"), a("image/x-atx")), // Camera RAW (DNG + vendor) - new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng"), false), - new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2"), false), - new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3"), false), - new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw"), false), - new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef"), false), - new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw"), false), - new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw"), false), - new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2"), false), - new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf"), false), - new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf"), false), - new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf"), false), - new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2"), false), - new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef"), false), - new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw"), false), - new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf"), false), - new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw"), false), - new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr"), false), - new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr"), false), - new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff"), false), - new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq"), false), - new Format(a("MOS","mos"), a("mos"), a("image/x-leaf-mos"), false), - new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl"), false) + new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng")), + new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2")), + new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3")), + new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw")), + new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef")), + new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw")), + new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw")), + new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2")), + new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf")), + new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf")), + new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf")), + new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2")), + new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef")), + new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw")), + new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf")), + new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw")), + new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr")), + new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr")), + new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff")), + new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq")), + new Format(a("MOS","mos"), a("mos"), a("image/x-leaf-mos")), + new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl")) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java index ced82fd..ff53780 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java @@ -1,17 +1,13 @@ package io.github.ghosthack.imageio.common; -import javax.imageio.stream.ImageInputStream; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Set; /** - * Shared magic-byte detection for ISO BMFF (ftyp), RIFF/WEBP containers, - * and Java-native image formats. + * Shared magic-byte detection that names the format of an input prefix. *

- * Used by the {@link javax.imageio.spi.ImageReaderSpi} implementations in - * both the Apple and Windows platform modules to decide whether they can - * decode a given input. + * The routing layer uses the result to find candidate backends and to apply + * routing preferences; each backend still confirms with its own probe. */ public final class FormatDetector { @@ -334,72 +330,6 @@ private static boolean containsAscii(byte[] h, int len, String value) { return false; } - /** - * Checks whether an {@link ImageInputStream} starts with an ISO BMFF - * {@code ftyp} box whose major brand or any compatible brand is in the - * supplied set. - *

- * The stream position is saved and restored. - * - * @param stream the image input stream (must support mark/reset) - * @param brands set of 4-character brand codes to match - * @return {@code true} if the stream matches - */ - public static boolean matchesFtyp(ImageInputStream stream, Set brands) throws IOException { - byte[] header = new byte[128]; - stream.mark(); - try { - int n = stream.read(header, 0, header.length); - if (n < 12) return false; - - // bytes 4..7 must be "ftyp" - if (header[4] != 'f' || header[5] != 't' || header[6] != 'y' || header[7] != 'p') - return false; - - // Box size (big-endian uint32 at offset 0) - int boxSize = ((header[0] & 0xFF) << 24) - | ((header[1] & 0xFF) << 16) - | ((header[2] & 0xFF) << 8) - | ((header[3] & 0xFF)); - - // Major brand at offset 8..11 - String major = new String(header, 8, 4, StandardCharsets.US_ASCII); - if (brands.contains(major)) return true; - - // Compatible brands start at offset 16 (after 4-byte minor_version) - // boxSize == 0 means "box extends to end of file" per ISO 14496-12 - int limit = (boxSize == 0) ? n : Math.min(boxSize, n); - for (int off = 16; off + 4 <= limit; off += 4) { - String compat = new String(header, off, 4, StandardCharsets.US_ASCII); - if (brands.contains(compat)) return true; - } - - return false; - } finally { - stream.reset(); - } - } - - /** - * Checks whether an {@link ImageInputStream} starts with the RIFF/WEBP - * magic bytes: {@code RIFF....WEBP}. - *

- * The stream position is saved and restored. - */ - public static boolean matchesWebP(ImageInputStream stream) throws IOException { - byte[] header = new byte[12]; - stream.mark(); - try { - int n = stream.read(header, 0, 12); - if (n < 12) return false; - // offset 0..3 = "RIFF", offset 8..11 = "WEBP" - return header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F' - && header[8] == 'W' && header[9] == 'E' && header[10] == 'B' && header[11] == 'P'; - } finally { - stream.reset(); - } - } - /** Unsigned byte → int. */ private static int u(byte b) { return b & 0xFF; } } diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java index 2375d2d..2be1e3a 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java @@ -15,9 +15,8 @@ */ public final class FormatRegistry { - /** A format's ImageIO names, suffixes, MIME types, and host-JDK overlap. */ - public record Format(String[] names, String[] suffixes, String[] mimeTypes, - boolean javaNative) {} + /** A format's ImageIO names, suffixes, and MIME types. */ + public record Format(String[] names, String[] suffixes, String[] mimeTypes) {} private final List formats; private final Map canonicalNames; diff --git a/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java b/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java index 7bfc43a..f834e60 100644 --- a/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java +++ b/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java @@ -20,72 +20,72 @@ private FormatRegistry() {} private static final List ALL_FORMATS = List.of( // ── Java-native formats ───────────────────────────────────────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), - new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), + new Format(a("GIF","gif"), a("gif"), a("image/gif")), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), // ── Supplemental ──────────────────────────────────────────────── // HEIF family - new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), - new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), - new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), + new Format(a("HEIC","heic"), a("heic"), a("image/heic")), + new Format(a("HEIF","heif"), a("heif"), a("image/heif")), + new Format(a("AVIF","avif"), a("avif"), a("image/avif")), // WebP - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), // JPEG 2000 - new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000"), false), + new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000")), // PDF / EPS / AI (rasterisation) - new Format(a("PDF","pdf"), a("pdf"), a("application/pdf"), false), - new Format(a("EPS","eps"), a("eps","epsf","epsi"), a("application/postscript"), false), + new Format(a("PDF","pdf"), a("pdf"), a("application/pdf")), + new Format(a("EPS","eps"), a("eps","epsf","epsi"), a("application/postscript")), // SVG - new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml"), false), + new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml")), // Photoshop - new Format(a("PSD","psd"), a("psd","psb"), a("image/vnd.adobe.photoshop"), false), + new Format(a("PSD","psd"), a("psd","psb"), a("image/vnd.adobe.photoshop")), // OpenEXR - new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr"), false), + new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr")), // GIMP - new Format(a("XCF","xcf"), a("xcf"), a("image/x-xcf"), false), + new Format(a("XCF","xcf"), a("xcf"), a("image/x-xcf")), // DPX / Cineon - new Format(a("DPX","dpx"), a("dpx"), a("image/x-dpx"), false), + new Format(a("DPX","dpx"), a("dpx"), a("image/x-dpx")), // TGA - new Format(a("TGA","tga"), a("tga","tpic"), a("image/x-tga"), false), + new Format(a("TGA","tga"), a("tga","tpic"), a("image/x-tga")), // ICO / CUR - new Format(a("ICO","ico"), a("ico"), a("image/x-icon","image/vnd.microsoft.icon"), false), - new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap"), false), + new Format(a("ICO","ico"), a("ico"), a("image/x-icon","image/vnd.microsoft.icon")), + new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap")), // PCX - new Format(a("PCX","pcx"), a("pcx"), a("image/x-pcx"), false), + new Format(a("PCX","pcx"), a("pcx"), a("image/x-pcx")), // Netpbm - new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap"), false), - new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap"), false), - new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap"), false), + new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap")), + new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap")), + new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap")), // Radiance HDR - new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance"), false), + new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance")), // X bitmap / pixmap - new Format(a("XBM","xbm"), a("xbm"), a("image/x-xbitmap"), false), - new Format(a("XPM","xpm"), a("xpm"), a("image/x-xpixmap"), false), + new Format(a("XBM","xbm"), a("xbm"), a("image/x-xbitmap")), + new Format(a("XPM","xpm"), a("xpm"), a("image/x-xpixmap")), // FITS - new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits"), false), + new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits")), // DDS - new Format(a("DDS","dds"), a("dds"), a("image/x-dds"), false) + new Format(a("DDS","dds"), a("dds"), a("image/x-dds")) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java deleted file mode 100644 index c98fb22..0000000 --- a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.ghosthack.imageio.video; - -import java.io.File; -import java.io.IOException; - -/** - * Compatibility alias for the path-aware stream now provided by - * {@code imageio-native-common}. - *

- * New code should use - * {@link io.github.ghosthack.imageio.common.PathAwareImageInputStream}. - * - * @deprecated use - * {@link io.github.ghosthack.imageio.common.PathAwareImageInputStream} - */ -@Deprecated -public class PathAwareImageInputStream - extends io.github.ghosthack.imageio.common.PathAwareImageInputStream { - - public PathAwareImageInputStream(File file) throws IOException { - super(file); - } -} diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java deleted file mode 100644 index 69f0494..0000000 --- a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.github.ghosthack.imageio.video; - -import javax.imageio.spi.ImageInputStreamSpi; -import javax.imageio.spi.ServiceRegistry; -import javax.imageio.stream.ImageInputStream; -import java.io.File; -import java.io.IOException; -import java.util.Locale; - -/** - * Compatibility alias for the provider now registered by - * {@code imageio-native-common}. - *

- * This is transparent to all existing readers (since {@link PathAwareImageInputStream} - * extends {@link javax.imageio.stream.FileImageInputStream}) but allows video-aware - * readers to extract the file path via {@link PathAwareImageInputStream#getPath()}. - *

This alias is no longer service-registered; the shared provider is - * registered by {@code imageio-native-common}.

- * - * @deprecated use - * {@link io.github.ghosthack.imageio.common.PathAwareImageInputStreamSpi} - */ -@Deprecated -public class PathAwareImageInputStreamSpi extends ImageInputStreamSpi { - - public PathAwareImageInputStreamSpi() { - super("ghosthack", "1.0", File.class); - } - - /** - * Ensures this SPI is ordered before any other {@code File}-based - * {@link ImageInputStreamSpi} (in particular the JDK's built-in - * {@code FileImageInputStream} SPI). - *

- * Without explicit ordering, the JDK's SPI may win, which would - * produce a plain {@code FileImageInputStream} instead of a - * {@link PathAwareImageInputStream}, breaking - * {@link NativeVideoReader}'s ability to recover the file path. - */ - @Override - @SuppressWarnings("unchecked") - public void onRegistration(ServiceRegistry registry, Class category) { - // Iterate all registered ImageInputStreamSpi providers that handle File - var others = registry.getServiceProviders( - (Class) category, true); - while (others.hasNext()) { - ImageInputStreamSpi other = others.next(); - if (other != this && File.class.equals(other.getInputClass())) { - // "this before other" — our SPI takes priority - registry.setOrdering( - (Class) category, this, other); - } - } - } - - @Override - public String getDescription(Locale locale) { - return "Path-aware FileImageInputStream for video frame extraction"; - } - - @Override - public ImageInputStream createInputStreamInstance(Object input, boolean useCache, - File cacheDir) throws IOException { - if (input instanceof File file) { - return new PathAwareImageInputStream(file); - } - throw new IllegalArgumentException("Expected File input, got: " + - (input == null ? "null" : input.getClass().getName())); - } -} diff --git a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java index a0e7acf..69f62ea 100644 --- a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java +++ b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java @@ -29,51 +29,51 @@ private FormatRegistry() {} /** All known libvips-decodable formats with metadata. */ private static final List ALL_FORMATS = List.of( // ── Java-native formats (built-in readers already exist) ──────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), - new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), + new Format(a("GIF","gif"), a("gif"), a("image/gif")), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), // ── Supplemental: formats Java cannot decode natively ─────────── // HEIF family (requires libheif) - new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), - new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), + new Format(a("HEIC","heic"), a("heic"), a("image/heic")), + new Format(a("HEIF","heif"), a("heif"), a("image/heif")), // AV1 image (requires libheif with AV1 decoder) - new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), + new Format(a("AVIF","avif"), a("avif"), a("image/avif")), // WebP (requires libwebp) - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), // JPEG 2000 (requires libopenjp2) - new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000"), false), + new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000")), // PDF (requires poppler) - new Format(a("PDF","pdf"), a("pdf"), a("application/pdf"), false), + new Format(a("PDF","pdf"), a("pdf"), a("application/pdf")), // SVG (requires librsvg) - new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml"), false), + new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml")), // OpenEXR (requires OpenEXR library) - new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr"), false), + new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr")), // FITS (requires cfitsio) - new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits"), false), + new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits")), // Netpbm (built-in) - new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap"), false), - new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap"), false), - new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap"), false), - new Format(a("PFM","pfm"), a("pfm"), a("image/x-portable-floatmap"), false), + new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap")), + new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap")), + new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap")), + new Format(a("PFM","pfm"), a("pfm"), a("image/x-portable-floatmap")), // Radiance HDR (built-in) - new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance"), false), + new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance")), // Analyze (built-in) - new Format(a("Analyze","analyze"), a("hdr","img"), a("application/x-analyze"), false) + new Format(a("Analyze","analyze"), a("hdr","img"), a("application/x-analyze")) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = diff --git a/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java b/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java index 7f51ea6..3a178e1 100644 --- a/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java +++ b/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java @@ -21,58 +21,58 @@ private FormatRegistry() {} /** All known WIC-decodable formats with metadata. */ private static final List ALL_FORMATS = List.of( // ── Java-native formats (built-in readers already exist) ──────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), - new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), + new Format(a("GIF","gif"), a("gif"), a("image/gif")), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), // ── Supplemental: formats Java cannot decode natively ─────────── // HEIF family (requires HEVC Video Extensions from Microsoft Store) - new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), - new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), + new Format(a("HEIC","heic"), a("heic"), a("image/heic")), + new Format(a("HEIF","heif"), a("heif"), a("image/heif")), // AV1 image (requires AV1 Video Extensions from Microsoft Store) - new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), + new Format(a("AVIF","avif"), a("avif"), a("image/avif")), // WebP (built-in on Windows 10 1809+) - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), // JPEG-XR / HD Photo (built-in WIC codec) new Format(a("JPEGXR","jpegxr","JXR","jxr","WDP","wdp","HDP","hdp"), - a("jxr","wdp","hdp"), a("image/vnd.ms-photo","image/jxr"), false), + a("jxr","wdp","hdp"), a("image/vnd.ms-photo","image/jxr")), // DDS (DirectDraw Surface, built-in WIC codec) - new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds"), false), + new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds")), // Icons / cursors - new Format(a("ICO","ico"), a("ico"), a("image/x-icon"), false), - new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap"), false), + new Format(a("ICO","ico"), a("ico"), a("image/x-icon")), + new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap")), // Camera RAW (WIC codec available via Microsoft Camera Codec Pack or built-in on Win10+) - new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng"), false), - new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2"), false), - new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3"), false), - new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw"), false), - new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef"), false), - new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw"), false), - new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw"), false), - new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2"), false), - new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf"), false), - new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf"), false), - new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf"), false), - new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2"), false), - new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef"), false), - new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw"), false), - new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf"), false), - new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw"), false), - new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr"), false), - new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr"), false), - new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff"), false), - new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq"), false), - new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl"), false) + new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng")), + new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2")), + new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3")), + new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw")), + new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef")), + new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw")), + new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw")), + new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2")), + new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf")), + new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf")), + new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf")), + new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2")), + new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef")), + new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw")), + new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf")), + new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw")), + new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr")), + new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr")), + new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff")), + new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq")), + new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl")) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = From 2bc3830ce86f7dd531a1674535e1cc897b227dd7 Mon Sep 17 00:00:00 2001 From: ghosthack <837911+ghosthack@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:13:27 -0800 Subject: [PATCH 7/7] Restore public API removed in the previous commit Bring back FormatDetector.matchesFtyp and matchesWebP, the javaNative component of FormatRegistry.Format, and the deprecated PathAware stream aliases in video-common. They stay part of the public API. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VwoQ7k4zMHqQ43juZ2juRw --- .../imageio/apple/FormatRegistry.java | 104 +++++++++--------- .../imageio/common/FormatDetector.java | 76 ++++++++++++- .../imageio/common/FormatRegistry.java | 5 +- .../imageio/magick/FormatRegistry.java | 60 +++++----- .../video/PathAwareImageInputStream.java | 23 ++++ .../video/PathAwareImageInputStreamSpi.java | 70 ++++++++++++ .../imageio/vips/FormatRegistry.java | 42 +++---- .../imageio/windows/FormatRegistry.java | 70 ++++++------ 8 files changed, 307 insertions(+), 143 deletions(-) create mode 100644 imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java create mode 100644 imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java diff --git a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java index 4471726..84130b9 100644 --- a/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java +++ b/imageio-native-apple/src/main/java/io/github/ghosthack/imageio/apple/FormatRegistry.java @@ -22,82 +22,82 @@ private FormatRegistry() {} /** All known Apple ImageIO source formats with metadata. */ private static final List ALL_FORMATS = List.of( // ── Java-native formats (built-in readers already exist) ──────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), - new Format(a("GIF","gif"), a("gif"), a("image/gif")), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), + new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), // ── Supplemental: formats Java cannot decode natively ─────────── // HEIF family - new Format(a("HEIC","heic"), a("heic"), a("image/heic")), - new Format(a("HEIF","heif"), a("heif"), a("image/heif")), + new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), + new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), // AV1 image - new Format(a("AVIF","avif"), a("avif"), a("image/avif")), + new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), // WebP - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), // JPEG 2000 - new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000")), + new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000"), false), // JPEG XL - new Format(a("JXL","jxl","JPEGXL"), a("jxl"), a("image/jxl")), + new Format(a("JXL","jxl","JPEGXL"), a("jxl"), a("image/jxl"), false), // Adobe PSD - new Format(a("PSD","psd"), a("psd"), a("image/vnd.adobe.photoshop")), + new Format(a("PSD","psd"), a("psd"), a("image/vnd.adobe.photoshop"), false), // Icons / cursors - new Format(a("ICO","ico"), a("ico"), a("image/x-icon")), - new Format(a("ICNS","icns"), a("icns"), a("image/x-icns")), - new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap")), + new Format(a("ICO","ico"), a("ico"), a("image/x-icon"), false), + new Format(a("ICNS","icns"), a("icns"), a("image/x-icns"), false), + new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap"), false), // HDR / scientific - new Format(a("EXR","exr"), a("exr"), a("image/x-exr")), - new Format(a("RADIANCE","hdr","rgbe"), a("hdr","pic","rgbe"), a("image/vnd.radiance")), + new Format(a("EXR","exr"), a("exr"), a("image/x-exr"), false), + new Format(a("RADIANCE","hdr","rgbe"), a("hdr","pic","rgbe"), a("image/vnd.radiance"), false), // Legacy / niche - new Format(a("TGA","tga"), a("tga","targa"), a("image/x-tga")), - new Format(a("SGI","sgi"), a("sgi","rgb","bw"), a("image/x-sgi")), - new Format(a("PBM","pbm","PGM","pgm","PPM","ppm"), a("pbm","pgm","ppm"),a("image/x-portable-bitmap")), - new Format(a("PICT","pict"), a("pict","pct"), a("image/x-pict")), - new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds")), - new Format(a("MPO","mpo"), a("mpo"), a("image/mpo")), - new Format(a("DICOM","dcm"), a("dcm","dicom"), a("application/dicom")), + new Format(a("TGA","tga"), a("tga","targa"), a("image/x-tga"), false), + new Format(a("SGI","sgi"), a("sgi","rgb","bw"), a("image/x-sgi"), false), + new Format(a("PBM","pbm","PGM","pgm","PPM","ppm"), a("pbm","pgm","ppm"),a("image/x-portable-bitmap"), false), + new Format(a("PICT","pict"), a("pict","pct"), a("image/x-pict"), false), + new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds"), false), + new Format(a("MPO","mpo"), a("mpo"), a("image/mpo"), false), + new Format(a("DICOM","dcm"), a("dcm","dicom"), a("application/dicom"), false), // GPU textures - new Format(a("KTX","ktx"), a("ktx"), a("image/ktx")), - new Format(a("KTX2","ktx2"), a("ktx2"), a("image/ktx2")), - new Format(a("ASTC","astc"), a("astc"), a("image/astc")), - new Format(a("PVR","pvr"), a("pvr"), a("image/x-pvr")), - new Format(a("ATX","atx"), a("atx"), a("image/x-atx")), + new Format(a("KTX","ktx"), a("ktx"), a("image/ktx"), false), + new Format(a("KTX2","ktx2"), a("ktx2"), a("image/ktx2"), false), + new Format(a("ASTC","astc"), a("astc"), a("image/astc"), false), + new Format(a("PVR","pvr"), a("pvr"), a("image/x-pvr"), false), + new Format(a("ATX","atx"), a("atx"), a("image/x-atx"), false), // Camera RAW (DNG + vendor) - new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng")), - new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2")), - new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3")), - new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw")), - new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef")), - new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw")), - new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw")), - new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2")), - new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf")), - new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf")), - new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf")), - new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2")), - new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef")), - new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw")), - new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf")), - new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw")), - new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr")), - new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr")), - new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff")), - new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq")), - new Format(a("MOS","mos"), a("mos"), a("image/x-leaf-mos")), - new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl")) + new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng"), false), + new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2"), false), + new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3"), false), + new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw"), false), + new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef"), false), + new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw"), false), + new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw"), false), + new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2"), false), + new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf"), false), + new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf"), false), + new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf"), false), + new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2"), false), + new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef"), false), + new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw"), false), + new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf"), false), + new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw"), false), + new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr"), false), + new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr"), false), + new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff"), false), + new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq"), false), + new Format(a("MOS","mos"), a("mos"), a("image/x-leaf-mos"), false), + new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl"), false) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java index ff53780..ced82fd 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatDetector.java @@ -1,13 +1,17 @@ package io.github.ghosthack.imageio.common; +import javax.imageio.stream.ImageInputStream; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Set; /** - * Shared magic-byte detection that names the format of an input prefix. + * Shared magic-byte detection for ISO BMFF (ftyp), RIFF/WEBP containers, + * and Java-native image formats. *

- * The routing layer uses the result to find candidate backends and to apply - * routing preferences; each backend still confirms with its own probe. + * Used by the {@link javax.imageio.spi.ImageReaderSpi} implementations in + * both the Apple and Windows platform modules to decide whether they can + * decode a given input. */ public final class FormatDetector { @@ -330,6 +334,72 @@ private static boolean containsAscii(byte[] h, int len, String value) { return false; } + /** + * Checks whether an {@link ImageInputStream} starts with an ISO BMFF + * {@code ftyp} box whose major brand or any compatible brand is in the + * supplied set. + *

+ * The stream position is saved and restored. + * + * @param stream the image input stream (must support mark/reset) + * @param brands set of 4-character brand codes to match + * @return {@code true} if the stream matches + */ + public static boolean matchesFtyp(ImageInputStream stream, Set brands) throws IOException { + byte[] header = new byte[128]; + stream.mark(); + try { + int n = stream.read(header, 0, header.length); + if (n < 12) return false; + + // bytes 4..7 must be "ftyp" + if (header[4] != 'f' || header[5] != 't' || header[6] != 'y' || header[7] != 'p') + return false; + + // Box size (big-endian uint32 at offset 0) + int boxSize = ((header[0] & 0xFF) << 24) + | ((header[1] & 0xFF) << 16) + | ((header[2] & 0xFF) << 8) + | ((header[3] & 0xFF)); + + // Major brand at offset 8..11 + String major = new String(header, 8, 4, StandardCharsets.US_ASCII); + if (brands.contains(major)) return true; + + // Compatible brands start at offset 16 (after 4-byte minor_version) + // boxSize == 0 means "box extends to end of file" per ISO 14496-12 + int limit = (boxSize == 0) ? n : Math.min(boxSize, n); + for (int off = 16; off + 4 <= limit; off += 4) { + String compat = new String(header, off, 4, StandardCharsets.US_ASCII); + if (brands.contains(compat)) return true; + } + + return false; + } finally { + stream.reset(); + } + } + + /** + * Checks whether an {@link ImageInputStream} starts with the RIFF/WEBP + * magic bytes: {@code RIFF....WEBP}. + *

+ * The stream position is saved and restored. + */ + public static boolean matchesWebP(ImageInputStream stream) throws IOException { + byte[] header = new byte[12]; + stream.mark(); + try { + int n = stream.read(header, 0, 12); + if (n < 12) return false; + // offset 0..3 = "RIFF", offset 8..11 = "WEBP" + return header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F' + && header[8] == 'W' && header[9] == 'E' && header[10] == 'B' && header[11] == 'P'; + } finally { + stream.reset(); + } + } + /** Unsigned byte → int. */ private static int u(byte b) { return b & 0xFF; } } diff --git a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java index 2be1e3a..2375d2d 100644 --- a/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java +++ b/imageio-native-common/src/main/java/io/github/ghosthack/imageio/common/FormatRegistry.java @@ -15,8 +15,9 @@ */ public final class FormatRegistry { - /** A format's ImageIO names, suffixes, and MIME types. */ - public record Format(String[] names, String[] suffixes, String[] mimeTypes) {} + /** A format's ImageIO names, suffixes, MIME types, and host-JDK overlap. */ + public record Format(String[] names, String[] suffixes, String[] mimeTypes, + boolean javaNative) {} private final List formats; private final Map canonicalNames; diff --git a/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java b/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java index f834e60..7bfc43a 100644 --- a/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java +++ b/imageio-native-magick/src/main/java/io/github/ghosthack/imageio/magick/FormatRegistry.java @@ -20,72 +20,72 @@ private FormatRegistry() {} private static final List ALL_FORMATS = List.of( // ── Java-native formats ───────────────────────────────────────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), - new Format(a("GIF","gif"), a("gif"), a("image/gif")), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), + new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), // ── Supplemental ──────────────────────────────────────────────── // HEIF family - new Format(a("HEIC","heic"), a("heic"), a("image/heic")), - new Format(a("HEIF","heif"), a("heif"), a("image/heif")), - new Format(a("AVIF","avif"), a("avif"), a("image/avif")), + new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), + new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), + new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), // WebP - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), // JPEG 2000 - new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000")), + new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000"), false), // PDF / EPS / AI (rasterisation) - new Format(a("PDF","pdf"), a("pdf"), a("application/pdf")), - new Format(a("EPS","eps"), a("eps","epsf","epsi"), a("application/postscript")), + new Format(a("PDF","pdf"), a("pdf"), a("application/pdf"), false), + new Format(a("EPS","eps"), a("eps","epsf","epsi"), a("application/postscript"), false), // SVG - new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml")), + new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml"), false), // Photoshop - new Format(a("PSD","psd"), a("psd","psb"), a("image/vnd.adobe.photoshop")), + new Format(a("PSD","psd"), a("psd","psb"), a("image/vnd.adobe.photoshop"), false), // OpenEXR - new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr")), + new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr"), false), // GIMP - new Format(a("XCF","xcf"), a("xcf"), a("image/x-xcf")), + new Format(a("XCF","xcf"), a("xcf"), a("image/x-xcf"), false), // DPX / Cineon - new Format(a("DPX","dpx"), a("dpx"), a("image/x-dpx")), + new Format(a("DPX","dpx"), a("dpx"), a("image/x-dpx"), false), // TGA - new Format(a("TGA","tga"), a("tga","tpic"), a("image/x-tga")), + new Format(a("TGA","tga"), a("tga","tpic"), a("image/x-tga"), false), // ICO / CUR - new Format(a("ICO","ico"), a("ico"), a("image/x-icon","image/vnd.microsoft.icon")), - new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap")), + new Format(a("ICO","ico"), a("ico"), a("image/x-icon","image/vnd.microsoft.icon"), false), + new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap"), false), // PCX - new Format(a("PCX","pcx"), a("pcx"), a("image/x-pcx")), + new Format(a("PCX","pcx"), a("pcx"), a("image/x-pcx"), false), // Netpbm - new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap")), - new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap")), - new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap")), + new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap"), false), + new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap"), false), + new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap"), false), // Radiance HDR - new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance")), + new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance"), false), // X bitmap / pixmap - new Format(a("XBM","xbm"), a("xbm"), a("image/x-xbitmap")), - new Format(a("XPM","xpm"), a("xpm"), a("image/x-xpixmap")), + new Format(a("XBM","xbm"), a("xbm"), a("image/x-xbitmap"), false), + new Format(a("XPM","xpm"), a("xpm"), a("image/x-xpixmap"), false), // FITS - new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits")), + new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits"), false), // DDS - new Format(a("DDS","dds"), a("dds"), a("image/x-dds")) + new Format(a("DDS","dds"), a("dds"), a("image/x-dds"), false) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java new file mode 100644 index 0000000..c98fb22 --- /dev/null +++ b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStream.java @@ -0,0 +1,23 @@ +package io.github.ghosthack.imageio.video; + +import java.io.File; +import java.io.IOException; + +/** + * Compatibility alias for the path-aware stream now provided by + * {@code imageio-native-common}. + *

+ * New code should use + * {@link io.github.ghosthack.imageio.common.PathAwareImageInputStream}. + * + * @deprecated use + * {@link io.github.ghosthack.imageio.common.PathAwareImageInputStream} + */ +@Deprecated +public class PathAwareImageInputStream + extends io.github.ghosthack.imageio.common.PathAwareImageInputStream { + + public PathAwareImageInputStream(File file) throws IOException { + super(file); + } +} diff --git a/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java new file mode 100644 index 0000000..69f0494 --- /dev/null +++ b/imageio-native-video-common/src/main/java/io/github/ghosthack/imageio/video/PathAwareImageInputStreamSpi.java @@ -0,0 +1,70 @@ +package io.github.ghosthack.imageio.video; + +import javax.imageio.spi.ImageInputStreamSpi; +import javax.imageio.spi.ServiceRegistry; +import javax.imageio.stream.ImageInputStream; +import java.io.File; +import java.io.IOException; +import java.util.Locale; + +/** + * Compatibility alias for the provider now registered by + * {@code imageio-native-common}. + *

+ * This is transparent to all existing readers (since {@link PathAwareImageInputStream} + * extends {@link javax.imageio.stream.FileImageInputStream}) but allows video-aware + * readers to extract the file path via {@link PathAwareImageInputStream#getPath()}. + *

This alias is no longer service-registered; the shared provider is + * registered by {@code imageio-native-common}.

+ * + * @deprecated use + * {@link io.github.ghosthack.imageio.common.PathAwareImageInputStreamSpi} + */ +@Deprecated +public class PathAwareImageInputStreamSpi extends ImageInputStreamSpi { + + public PathAwareImageInputStreamSpi() { + super("ghosthack", "1.0", File.class); + } + + /** + * Ensures this SPI is ordered before any other {@code File}-based + * {@link ImageInputStreamSpi} (in particular the JDK's built-in + * {@code FileImageInputStream} SPI). + *

+ * Without explicit ordering, the JDK's SPI may win, which would + * produce a plain {@code FileImageInputStream} instead of a + * {@link PathAwareImageInputStream}, breaking + * {@link NativeVideoReader}'s ability to recover the file path. + */ + @Override + @SuppressWarnings("unchecked") + public void onRegistration(ServiceRegistry registry, Class category) { + // Iterate all registered ImageInputStreamSpi providers that handle File + var others = registry.getServiceProviders( + (Class) category, true); + while (others.hasNext()) { + ImageInputStreamSpi other = others.next(); + if (other != this && File.class.equals(other.getInputClass())) { + // "this before other" — our SPI takes priority + registry.setOrdering( + (Class) category, this, other); + } + } + } + + @Override + public String getDescription(Locale locale) { + return "Path-aware FileImageInputStream for video frame extraction"; + } + + @Override + public ImageInputStream createInputStreamInstance(Object input, boolean useCache, + File cacheDir) throws IOException { + if (input instanceof File file) { + return new PathAwareImageInputStream(file); + } + throw new IllegalArgumentException("Expected File input, got: " + + (input == null ? "null" : input.getClass().getName())); + } +} diff --git a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java index 69f62ea..a0e7acf 100644 --- a/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java +++ b/imageio-native-vips/src/main/java/io/github/ghosthack/imageio/vips/FormatRegistry.java @@ -29,51 +29,51 @@ private FormatRegistry() {} /** All known libvips-decodable formats with metadata. */ private static final List ALL_FORMATS = List.of( // ── Java-native formats (built-in readers already exist) ──────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), - new Format(a("GIF","gif"), a("gif"), a("image/gif")), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), + new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), // ── Supplemental: formats Java cannot decode natively ─────────── // HEIF family (requires libheif) - new Format(a("HEIC","heic"), a("heic"), a("image/heic")), - new Format(a("HEIF","heif"), a("heif"), a("image/heif")), + new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), + new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), // AV1 image (requires libheif with AV1 decoder) - new Format(a("AVIF","avif"), a("avif"), a("image/avif")), + new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), // WebP (requires libwebp) - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), // JPEG 2000 (requires libopenjp2) - new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000")), + new Format(a("JPEG2000","jpeg2000","JP2","jp2"), a("jp2","j2k","jpf","jpx","j2c"), a("image/jp2","image/jpeg2000"), false), // PDF (requires poppler) - new Format(a("PDF","pdf"), a("pdf"), a("application/pdf")), + new Format(a("PDF","pdf"), a("pdf"), a("application/pdf"), false), // SVG (requires librsvg) - new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml")), + new Format(a("SVG","svg"), a("svg","svgz"), a("image/svg+xml"), false), // OpenEXR (requires OpenEXR library) - new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr")), + new Format(a("EXR","exr","OpenEXR"), a("exr"), a("image/x-exr"), false), // FITS (requires cfitsio) - new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits")), + new Format(a("FITS","fits"), a("fits","fit","fts"), a("application/fits"), false), // Netpbm (built-in) - new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap")), - new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap")), - new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap")), - new Format(a("PFM","pfm"), a("pfm"), a("image/x-portable-floatmap")), + new Format(a("PBM","pbm"), a("pbm"), a("image/x-portable-bitmap"), false), + new Format(a("PGM","pgm"), a("pgm"), a("image/x-portable-graymap"), false), + new Format(a("PPM","ppm"), a("ppm"), a("image/x-portable-pixmap"), false), + new Format(a("PFM","pfm"), a("pfm"), a("image/x-portable-floatmap"), false), // Radiance HDR (built-in) - new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance")), + new Format(a("HDR","hdr","Radiance"), a("hdr"), a("image/vnd.radiance"), false), // Analyze (built-in) - new Format(a("Analyze","analyze"), a("hdr","img"), a("application/x-analyze")) + new Format(a("Analyze","analyze"), a("hdr","img"), a("application/x-analyze"), false) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE = diff --git a/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java b/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java index 3a178e1..7f51ea6 100644 --- a/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java +++ b/imageio-native-windows/src/main/java/io/github/ghosthack/imageio/windows/FormatRegistry.java @@ -21,58 +21,58 @@ private FormatRegistry() {} /** All known WIC-decodable formats with metadata. */ private static final List ALL_FORMATS = List.of( // ── Java-native formats (built-in readers already exist) ──────── - new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg")), - new Format(a("PNG","png"), a("png"), a("image/png","image/x-png")), - new Format(a("GIF","gif"), a("gif"), a("image/gif")), - new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp")), - new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff")), - new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp")), + new Format(a("JPEG","jpeg","JPG","jpg"), a("jpg","jpeg","jpe","jfif"), a("image/jpeg"), true), + new Format(a("PNG","png"), a("png"), a("image/png","image/x-png"), true), + new Format(a("GIF","gif"), a("gif"), a("image/gif"), true), + new Format(a("BMP","bmp"), a("bmp","dib"), a("image/bmp","image/x-ms-bmp"), true), + new Format(a("TIFF","tiff"), a("tiff","tif"), a("image/tiff"), true), + new Format(a("WBMP","wbmp"), a("wbmp"), a("image/vnd.wap.wbmp"), true), // ── Supplemental: formats Java cannot decode natively ─────────── // HEIF family (requires HEVC Video Extensions from Microsoft Store) - new Format(a("HEIC","heic"), a("heic"), a("image/heic")), - new Format(a("HEIF","heif"), a("heif"), a("image/heif")), + new Format(a("HEIC","heic"), a("heic"), a("image/heic"), false), + new Format(a("HEIF","heif"), a("heif"), a("image/heif"), false), // AV1 image (requires AV1 Video Extensions from Microsoft Store) - new Format(a("AVIF","avif"), a("avif"), a("image/avif")), + new Format(a("AVIF","avif"), a("avif"), a("image/avif"), false), // WebP (built-in on Windows 10 1809+) - new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp")), + new Format(a("WEBP","webp","WebP"), a("webp"), a("image/webp"), false), // JPEG-XR / HD Photo (built-in WIC codec) new Format(a("JPEGXR","jpegxr","JXR","jxr","WDP","wdp","HDP","hdp"), - a("jxr","wdp","hdp"), a("image/vnd.ms-photo","image/jxr")), + a("jxr","wdp","hdp"), a("image/vnd.ms-photo","image/jxr"), false), // DDS (DirectDraw Surface, built-in WIC codec) - new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds")), + new Format(a("DDS","dds"), a("dds"), a("image/vnd.ms-dds"), false), // Icons / cursors - new Format(a("ICO","ico"), a("ico"), a("image/x-icon")), - new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap")), + new Format(a("ICO","ico"), a("ico"), a("image/x-icon"), false), + new Format(a("CUR","cur"), a("cur"), a("image/x-win-bitmap"), false), // Camera RAW (WIC codec available via Microsoft Camera Codec Pack or built-in on Win10+) - new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng")), - new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2")), - new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3")), - new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw")), - new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef")), - new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw")), - new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw")), - new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2")), - new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf")), - new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf")), - new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf")), - new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2")), - new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef")), - new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw")), - new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf")), - new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw")), - new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr")), - new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr")), - new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff")), - new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq")), - new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl")) + new Format(a("DNG","dng"), a("dng"), a("image/x-adobe-dng"), false), + new Format(a("CR2","cr2"), a("cr2"), a("image/x-canon-cr2"), false), + new Format(a("CR3","cr3"), a("cr3"), a("image/x-canon-cr3"), false), + new Format(a("CRW","crw"), a("crw"), a("image/x-canon-crw"), false), + new Format(a("NEF","nef"), a("nef"), a("image/x-nikon-nef"), false), + new Format(a("NRW","nrw"), a("nrw"), a("image/x-nikon-nrw"), false), + new Format(a("ARW","arw"), a("arw"), a("image/x-sony-arw"), false), + new Format(a("SR2","sr2"), a("sr2"), a("image/x-sony-sr2"), false), + new Format(a("SRF","srf"), a("srf"), a("image/x-sony-srf"), false), + new Format(a("ORF","orf"), a("orf"), a("image/x-olympus-orf"), false), + new Format(a("RAF","raf"), a("raf"), a("image/x-fuji-raf"), false), + new Format(a("RW2","rw2"), a("rw2"), a("image/x-panasonic-rw2"), false), + new Format(a("PEF","pef"), a("pef"), a("image/x-pentax-pef"), false), + new Format(a("SRW","srw"), a("srw"), a("image/x-samsung-srw"), false), + new Format(a("ERF","erf"), a("erf"), a("image/x-epson-erf"), false), + new Format(a("MRW","mrw"), a("mrw"), a("image/x-minolta-mrw"), false), + new Format(a("DCR","dcr"), a("dcr"), a("image/x-kodak-dcr"), false), + new Format(a("3FR","3fr"), a("3fr"), a("image/x-hasselblad-3fr"), false), + new Format(a("FFF","fff"), a("fff"), a("image/x-hasselblad-fff"), false), + new Format(a("IIQ","iiq"), a("iiq"), a("image/x-phaseone-iiq"), false), + new Format(a("RWL","rwl"), a("rwl"), a("image/x-leica-rwl"), false) ); static final io.github.ghosthack.imageio.common.FormatRegistry INSTANCE =