diff --git a/README.md b/README.md index 038f93d..9e74e3d 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. @@ -425,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 | @@ -469,7 +483,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 @@ -521,9 +535,14 @@ 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. 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 | |------------|-----------| @@ -540,9 +559,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. + +**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. 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. +**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/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-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-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/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/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/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-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-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-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/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-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/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..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; @@ -21,8 +20,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. @@ -33,20 +33,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 +120,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 @@ -150,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/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-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-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 0000000..a07e7d4 Binary files /dev/null and b/imageio-native-video-common/src/test/resources/test-video-long-gop.mp4 differ 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 0000000..02d1069 Binary files /dev/null and b/imageio-native-video-common/src/test/resources/test-video-rotated.mp4 differ diff --git a/imageio-native-video-ffmpeg/src/main/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractor.java b/imageio-native-video-ffmpeg/src/main/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractor.java index 8daed1d..950ffd7 100644 --- a/imageio-native-video-ffmpeg/src/main/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractor.java +++ b/imageio-native-video-ffmpeg/src/main/java/io/github/ghosthack/imageio/video/ffmpeg/FFmpegVideoFrameExtractor.java @@ -28,11 +28,26 @@ *

* 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/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-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..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 ───────────────────────────────────────────────── @@ -51,12 +50,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 +97,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 +140,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 +214,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 +281,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 +308,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 +330,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 +350,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 +515,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 ──────────────────────────────────────── @@ -548,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; 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 { 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 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()); 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"