From 3a4a7e7cf9f2aa891e2794e009ca17b2cea589d2 Mon Sep 17 00:00:00 2001 From: Mauro Romito Date: Tue, 20 Oct 2026 16:49:11 +0200 Subject: [PATCH] Keep spatial photos spatial when stripping location data Spatial photos pair their images in a stereo group. ImageIO only writes that group from the properties each image is added with, so re-encoding a photo to remove its location dropped the pairing, and the photo was sent as a flat one with hidden extra images. Each image is now added with its stereo group again, read from the source's container properties, so the left, right and monoscopic images keep their roles along with the group's disparity adjustment. ImageIO ignores the group's image index keys and anything it can't write, so the group is passed on as it is. --- .../Media/MediaUploadingPreprocessor.swift | 27 ++++- .../MediaUploadingPreprocessorTests.swift | 99 +++++++++++++++++++ 2 files changed, 122 insertions(+), 4 deletions(-) diff --git a/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift b/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift index 4b3a7bfbb..d94eccd3d 100644 --- a/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift +++ b/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift @@ -381,7 +381,7 @@ nonisolated struct MediaUploadingPreprocessor { } let count = CGImageSourceGetCount(imageSource) - let metadataKeysToRemove = [kCGImagePropertyGPSDictionary: kCFNull] + let metadataKeysToRemove: [CFString: Any] = [kCGImagePropertyGPSDictionary: kCFNull as Any] let data = NSMutableData() @@ -394,12 +394,16 @@ nonisolated struct MediaUploadingPreprocessor { } // The container properties hold an animation's loop count. - if let properties = CGImageSourceCopyProperties(imageSource, nil) { - CGImageDestinationSetProperties(destination, properties) + let containerProperties = CGImageSourceCopyProperties(imageSource, nil) as? [CFString: Any] + if let containerProperties { + CGImageDestinationSetProperties(destination, containerProperties as NSDictionary) } + let groups = containerProperties?[kCGImagePropertyGroups] as? [[CFString: Any]] ?? [] for index in 0.. [CFString: Any]? { + let roles: KeyValuePairs = [kCGImagePropertyGroupImageIndexLeft: kCGImagePropertyGroupImageIsLeftImage, + kCGImagePropertyGroupImageIndexRight: kCGImagePropertyGroupImageIsRightImage, + kCGImagePropertyGroupImageIndexMonoscopic: kCGImagePropertyGroupImageIsMonoscopicImage] + + for group in groups { + if let role = roles.first(where: { group[$0.key] as? Int == index })?.value { + // ImageIO ignores the group's index keys and takes the image's role from this flag. + return group.merging([role: true]) { $1 } + } + } + return nil + } + /// Copies the HDR gain map of the image at the given index, which is stored as auxiliary data and isn't copied along with the image. /// ImageIO attaches it to the most recently added image, so call this right after adding the image at that index. private func copyGainMap(from imageSource: CGImageSource, at index: Int, to destination: CGImageDestination) { diff --git a/UnitTests/Sources/MediaUploadingPreprocessorTests.swift b/UnitTests/Sources/MediaUploadingPreprocessorTests.swift index 4c404b589..f38a42416 100644 --- a/UnitTests/Sources/MediaUploadingPreprocessorTests.swift +++ b/UnitTests/Sources/MediaUploadingPreprocessorTests.swift @@ -376,6 +376,53 @@ final class MediaUploadingPreprocessorTests { #expect(CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, 2, kCGImageAuxiliaryDataTypeHDRGainMap) == nil) } + @Test + func spatialImageProcessingKeepsStereoPair() async throws { + let imageSource = try await processedImageSource(at: makeSpatialImageWithLocation()) + + let group = try #require(stereoGroup(of: imageSource)) + #expect(group[kCGImagePropertyGroupImageIndexMonoscopic] as? Int == 0) + #expect(group[kCGImagePropertyGroupImageIndexRight] as? Int == 1) + #expect(group[kCGImagePropertyGroupImageIndexLeft] as? Int == 2) + #expect(group[kCGImagePropertyGroupImageDisparityAdjustment] as? Int == 800) + #expect(group[kCGImagePropertyGroupMonoscopicImageLocation] as? String == kIIOMonoscopicImageLocation_Right as String) + } + + @Test + func spatialImageProcessingKeepsEyeCameras() async throws { + let imageSource = try await processedImageSource(at: makeSpatialImageWithLocation()) + + for eyeIndex in [1, 2] { + let properties = try #require(CGImageSourceCopyPropertiesAtIndex(imageSource, eyeIndex, nil) as? [CFString: Any]) + let camera = properties[kCGImagePropertyHEIFDictionary] as? [CFString: Any] + #expect(camera?[kIIOMetadata_CameraExtrinsicsKey] != nil) + #expect(camera?[kIIOMetadata_CameraModelKey] != nil) + } + } + + @Test + func spatialImageProcessingStripsLocationFromEveryImage() async throws { + let imageSource = try await processedImageSource(at: makeSpatialImageWithLocation()) + + #expect(CGImageSourceGetCount(imageSource) == 3) + for index in 0.. URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("\(Self.self)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent("spatial_test_image.heic") + + let roles = [kCGImagePropertyGroupImageIsMonoscopicImage, kCGImagePropertyGroupImageIsRightImage, kCGImagePropertyGroupImageIsLeftImage] + let destination = try #require(CGImageDestinationCreateWithURL(url as NSURL, UTType.heic.identifier as CFString, roles.count, nil)) + let colorSpace = try #require(CGColorSpace(name: CGColorSpace.displayP3)) + + for (index, role) in roles.enumerated() { + 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: 16 + 8 * index, height: 16 + 8 * index)) + let hdrData = try #require(CIContext().heifRepresentation(of: image, format: .RGBA8, colorSpace: colorSpace, options: [.hdrGainMapImage: gainMap])) + let hdrSource = try #require(CGImageSourceCreateWithData(hdrData as NSData, nil)) + let gainMapInfo = try #require(CGImageSourceCopyAuxiliaryDataInfoAtIndex(hdrSource, 0, kCGImageAuxiliaryDataTypeHDRGainMap)) + + var properties: [CFString: Any] = [kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 51.5, kCGImagePropertyGPSLongitude: 0.1], + kCGImagePropertyGroups: [kCGImagePropertyGroupIndex: 0, + kCGImagePropertyGroupType: kCGImagePropertyGroupTypeStereoPair, + kCGImagePropertyGroupImageDisparityAdjustment: 800, + kCGImagePropertyGroupMonoscopicImageLocation: kIIOMonoscopicImageLocation_Right, + role: true]] + if role != kCGImagePropertyGroupImageIsMonoscopicImage { + properties[kCGImagePropertyHEIFDictionary] = [kIIOMetadata_CameraExtrinsicsKey: [kIIOCameraExtrinsics_Position: [0.0, 0.0, 0.0], + kIIOCameraExtrinsics_Rotation: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]], + kIIOMetadata_CameraModelKey: [kIIOCameraModel_Intrinsics: [1000.0, 0.0, 32.0, 0.0, 1000.0, 32.0, 0.0, 0.0, 1.0]]] + } + CGImageDestinationAddImageFromSource(destination, hdrSource, 0, properties as NSDictionary) + CGImageDestinationAddAuxiliaryDataInfo(destination, kCGImageAuxiliaryDataTypeHDRGainMap, gainMapInfo) + } + try #require(CGImageDestinationFinalize(destination)) + + let imageSource = try #require(CGImageSourceCreateWithURL(url as NSURL, nil)) + try #require(stereoGroup(of: imageSource) != nil) + + return url + } + + /// The stereo pair group of a spatial photo, which ImageIO reports on the whole image rather than on each of its images. + private func stereoGroup(of imageSource: CGImageSource) -> [CFString: Any]? { + let groups = (CGImageSourceCopyProperties(imageSource, nil) as? [CFString: Any])?[kCGImagePropertyGroups] as? [[CFString: Any]] + return groups?.first { $0[kCGImagePropertyGroupType] as? String == kCGImagePropertyGroupTypeStereoPair as String } + } + + private func gainMapWidth(of imageSource: CGImageSource, at index: Int) -> Int? { + let gainMapInfo = CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, index, kCGImageAuxiliaryDataTypeHDRGainMap) as? [CFString: Any] + let description = gainMapInfo?[kCGImageAuxiliaryDataInfoDataDescription] as? [String: Any] + return description?["Width"] as? Int + } + /// Generates a copy of the animated test GIF with GPS metadata on every frame in a unique temporary directory. private func makeAnimatedGIFWithLocation(loopCount: Int) throws -> URL { let assetURL = try #require(Bundle(for: Self.self).url(forResource: "test_animated_image.gif", withExtension: nil))