From 74b6c234b3c27d4039557c85713c2b33ab7b9f5a Mon Sep 17 00:00:00 2001 From: Rene Schakmann <108671777+rene-schakmann@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:19:53 +0200 Subject: [PATCH] Keep HDR gain maps when stripping location data from images (#6371) --- .../Media/MediaUploadingPreprocessor.swift | 69 +++++++- .../MediaUploadingPreprocessorTests.swift | 162 +++++++++++++++++- 2 files changed, 219 insertions(+), 12 deletions(-) diff --git a/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift b/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift index 074557f64..4b3a7bfbb 100644 --- a/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift +++ b/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift @@ -95,6 +95,8 @@ nonisolated struct MediaUploadingPreprocessor { static let jpegCompressionQuality = 0.78 static let videoThumbnailTime = 5.0 // seconds static let maximumConcurrentProcessingCount = 2 + /// The XMP namespaces of Apple's and ISO gain map HDR metadata. + static let hdrMetadataNamespaces: Set = ["http://ns.apple.com/HDRGainMap/1.0/", "http://ns.apple.com/HDRToneMap/1.0/"] } /// Processes media at the given URLs. It will generate thumbnails for images and videos, convert videos to 1080p mp4, strip GPS locations @@ -219,7 +221,7 @@ nonisolated struct MediaUploadingPreprocessor { } } - /// Prepares an image for upload. Strips location data from it and generates a thumbnail + /// Prepares an image for upload. Resizes it when optimising (otherwise strips location data from it) and generates a thumbnail /// - Parameters: /// - url: The image URL /// - type: its UTType @@ -229,11 +231,9 @@ nonisolated struct MediaUploadingPreprocessor { private func processImage(at url: URL, type: UTType, mimeType: String, maxUploadSize: UInt) async -> Result { var url = url do { - try stripLocationFromImage(at: url, type: type) - guard !Task.isCancelled else { return .failure(.cancelled) } - var mimeType = mimeType if userSettings.app.optimizeMediaUploads, !type.conforms(to: .gif) { + // Resizing writes a new image without any metadata, so there's no location left to strip. let outputType = type.conforms(to: .png) ? UTType.png : .jpeg mimeType = outputType.preferredMIMEType ?? "application/octet-stream" try resizeImage(at: url, maxPixelSize: Constants.optimizedMaxPixelSize, destination: url, type: outputType) @@ -248,6 +248,8 @@ nonisolated struct MediaUploadingPreprocessor { } url = convertedURL } + } else { + try stripLocationFromImage(at: url, type: type) } guard !Task.isCancelled else { return .failure(.cancelled) } @@ -361,7 +363,7 @@ nonisolated struct MediaUploadingPreprocessor { // MARK: Image Helpers - /// Removes the GPS dictionary from an image's metadata + /// Removes the GPS dictionary from the metadata of every frame in an image /// - Parameters: /// - url: the URL for the original image /// - type: its UTType @@ -391,8 +393,19 @@ nonisolated struct MediaUploadingPreprocessor { throw .failedStrippingLocationData } - CGImageDestinationAddImageFromSource(destination, imageSource, 0, metadataKeysToRemove as NSDictionary) - CGImageDestinationFinalize(destination) + // The container properties hold an animation's loop count. + if let properties = CGImageSourceCopyProperties(imageSource, nil) { + CGImageDestinationSetProperties(destination, properties) + } + + for index in 0.. CGImageMetadata { + let hdrMetadata = CGImageMetadataCreateMutable() + + CGImageMetadataEnumerateTagsUsingBlock(metadata, nil, nil) { path, tag in + guard let namespace = CGImageMetadataTagCopyNamespace(tag), + let prefix = CGImageMetadataTagCopyPrefix(tag), + Constants.hdrMetadataNamespaces.contains(namespace as String) else { + return true + } + + CGImageMetadataRegisterNamespaceForPrefix(hdrMetadata, namespace, prefix, nil) + CGImageMetadataSetTagWithPath(hdrMetadata, nil, path, tag) + return true + } + + return hdrMetadata + } + /// Generates a thumbnail for an image /// - Parameter url: the original image URL /// - Returns: the URL for the resulting thumbnail and its sizing info as an `ImageProcessingResult` @@ -453,7 +503,10 @@ nonisolated struct MediaUploadingPreprocessor { let properties = [kCGImageDestinationLossyCompressionQuality: Constants.jpegCompressionQuality] CGImageDestinationAddImage(destination, scaledImage, properties as NSDictionary) - CGImageDestinationFinalize(destination) + + guard CGImageDestinationFinalize(destination) else { + throw .failedResizingImage + } } // MARK: Video Helpers diff --git a/UnitTests/Sources/MediaUploadingPreprocessorTests.swift b/UnitTests/Sources/MediaUploadingPreprocessorTests.swift index 72efa16a6..4c404b589 100644 --- a/UnitTests/Sources/MediaUploadingPreprocessorTests.swift +++ b/UnitTests/Sources/MediaUploadingPreprocessorTests.swift @@ -197,7 +197,7 @@ final class MediaUploadingPreprocessorTests { // Check optimised image info #expect(optimizedImageInfo.mimetype == "image/jpeg") #expect(optimizedImageInfo.blurhash == "K%I#.NofkC_4ayaxxujsWB") - #expect(isEqual(optimizedImageInfo.size ?? 0, 524_226, within: 100)) + #expect(isEqual(optimizedImageInfo.size ?? 0, 523_809, within: 100)) #expect(optimizedImageInfo.width == 2048) #expect(optimizedImageInfo.height == 879) } @@ -241,7 +241,7 @@ final class MediaUploadingPreprocessorTests { // Check optimised image info #expect(optimizedImageInfo.mimetype == "image/jpeg") #expect(optimizedImageInfo.blurhash == "KdE|0Ls+RP^-n*RP%OWAV@") - #expect(isEqual(optimizedImageInfo.size ?? 0, 1_462_937, within: 100)) + #expect(isEqual(optimizedImageInfo.size ?? 0, 1_466_366, within: 100)) #expect(optimizedImageInfo.width == 1536) #expect(optimizedImageInfo.height == 2048) } @@ -341,12 +341,64 @@ final class MediaUploadingPreprocessorTests { // Check optimised image info #expect(optimizedImageInfo.mimetype == "image/jpeg") - #expect(optimizedImageInfo.blurhash == "KGD]3ns:T00#kWxFb^s:xv") - #expect(isEqual(optimizedImageInfo.size ?? 0, 1_049_393, within: 100)) + #expect(optimizedImageInfo.blurhash == "KGD]3ns:T00#kWxFXms:xv") + #expect(isEqual(optimizedImageInfo.size ?? 0, 1_063_370, within: 100)) #expect(optimizedImageInfo.width == 1536) #expect(optimizedImageInfo.height == 2048) } + @Test + func hdrImageProcessingStripsLocationFromImageAndGainMap() async throws { + let imageSource = try await processedImageSource(at: makeHDRImageWithLocation()) + + let metadata = try #require(CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as NSDictionary?) + #expect(metadata.value(forKeyPath: "\(kCGImagePropertyGPSDictionary)") == nil) + + let gainMapMetadata = try gainMapMetadata(from: imageSource) + #expect(CGImageMetadataCopyTagWithPath(gainMapMetadata, nil, "exif:GPSLatitude" as CFString) == nil) + #expect(CGImageMetadataCopyTagWithPath(gainMapMetadata, nil, "exif:GPSLongitude" as CFString) == nil) + } + + @Test + func hdrImageProcessingPreservesGainMap() async throws { + let imageSource = try await processedImageSource(at: makeHDRImageWithLocation()) + + let gainMapMetadata = try gainMapMetadata(from: imageSource) + #expect(CGImageMetadataCopyTagWithPath(gainMapMetadata, nil, "HDRGainMap:HDRGainMapVersion" as CFString) != nil) + } + + @Test + func multiImageHDRProcessingKeepsGainMapOnItsImage() async throws { + let imageSource = try await processedImageSource(at: makeHDRImageWithLocation(imageCount: 3)) + + #expect(CGImageSourceGetCount(imageSource) == 3) + #expect(CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, 0, kCGImageAuxiliaryDataTypeHDRGainMap) != nil) + #expect(CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, 2, kCGImageAuxiliaryDataTypeHDRGainMap) == nil) + } + + @Test + func optimisedImageProcessingSkipsStrippingLocation() async throws { + // A read-only image can't be rewritten in place, so it can only be processed when the strip is skipped. + let url = try copyResourceToTemporaryDirectory("landscape_test_image.jpg") + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: url.path(percentEncoded: false)) + + guard case .failure(.failedProcessingImage(.failedStrippingLocationData)) = await mediaUploadingPreprocessor.processMedia(at: url, maxUploadSize: maxUploadSize) else { + Issue.record("Expected stripping the location to fail") + return + } + + userSettings.app.optimizeMediaUploads = true + + guard case let .success(result) = await mediaUploadingPreprocessor.processMedia(at: url, maxUploadSize: maxUploadSize), + case let .image(optimizedImageURL, thumbnailURL, _) = result else { + Issue.record("Failed processing asset") + return + } + + try compare(originalImageAt: url, toConvertedImageAt: optimizedImageURL, withThumbnailAt: thumbnailURL) + } + @Test func gifImageProcessing() async throws { let url = try #require(Bundle(for: Self.self).url(forResource: "test_animated_image.gif", withExtension: nil), "Failed retrieving test asset") @@ -397,6 +449,24 @@ final class MediaUploadingPreprocessorTests { #expect(optimizedImageInfo.height == 472) } + @Test + func animatedGIFWithLocationProcessingKeepsAllFrames() async throws { + let url = try makeAnimatedGIFWithLocation(loopCount: 3) + let originalSource = try #require(CGImageSourceCreateWithURL(url as NSURL, nil)) + + let imageSource = try await processedImageSource(at: url) + + #expect(CGImageSourceGetCount(imageSource) == CGImageSourceGetCount(originalSource)) + #expect(gifProperties(of: imageSource)?[kCGImagePropertyGIFLoopCount] as? Int == 3) + + for index in 0.. CGImageSource { + let mediaInfo = try await mediaUploadingPreprocessor.processMedia(at: url, maxUploadSize: maxUploadSize).get() + return try #require(CGImageSourceCreateWithURL(mediaInfo.url as NSURL, nil)) + } + + private func gainMapMetadata(from imageSource: CGImageSource) throws -> CGImageMetadata { + let gainMapInfo = try #require(CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, 0, kCGImageAuxiliaryDataTypeHDRGainMap) as? [CFString: Any]) + let gainMapMetadata = try #require(gainMapInfo[kCGImageAuxiliaryDataInfoMetadata]) + // swiftlint:disable:next force_cast + return gainMapMetadata as! CGImageMetadata + } + + /// Generates a HEIC with an HDR gain map on its first image and GPS metadata (on both the images and the gain map) in a unique temporary directory. + private func makeHDRImageWithLocation(imageCount: Int = 1) throws -> URL { + let image = CIImage(color: .gray).cropped(to: CGRect(x: 0, y: 0, width: 64, height: 64)) + let gainMap = CIImage(color: .white).cropped(to: CGRect(x: 0, y: 0, width: 32, height: 32)) + let colorSpace = try #require(CGColorSpace(name: CGColorSpace.displayP3)) + let hdrData = try #require(CIContext().heifRepresentation(of: image, format: .RGBA8, colorSpace: colorSpace, options: [.hdrGainMapImage: gainMap])) + let hdrSource = try #require(CGImageSourceCreateWithData(hdrData as NSData, nil)) + var gainMapInfo = try #require(CGImageSourceCopyAuxiliaryDataInfoAtIndex(hdrSource, 0, kCGImageAuxiliaryDataTypeHDRGainMap) as? [CFString: Any]) + let gainMapMetadataWithLocation = try #require(CGImageMetadataCreateMutableCopy(gainMapMetadata(from: hdrSource))) + try #require(CGImageMetadataSetValueWithPath(gainMapMetadataWithLocation, nil, "exif:GPSLatitude" as CFString, "51,30.0N" as CFString)) + try #require(CGImageMetadataSetValueWithPath(gainMapMetadataWithLocation, nil, "exif:GPSLongitude" as CFString, "0,6.0W" as CFString)) + gainMapInfo[kCGImageAuxiliaryDataInfoMetadata] = gainMapMetadataWithLocation + + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("\(Self.self)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent("hdr_test_image.heic") + + let destination = try #require(CGImageDestinationCreateWithURL(url as NSURL, UTType.heic.identifier as CFString, imageCount, nil)) + let location = [kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 51.5, kCGImagePropertyGPSLongitude: 0.1]] + CGImageDestinationAddImageFromSource(destination, hdrSource, 0, location as NSDictionary) + CGImageDestinationAddAuxiliaryDataInfo(destination, kCGImageAuxiliaryDataTypeHDRGainMap, gainMapInfo as NSDictionary) + for _ in 1.. URL { + let assetURL = try #require(Bundle(for: Self.self).url(forResource: "test_animated_image.gif", withExtension: nil)) + let gifSource = try #require(CGImageSourceCreateWithURL(assetURL as NSURL, nil)) + let frameCount = CGImageSourceGetCount(gifSource) + try #require(frameCount > 1) + + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("\(Self.self)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent("gif_test_image.gif") + + let destination = try #require(CGImageDestinationCreateWithURL(url as NSURL, UTType.gif.identifier as CFString, frameCount, nil)) + CGImageDestinationSetProperties(destination, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: loopCount]] as NSDictionary) + let location = [kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 51.5, kCGImagePropertyGPSLongitude: 0.1]] + for index in 0.. [CFString: Any]? { + let properties = if let index { + CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil) + } else { + CGImageSourceCopyProperties(imageSource, nil) + } + return (properties as? [CFString: Any])?[kCGImagePropertyGIFDictionary] as? [CFString: Any] + } + /// The unique folders created by the preprocessor for the given file that still exist. private func preparedFolders(for url: URL) throws -> [URL] { let name = url.deletingPathExtension().lastPathComponent