SPB Git

Repository Public License

MediaTests.swift 39.9 KB 660 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Tests/ORIXImagingTests/MediaTests.swift10// Description      : Metadata, export fidelity, the movie writer, storage, the11//                    SwiftData library and duplicate detection.12// Module           : ORIXImagingTests13// Repository       : https://git.spboucher.ai/orix-camera14// Project Website  : https://www.orixlab.dev15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AVFoundation92import CoreGraphics93import CoreMedia94import Foundation95import ImageIO96import Testing97import UniformTypeIdentifiers98@testable import ORIXImaging99100enum MediaFixture {101    /// A JPEG carrying EXIF, TIFF and GPS metadata, as a camera would write it.102    static func photoWithMetadata(in directory: URL, name: String = "source.jpg", width: Int = 320, height: Int = 240) -> URL {103        let url = directory.appendingPathComponent(name)104        let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.jpeg.identifier as CFString, 1, nil)!105        let properties: [CFString: Any] = [106            kCGImagePropertyOrientation: 6,107            kCGImagePropertyTIFFDictionary: [kCGImagePropertyTIFFMake: "Apple", kCGImagePropertyTIFFModel: "iPhone Test", kCGImagePropertyTIFFSoftware: "ORIX Camera"],108            kCGImagePropertyExifDictionary: [109                kCGImagePropertyExifDateTimeOriginal: "2026:11:20 10:11:12", kCGImagePropertyExifLensModel: "Test back camera 6.86mm f/1.78",110                kCGImagePropertyExifFocalLength: 6.86, kCGImagePropertyExifFocalLenIn35mmFilm: 24, kCGImagePropertyExifFNumber: 1.78,111                kCGImagePropertyExifExposureTime: 1.0 / 120, kCGImagePropertyExifISOSpeedRatings: [80], kCGImagePropertyExifExposureBiasValue: -0.3,112                kCGImagePropertyExifFlash: 0, kCGImagePropertyExifWhiteBalance: 1,113            ] as [CFString: Any],114            kCGImagePropertyGPSDictionary: [115                kCGImagePropertyGPSLatitude: 45.4215, kCGImagePropertyGPSLatitudeRef: "N", kCGImagePropertyGPSLongitude: 75.6972,116                kCGImagePropertyGPSLongitudeRef: "W", kCGImagePropertyGPSAltitude: 70.0, kCGImagePropertyGPSAltitudeRef: 0,117            ] as [CFString: Any],118        ]119        CGImageDestinationAddImage(destination, Fixture.image(Fixture.textured(width: width, height: height)), properties as CFDictionary)120        CGImageDestinationFinalize(destination)121        return url122    }123124    static func recordMovie(to url: URL, codec: VideoCodec = .h264, frames: Int = 30, width: Int = 320, height: Int = 180, fps: Double = 30, timeLapse: Double? = nil) async throws -> VideoRecordingResult {125        var configuration = VideoRecorderConfiguration(url: url, width: width, height: height, codec: codec, frameRate: fps)126        configuration.audio = false127        configuration.timeLapsePlaybackRate = timeLapse128        let recorder = try VideoRecorder(configuration: configuration)129        let scene = SyntheticScene(width: width, height: height)!130        for i in 0..<frames {131            let buffer = scene.render(time: Double(i) / fps)!132            for _ in 0..<400 where !recorder.isReadyForVideo { try await Task.sleep(for: .milliseconds(5)) }133            recorder.appendVideo(buffer, time: CMTime(value: CMTimeValue(i), timescale: CMTimeScale(fps)) + CMTime(seconds: 100, preferredTimescale: 600))134        }135        return try await recorder.finish()136    }137}138139@Suite struct MetadataTests {140    @Test func readsEveryFieldThatIsPresent() throws {141        let url = MediaFixture.photoWithMetadata(in: Fixture.tempDirectory())142        let m = try #require(MetadataInspector.readImage(url: url))143        #expect(m.pixelWidth == 320 && m.pixelHeight == 240 && m.orientation == 6)144        #expect(m.cameraMake == "Apple" && m.cameraModel == "iPhone Test")145        #expect(m.captureDate == "2026:11:20 10:11:12")146        #expect(m.iso == 80 && m.aperture == 1.78 && m.focalLength35mm == 24)147        #expect(abs((m.exposureTime ?? 0) - 1.0 / 120) < 1e-6)148        #expect(m.flashFired == false && m.whiteBalanceManual == true)149        #expect(abs((m.latitude ?? 0) - 45.4215) < 1e-4 && abs((m.longitude ?? 0) + 75.6972) < 1e-4 && m.altitude == 70)150        #expect(m.typeIdentifier == "public.jpeg" && (m.fileSize ?? 0) > 1000 && !m.isRAW)151    }152153    @Test func absentFieldsStayNil() throws {154        let directory = Fixture.tempDirectory()155        let url = try ImageExporter.export(Fixture.image(Fixture.solid(9, 9, 9)), options: { var o = ImageExportOptions(); o.format = .png; return o }(), to: directory)156        let m = try #require(MetadataInspector.readImage(url: url))157        #expect(m.iso == nil && m.cameraModel == nil && m.latitude == nil && m.lensModel == nil && !m.hasLocation)158        let json = try #require(String(data: MetadataInspector.jsonReport(m), encoding: .utf8))159        #expect(json.contains("\"pixelWidth\" : 64") && !json.contains("iso"))160    }161162    @Test func readsVideoMetadata() async throws {163        let url = Fixture.tempDirectory().appendingPathComponent("clip.mov")164        _ = try await MediaFixture.recordMovie(to: url, codec: .hevc, frames: 30)165        let m = try #require(await MetadataInspector.readVideo(url: url))166        #expect(m.pixelWidth == 320 && m.pixelHeight == 180 && m.videoCodec == "HEVC" && m.hasAudio == false)167        #expect(abs((m.duration ?? 0) - 1.0) < 0.05 && abs((m.frameRate ?? 0) - 30) < 1)168    }169}170171@Suite struct ExportTests {172    let image = Fixture.image(Fixture.textured(width: 400, height: 300))173174    @Test(arguments: ExportImageFormat.allCases) func everyFormatDecodesBackToTheSamePicture(format: ExportImageFormat) throws {175        var options = ImageExportOptions(); options.format = format; options.quality = 0.95; options.fileName = "roundtrip"176        let url = try ImageExporter.export(image, options: options, to: Fixture.tempDirectory())177        #expect(url.pathExtension == format.fileExtension)178        let source = try #require(CGImageSourceCreateWithURL(url as CFURL, nil))179        #expect(CGImageSourceGetType(source) as String? == format.type.identifier)180        let decoded = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil))181        #expect(decoded.width == 400 && decoded.height == 300)182        let original = try #require(FloatImage(cgImage: image))183        let psnr = try #require(FloatImage(cgImage: decoded)).psnr(original)184        #expect(psnr > (format.isLossy ? 34 : 60), "\(format) PSNR \(psnr)")185    }186187    @Test func resizeQualityAndColourSpace() throws {188        let directory = Fixture.tempDirectory()189        var options = ImageExportOptions(); options.maxDimension = 100; options.colorSpace = .displayP3190        let small = try ImageExporter.export(image, options: options, to: directory)191        let meta = try #require(MetadataInspector.readImage(url: small))192        #expect(meta.pixelWidth == 100 && meta.pixelHeight == 75)193        #expect(meta.colorProfile?.contains("P3") == true)194        options = ImageExportOptions(); options.quality = 0.3; options.fileName = "low"195        let low = try ImageExporter.export(image, options: options, to: directory)196        options.quality = 0.95; options.fileName = "high"197        let high = try ImageExporter.export(image, options: options, to: directory)198        let lowSize = try #require(MetadataInspector.fileSize(low)), highSize = try #require(MetadataInspector.fileSize(high))199        #expect(lowSize < highSize)200    }201202    @Test func metadataPoliciesAreHonoured() throws {203        let directory = Fixture.tempDirectory()204        let source = MediaFixture.photoWithMetadata(in: directory)205        let properties = MetadataInspector.properties(url: source)206        func export(_ policy: MetadataPolicy) throws -> MediaMetadata {207            var options = ImageExportOptions(); options.metadata = policy; options.fileName = policy.rawValue208            let url = try ImageExporter.export(image, sourceProperties: properties, options: options, to: directory)209            return try #require(MetadataInspector.readImage(url: url))210        }211        let all = try export(.keepAll)212        #expect(all.hasLocation && all.iso == 80 && all.cameraModel == "iPhone Test" && all.orientation == 1 && all.pixelWidth == 400)213        let noLocation = try export(.removeLocation)214        #expect(!noLocation.hasLocation && noLocation.iso == 80 && noLocation.lensModel != nil)215        let none = try export(.removeAll)216        #expect(!none.hasLocation && none.iso == nil && none.cameraModel == nil && none.captureDate == nil)217    }218219    @Test func originalExportIsByteIdentical() throws {220        let directory = Fixture.tempDirectory()221        let source = MediaFixture.photoWithMetadata(in: directory)222        let copy = try ImageExporter.exportOriginal(source, fileName: "copy", to: directory.appendingPathComponent("out"))223        #expect(try Data(contentsOf: copy) == Data(contentsOf: source))224        #expect(DuplicateDetector.contentHash(url: copy) == DuplicateDetector.contentHash(url: source))225    }226227    @Test func fileNamesAreSanitizedAndNeverOverwrite() throws {228        let directory = Fixture.tempDirectory()229        var options = ImageExportOptions(); options.fileName = "a/b:c?"230        let first = try ImageExporter.export(image, options: options, to: directory)231        let second = try ImageExporter.export(image, options: options, to: directory)232        #expect(first.lastPathComponent == "a-b-c-.jpg" && second.lastPathComponent == "a-b-c--2.jpg")233        #expect(ImageExporter.sanitized("   ") == "ORIX")234    }235236    @Test func sixteenBitSourcesStayDeepInTIFFAndPNG() throws {237        let float = try #require(FloatImage(cgImage: image))238        let deep = try #require(float.cgImage16())239        for format in [ExportImageFormat.tiff, .png] {240            var options = ImageExportOptions(); options.format = format; options.fileName = "deep"241            let url = try ImageExporter.export(deep, options: options, to: Fixture.tempDirectory())242            #expect(MetadataInspector.readImage(url: url)?.bitDepth == 16)243        }244        var options = ImageExportOptions(); options.format = .jpeg245        let jpeg = try ImageExporter.export(deep, options: options, to: Fixture.tempDirectory())246        #expect(MetadataInspector.readImage(url: jpeg)?.bitDepth == 8)247    }248249    @Test func videoPassthroughAndReencode() async throws {250        let directory = Fixture.tempDirectory()251        let source = directory.appendingPathComponent("source.mov")252        _ = try await MediaFixture.recordMovie(to: source, codec: .h264, frames: 30, width: 640, height: 360)253        let original = try await VideoExporter.export(source, preset: .original, removeLocation: false, to: directory.appendingPathComponent("a"))254        #expect(try Data(contentsOf: original) == Data(contentsOf: source))255        let hevc = try await VideoExporter.export(source, preset: .hevc1080, removeLocation: true, to: directory.appendingPathComponent("b"))256        let meta = try #require(await MetadataInspector.readVideo(url: hevc))257        #expect(meta.videoCodec == "HEVC" && abs((meta.duration ?? 0) - 1) < 0.1)258        #expect(VideoExportPreset.hevc1080.isReencoded && !VideoExportPreset.original.isReencoded)259    }260}261262@Suite struct VideoRecorderTests {263    @Test(arguments: VideoCodec.allCases) func recordsAPlayableMovie(codec: VideoCodec) async throws {264        let url = Fixture.tempDirectory().appendingPathComponent("movie.mov")265        let result = try await MediaFixture.recordMovie(to: url, codec: codec, frames: 45)266        #expect(result.frameCount == 45 && result.droppedFrames == 0 && result.fileSize > 5_000)267        #expect(abs(result.duration - 1.5) < 0.05)268        let asset = AVURLAsset(url: url)269        let tracks = try await asset.loadTracks(withMediaType: .video)270        let track = try #require(tracks.first)271        let descriptions = try await track.load(.formatDescriptions)272        let description = try #require(descriptions.first)273        #expect(MetadataInspector.codecName(CMFormatDescriptionGetMediaSubType(description)) == (codec == .proRes422 ? "Apple ProRes 422" : codec.title))274        // Decode a frame from the middle: the file is not just a container, the pictures are there.275        let generator = AVAssetImageGenerator(asset: asset)276        generator.requestedTimeToleranceBefore = .zero; generator.requestedTimeToleranceAfter = .zero277        let frame = try await generator.image(at: CMTime(seconds: 0.7, preferredTimescale: 600)).image278        #expect(frame.width == 320 && frame.height == 180)279        let means = Fixture.means(frame)280        #expect(means.r > 20 && means.r < 235)281    }282283    @Test func timeLapseRetimesFramesToThePlaybackRate() async throws {284        let url = Fixture.tempDirectory().appendingPathComponent("lapse.mov")285        // 60 frames captured "one per second" play back at 30 fps: a 2-second movie.286        let result = try await MediaFixture.recordMovie(to: url, codec: .hevc, frames: 60, fps: 1, timeLapse: 30)287        #expect(result.frameCount == 60 && abs(result.duration - 2.0) < 0.05)288        let meta = try #require(await MetadataInspector.readVideo(url: url))289        #expect(abs((meta.frameRate ?? 0) - 30) < 1 && meta.hasAudio == false)290    }291292    @Test func recordsAudioAlongsideVideo() async throws {293        let url = Fixture.tempDirectory().appendingPathComponent("av.mov")294        var configuration = VideoRecorderConfiguration(url: url, width: 320, height: 180, codec: .h264, frameRate: 30)295        configuration.audio = true; configuration.audioSampleRate = 44_100296        let recorder = try VideoRecorder(configuration: configuration)297        let scene = try #require(SyntheticScene(width: 320, height: 180))298        var format = AudioStreamBasicDescription(mSampleRate: 44_100, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked,299                                                 mBytesPerPacket: 2, mFramesPerPacket: 1, mBytesPerFrame: 2, mChannelsPerFrame: 1, mBitsPerChannel: 16, mReserved: 0)300        var description: CMAudioFormatDescription?301        CMAudioFormatDescriptionCreate(allocator: nil, asbd: &format, layoutSize: 0, layout: nil, magicCookieSize: 0, magicCookie: nil, extensions: nil, formatDescriptionOut: &description)302        for i in 0..<30 {303            let time = CMTime(value: CMTimeValue(i), timescale: 30)304            for _ in 0..<400 where !recorder.isReadyForVideo { try await Task.sleep(for: .milliseconds(5)) }305            recorder.appendVideo(scene.render(time: Double(i) / 30)!, time: time)306            // 1470 samples of a 440 Hz tone per video frame.307            var samples = (0..<1470).map { n in Int16(sin(Double(i * 1470 + n) * 2 * .pi * 440 / 44_100) * 12_000) }308            var block: CMBlockBuffer?309            CMBlockBufferCreateWithMemoryBlock(allocator: nil, memoryBlock: nil, blockLength: 2940, blockAllocator: nil, customBlockSource: nil, offsetToData: 0, dataLength: 2940, flags: 0, blockBufferOut: &block)310            CMBlockBufferReplaceDataBytes(with: &samples, blockBuffer: block!, offsetIntoDestination: 0, dataLength: 2940)311            var sample: CMSampleBuffer?312            CMAudioSampleBufferCreateReadyWithPacketDescriptions(allocator: nil, dataBuffer: block!, formatDescription: description!, sampleCount: 1470,313                                                                 presentationTimeStamp: time, packetDescriptions: nil, sampleBufferOut: &sample)314            recorder.appendAudio(sample!)315        }316        _ = try await recorder.finish()317        let meta = try #require(await MetadataInspector.readVideo(url: url))318        #expect(meta.hasAudio == true)319    }320321    @Test func outOfOrderFramesAreCountedAsDropped() async throws {322        let url = Fixture.tempDirectory().appendingPathComponent("drop.mov")323        var configuration = VideoRecorderConfiguration(url: url, width: 320, height: 180, codec: .h264, frameRate: 30)324        configuration.audio = false325        let recorder = try VideoRecorder(configuration: configuration)326        let frame = Fixture.textured(width: 320, height: 180)327        #expect(recorder.appendVideo(frame, time: CMTime(value: 10, timescale: 30)))328        #expect(!recorder.appendVideo(frame, time: CMTime(value: 10, timescale: 30)))329        #expect(!recorder.appendVideo(frame, time: CMTime(value: 5, timescale: 30)))330        #expect(recorder.droppedFrames == 2 && recorder.frameCount == 1)331        let result = try await recorder.finish()332        #expect(result.droppedFrames == 2)333    }334335    @Test func finishingWithoutFramesFailsAndLeavesNoFile() async throws {336        let url = Fixture.tempDirectory().appendingPathComponent("empty.mov")337        var configuration = VideoRecorderConfiguration(url: url, width: 320, height: 180, codec: .h264, frameRate: 30)338        configuration.audio = false339        let recorder = try VideoRecorder(configuration: configuration)340        await #expect(throws: VideoRecorder.RecorderError.noFrames) { _ = try await recorder.finish() }341        #expect(!FileManager.default.fileExists(atPath: url.path))342    }343}344345@Suite struct StorageTests {346    @Test func writesAtomicallyWithUniqueNames() throws {347        let storage = try CaptureStorage(root: Fixture.tempDirectory())348        let a = try storage.write(Data("one".utf8), base: "ORIX_X", ext: "heic")349        let b = try storage.write(Data("two".utf8), base: "ORIX_X", ext: "heic")350        #expect(a == "ORIX_X.heic" && b == "ORIX_X-2.heic")351        #expect(try Data(contentsOf: storage.url(for: b)) == Data("two".utf8))352        #expect(try FileManager.default.contentsOfDirectory(atPath: storage.incomingDirectory.path).isEmpty)353        #expect(storage.size(of: a) == 3 && storage.freeSpace() > 0)354        storage.delete(a)355        #expect(!storage.exists(a) && storage.exists(b))356    }357358    @Test func baseNamesSortChronologically() {359        let early = CaptureStorage.baseName(date: Date(timeIntervalSince1970: 1_800_000_000))360        let late = CaptureStorage.baseName(date: Date(timeIntervalSince1970: 1_800_000_000.5))361        #expect(early.hasPrefix("ORIX_20") && early.count == "ORIX_20261120_153012_042".count && early < late)362    }363364    @Test func adoptsMoviesAndFindsInterruptedRecordings() throws {365        let storage = try CaptureStorage(root: Fixture.tempDirectory())366        let movie = storage.incomingURL(ext: "mov")367        try Data(repeating: 1, count: 2048).write(to: movie)368        #expect(storage.interruptedRecordings().count == 1)369        let name = try storage.adopt(movie, base: "ORIX_M")370        #expect(name == "ORIX_M.mov" && storage.exists(name) && storage.interruptedRecordings().isEmpty)371        #expect(throws: CaptureStorage.StorageError.missing("gone.mov")) { try storage.adopt(storage.incomingDirectory.appendingPathComponent("gone.mov")) }372    }373374    @Test func thumbnailsAreCreatedOnceAndRespectOrientation() throws {375        let storage = try CaptureStorage(root: Fixture.tempDirectory())376        let source = MediaFixture.photoWithMetadata(in: storage.mediaDirectory, name: "p.jpg")      // orientation 6: displayed as portrait377        let thumbnail = try #require(storage.makeImageThumbnail(for: source.lastPathComponent, maxPixel: 120))378        let meta = try #require(MetadataInspector.readImage(url: thumbnail))379        #expect(meta.pixelHeight == 120 && meta.pixelWidth == 90)380        #expect(storage.makeImageThumbnail(for: "p.jpg") == thumbnail)381        #expect(storage.makeImageThumbnail(for: "absent.jpg") == nil)382    }383}384385@MainActor @Suite struct MediaLibraryTests {386    func makeLibrary() throws -> MediaLibrary { try MediaLibrary(storage: try CaptureStorage(root: Fixture.tempDirectory()), inMemory: true) }387388    func addPhoto(_ library: MediaLibrary, _ base: String, kind: MediaKind = .photo, summary: String = "", date: Date = Date(), bytes: Int = 100) throws -> MediaItem {389        let name = try library.storage.write(Data(repeating: 7, count: bytes), base: base, ext: kind.isVideo ? "mov" : (kind.isRAW ? "dng" : "heic"))390        return library.add(MediaItem(createdAt: date, kind: kind, fileName: name, pixelWidth: 4032, pixelHeight: 3024, captureSummary: summary))391    }392393    @Test func addFilterSearchSort() throws {394        let library = try makeLibrary()395        let t = Date(timeIntervalSince1970: 1_800_000_000)396        let photo = try addPhoto(library, "A", summary: "Wide 1× ISO 80 1/120 Auto", date: t, bytes: 300)397        let raw = try addPhoto(library, "B", kind: .proRAW, summary: "Telephoto 5× ISO 400 Pro", date: t.addingTimeInterval(10), bytes: 900)398        let video = try addPhoto(library, "C", kind: .video, summary: "4K 30 HEVC", date: t.addingTimeInterval(20), bytes: 500)399        let trails = try addPhoto(library, "D", kind: .lightTrails, summary: "Creative 120 frames", date: t.addingTimeInterval(30))400        #expect(photo.byteSize == 300)401        #expect(library.items().map(\.fileName) == ["D.heic", "C.mov", "B.dng", "A.heic"])402        #expect(library.items(sort: .oldest).first?.id == photo.id)403        #expect(library.items(sort: .largest).first?.id == raw.id)404        #expect(library.items(filter: .videos).map(\.id) == [video.id])405        #expect(library.items(filter: .raw).map(\.id) == [raw.id])406        #expect(library.items(filter: .computational).map(\.id) == [trails.id])407        #expect(library.items(filter: .photos).count == 3)408        #expect(library.items(search: "telephoto iso").map(\.id) == [raw.id])409        #expect(library.items(search: "hevc").map(\.id) == [video.id])410        #expect(library.items(search: "nothing-matches").isEmpty)411        #expect(library.totalBytes == 300 + 900 + 500 + 100)412    }413414    @Test func favouritesRecipesAndAlbums() throws {415        let library = try makeLibrary()416        let a = try addPhoto(library, "A"), b = try addPhoto(library, "B")417        library.toggleFavorite(a)418        #expect(library.items(filter: .favorites).map(\.id) == [a.id])419        var recipe = EditRecipe(); recipe.exposure = 0.5420        library.setRecipe(recipe, for: b)421        #expect(library.items(filter: .edited).map(\.id) == [b.id] && library.item(id: b.id)?.recipe == recipe)422        library.setRecipe(EditRecipe(), for: b)                  // identity recipe = no edits423        #expect(!b.hasEdits)424        let album = library.createAlbum(named: "  Trip ")425        library.add(a, to: album); library.add(a, to: album); library.add(b, to: album)426        #expect(album.name == "Trip" && album.items.count == 2 && library.items(album: album).count == 2)427        library.remove(a, from: album)428        #expect(album.items.map(\.id) == [b.id])429        library.delete(album)430        #expect(library.albums().isEmpty && library.allItems().count == 2)431    }432433    @Test func deleteRemovesFilesAndRow() throws {434        let library = try makeLibrary()435        let item = try addPhoto(library, "A", kind: .raw)436        item.companionFileName = try library.storage.write(Data("x".utf8), base: "A", ext: "heic")437        library.save()438        library.delete(item)439        #expect(library.allItems().isEmpty && !library.storage.exists("A.dng") && !library.storage.exists("A.heic"))440    }441442    @Test func reconcileRecoversFilesTheIndexLost() throws {443        let library = try makeLibrary()444        _ = try addPhoto(library, "Known")445        let orphanPhoto = MediaFixture.photoWithMetadata(in: library.storage.mediaDirectory, name: "ORIX_orphan.jpg")446        try Data(repeating: 1, count: 64).write(to: library.storage.url(for: "ORIX_orphan.mov"))447        let recovered = library.reconcile()448        #expect(Set(recovered.map(\.fileName)) == ["ORIX_orphan.jpg", "ORIX_orphan.mov"])449        #expect(recovered.first { $0.fileName == orphanPhoto.lastPathComponent }?.pixelWidth == 320)450        #expect(recovered.first { $0.fileName == "ORIX_orphan.mov" }?.kind == .video)451        #expect(library.reconcile().isEmpty && library.allItems().count == 3)452        try FileManager.default.removeItem(at: library.storage.url(for: "Known.heic"))453        #expect(library.itemsMissingFiles().map(\.fileName) == ["Known.heic"])454    }455456    @Test func persistsAcrossReopen() throws {457        let storage = try CaptureStorage(root: Fixture.tempDirectory())458        do {459            let library = try MediaLibrary(storage: storage)460            let name = try storage.write(Data("p".utf8), base: "P", ext: "heic")461            let item = library.add(MediaItem(kind: .photo, fileName: name, title: "Keeper"))462            library.toggleFavorite(item)463        }464        let reopened = try MediaLibrary(storage: storage)465        #expect(reopened.allItems().map(\.title) == ["Keeper"] && reopened.allItems().first?.isFavorite == true)466    }467468    @Test func duplicateGroupsUseVisualHashes() throws {469        let library = try makeLibrary()470        let base = Fixture.image(Fixture.textured())471        let near = Fixture.image(Fixture.noisy(Fixture.textured(), sigma: 2, seed: 4))472        let other = Fixture.image(Fixture.natural())473        let hashes = [base, near, other].map { DuplicateDetector.differenceHash($0)! }474        #expect(DuplicateDetector.distance(hashes[0], hashes[1]) <= 4)475        #expect(DuplicateDetector.distance(hashes[0], hashes[2]) > 10)476        for (i, hash) in hashes.enumerated() {477            let item = try addPhoto(library, "H\(i)", date: Date(timeIntervalSince1970: Double(i)))478            item.visualHash = Int64(bitPattern: hash)479        }480        library.save()481        let groups = library.duplicateGroups()482        #expect(groups.count == 1 && groups[0].map(\.fileName) == ["H0.heic", "H1.heic"])483    }484}485486@Suite struct CaptureMathTests {487    @Test func shutterAndISOLabels() {488        #expect(ExposureMath.shutterLabel(1.0 / 250) == "1/250")489        #expect(ExposureMath.shutterLabel(1.0 / 249.2) == "1/250")490        #expect(ExposureMath.shutterLabel(1.0 / 49) == "1/50")491        #expect(ExposureMath.shutterLabel(1.0 / 48) == "1/48")      // the 180° shutter at 24 fps is shown as it is492        #expect(ExposureMath.shutterLabel(0.5) == "0.5″" && ExposureMath.shutterLabel(1) == "1″" && ExposureMath.shutterLabel(0) == "–")493        #expect(ExposureMath.isoLabel(399.6) == "400")494    }495496    @Test func stopsStayInsideTheDeviceRange() {497        let iso = ExposureMath.stops(ExposureMath.isoStops, min: 34, max: 3264)498        #expect(iso.first == 34 && iso.last == 3264 && iso[1] == 40 && iso.allSatisfy { $0 >= 34 && $0 <= 3264 })499        #expect(iso == iso.sorted())500        let shutter = ExposureMath.stops(ExposureMath.shutterStops, min: 1.0 / 76923, max: 1.0)501        #expect(shutter.first == 1.0 / 76923 && shutter.last == 1.0 && shutter == shutter.sorted())502    }503504    @Test func exposureValueAndShutterAngle() {505        #expect(abs(ExposureMath.ev100(aperture: 16, duration: 1.0 / 100, iso: 100) - 14.64) < 0.01)     // sunny 16506        #expect(abs(ExposureMath.ev100(aperture: 16, duration: 1.0 / 100, iso: 200) - 13.64) < 0.01)507        #expect(ExposureMath.shutter180(frameRate: 24) == 1.0 / 48)508        #expect(abs(ExposureMath.shutterAngle(duration: 1.0 / 48, frameRate: 24) - 180) < 1e-9)509        #expect(ExposureMath.shutterAngle(duration: 1, frameRate: 30) == 360)510    }511512    @Test func blurRiskFollowsTheReciprocalRule() {513        #expect(ExposureMath.blurRisk(duration: 1.0 / 60, focalLength35mm: 24) == .low)514        #expect(ExposureMath.blurRisk(duration: 1.0 / 15, focalLength35mm: 24) == .elevated)515        #expect(ExposureMath.blurRisk(duration: 1.0 / 30, focalLength35mm: 120) == .elevated)516        #expect(ExposureMath.blurRisk(duration: 0.5, focalLength35mm: 24) == .high)517    }518519    @Test func storageEstimates() {520        // HEVC 4K30 at 0.13 bit/pixel/frame = 32.3 Mbit/s = 4.04 MB/s (+ audio).521        let rate = ExposureMath.bytesPerSecond(codec: .hevc, width: 3840, height: 2160, frameRate: 30, audio: true)522        #expect(abs(rate - (3840 * 2160 * 30 * 0.13 / 8 + 12_000)) < 1)523        let time = ExposureMath.remainingRecordingTime(freeBytes: 10_500_000_000, codec: .hevc, width: 3840, height: 2160, frameRate: 30, audio: true)524        #expect(abs(time - 10_000_000_000 / rate) < 1e-6)525        #expect(ExposureMath.remainingRecordingTime(freeBytes: 100, codec: .h264, width: 1920, height: 1080, frameRate: 30, audio: false) == 0)526        #expect(VideoCodec.proRes422.bitRate(width: 3840, height: 2160, frameRate: 30) > 500_000_000)527        #expect(ExposureMath.durationLabel(45) == "45 s" && ExposureMath.durationLabel(725) == "12 min" && ExposureMath.durationLabel(3900) == "1 h 05")528        #expect(ExposureMath.timecode(62) == "01:02" && ExposureMath.timecode(3723) == "1:02:03")529    }530531    @Test func sceneAssessmentFlagsRealConditions() throws {532        let bright = try #require(HistogramProcessor.compute(Fixture.solid(255, 255, 255)))533        let dark = try #require(HistogramProcessor.compute(Fixture.solid(4, 4, 4)))534        let mid = try #require(HistogramProcessor.compute(Fixture.ramp()))535        #expect(SceneAssessment.assess(histogram: bright, focus: nil, exposureDuration: nil, focalLength35mm: nil, rollDegrees: nil).hints == [.highlightsClipped])536        #expect(SceneAssessment.assess(histogram: dark, focus: nil, exposureDuration: nil, focalLength35mm: nil, rollDegrees: nil).hints.contains(.lowLight))537        let hints = SceneAssessment.assess(histogram: mid, focus: FocusMetrics(sharpness: 2, peakingCoverage: 0), exposureDuration: 1.0 / 8, focalLength35mm: 24, rollDegrees: 3).hints538        #expect(hints == [.motionBlurRisk, .lowDetail, .tilted])539        #expect(SceneAssessment.assess(histogram: mid, focus: FocusMetrics(sharpness: 90, peakingCoverage: 0.1), exposureDuration: 1.0 / 250, focalLength35mm: 24, rollDegrees: 0.2).hints.isEmpty)540    }541542    @Test func whiteBalanceGainsAreClampedWithoutChangingRatiosWhenPossible() {543        let gains = WhiteBalanceGains(red: 0.8, green: 0.5, blue: 1.2).clamped(maxGain: 4)544        #expect(abs(gains.green - 1) < 1e-9 && abs(gains.red - 1.6) < 1e-9 && abs(gains.blue - 2.4) < 1e-9)545        let capped = WhiteBalanceGains(red: 10, green: 1, blue: 1).clamped(maxGain: 4)546        #expect(capped.red == 4 && capped.green == 1)547        #expect(Set(WhiteBalancePreset.builtIn.map(\.id)).count == 5)548    }549550    @Test func colourCastFromChannelMeans() throws {551        let warm = ColorCast(histogram: try #require(HistogramProcessor.compute(Fixture.solid(180, 120, 80))))552        #expect(abs(warm.redOverGreen - 1.5) < 0.01 && abs(warm.blueOverGreen - 2.0 / 3) < 0.01 && warm.warmth > 0.9)553        let neutral = ColorCast(histogram: try #require(HistogramProcessor.compute(Fixture.solid(100, 100, 100))))554        #expect(abs(neutral.warmth) < 1e-9)555    }556}557558@Suite struct CompositionTests {559    @Test func gridLines() {560        #expect(GridOverlay.none.lines.isEmpty && GridOverlay.thirds.lines.count == 4 && GridOverlay.square.lines.count == 6)561        #expect(abs(GridOverlay.thirds.lines[0].start.x - 1.0 / 3) < 1e-9)562        #expect(abs(GridOverlay.golden.lines[1].start.x - 0.618) < 1e-3 && abs(GridOverlay.golden.lines[0].start.x - 0.382) < 1e-3)563        for grid in GridOverlay.allCases { for line in grid.lines { #expect((0...1).contains(line.start.x) && (0...1).contains(line.end.y)) } }564    }565566    @Test func aspectGuidesFitInsideTheFrame() {567        let frame = 4.0 / 3568        #expect(AspectGuide.native.rect(frameAspect: frame) == CGRect(x: 0, y: 0, width: 1, height: 1))569        let wide = AspectGuide.r16x9.rect(frameAspect: frame)570        #expect(wide.width == 1 && abs(wide.height - 0.75) < 1e-9 && abs(wide.minY - 0.125) < 1e-9)571        let square = AspectGuide.r1x1.rect(frameAspect: frame)572        #expect(square.height == 1 && abs(square.width - 0.75) < 1e-9)573        // Portrait 3:4 frame: "16:9" means a tall 9:16 rectangle.574        let tall = AspectGuide.r16x9.rect(frameAspect: 3.0 / 4, portrait: true)575        #expect(tall.height == 1 && abs(tall.width - 0.75) < 1e-9)576        for guide in AspectGuide.allCases {577            let r = guide.rect(frameAspect: frame)578            #expect(r.minX >= 0 && r.minY >= 0 && r.maxX <= 1 + 1e-9 && r.maxY <= 1 + 1e-9)579            if let ratio = guide.ratio { #expect(abs(r.width * frame / r.height - ratio) < 1e-9) }580        }581        #expect(SafeFraming.titleSafe.width == 0.9 && SafeFraming.actionSafe.contains(SafeFraming.titleSafe))582    }583584    @Test func levelFromGravity() {585        let upright = LevelReading(gravityX: 0, y: -1, z: 0)586        #expect(abs(upright.roll) < 1e-9 && abs(upright.pitch) < 1e-9 && upright.isLevel() && !upright.isFlat)587        let tilted = LevelReading(gravityX: sin(5 * .pi / 180), y: -cos(5 * .pi / 180), z: 0)588        #expect(abs(tilted.roll - 5) < 1e-6 && !tilted.isLevel())589        let landscape = LevelReading(gravityX: -1, y: 0, z: 0)590        #expect(abs(landscape.roll) < 1e-6 && landscape.isLevel())591        let landscapeTilted = LevelReading(gravityX: -cos(3 * .pi / 180), y: -sin(3 * .pi / 180), z: 0)592        #expect(abs(abs(landscapeTilted.roll) - 3) < 1e-6)593        let flat = LevelReading(gravityX: 0, y: 0, z: -1)594        #expect(flat.isFlat && !flat.isLevel() && abs(flat.pitch + 90) < 1e-6)595    }596}597598@Suite struct CaptureGeometryTests {599    @Test func sensorAndDisplayPointsAreInverse() {600        let p = CGPoint(x: 0.2, y: 0.7)601        for rotation in [0.0, 90, 180, 270] { for mirrored in [false, true] {602            let sensor = CaptureGeometry.sensorPoint(displayed: p, rotationDegrees: rotation, mirrored: mirrored)603            let back = CaptureGeometry.displayedPoint(sensor: sensor, rotationDegrees: rotation, mirrored: mirrored)604            #expect(abs(back.x - p.x) < 1e-9 && abs(back.y - p.y) < 1e-9)605        } }606    }607608    @Test func portraitTapMapsLikeTheRenderer() throws {609        // Back camera in portrait: display = sensor rotated 90° clockwise. The top-right of the screen is the sensor's top-left.610        let sensor = CaptureGeometry.sensorPoint(displayed: CGPoint(x: 0.9, y: 0.1), rotationDegrees: 90, mirrored: false)611        #expect(abs(sensor.x - 0.1) < 1e-9 && abs(sensor.y - 0.1) < 1e-9)612        // Same check against pixels: mark the sensor's top-left red, render rotated, the red lands top-right.613        let renderer = try #require(MonitorRenderer())614        let buffer = PixelBuffers.makeBGRA(width: 64, height: 32)!615        PixelBuffers.fill(buffer) { x, y in (x < 16 && y < 8) ? (255, 0, 0) : (0, 0, 0) }616        var settings = MonitorSettings(); settings.rotationDegrees = 90617        let out = try #require(renderer.renderOffscreen(pixelBuffer: buffer, settings: settings, width: 32, height: 64))618        let displayed = CaptureGeometry.displayedPoint(sensor: CGPoint(x: 0.1, y: 0.1), rotationDegrees: 90, mirrored: false)619        let x = Int(displayed.x * 32), y = Int(displayed.y * 64)620        #expect(out[(y * 32 + x) * 4 + 2] > 200)621        // Mirrored (front camera) flips the displayed x.622        settings.mirrored = true623        let mirrored = try #require(renderer.renderOffscreen(pixelBuffer: buffer, settings: settings, width: 32, height: 64))624        let m = CaptureGeometry.displayedPoint(sensor: CGPoint(x: 0.1, y: 0.1), rotationDegrees: 90, mirrored: true)625        #expect(mirrored[(Int(m.y * 64) * 32 + Int(m.x * 32)) * 4 + 2] > 200 && m.x < 0.5)626    }627628    @Test func orientationTagsAndSizes() {629        #expect([0.0, 90, 180, 270].map { CaptureGeometry.exifOrientation(rotationDegrees: $0) } == [1, 6, 3, 8])630        #expect(CaptureGeometry.displayedSize(width: 1920, height: 1080, rotationDegrees: 90) == CGSize(width: 1080, height: 1920))631        #expect(CaptureGeometry.movieTransform(rotationDegrees: 0) == .identity)632        #expect(VideoCodec.h264.isEncoderAvailable && VideoCodec.hevc.isEncoderAvailable)633    }634}635636@Suite struct CapabilityTests {637    @Test func focalLengthFromFieldOfView() {638        #expect(abs(LensDescriptor.focalLength35(fieldOfView: 73.7) - 24) < 0.1)639        #expect(abs(LensDescriptor.focalLength35(fieldOfView: 108) - 13.1) < 0.1)640        #expect(LensDescriptor.focalLength35(fieldOfView: 0) == 0)641    }642643    @Test func unavailableFeaturesAreExplained() {644        var caps = CameraCapabilities(lens: LensDescriptor(id: "x", position: .back, kind: "wide", label: "1×", fieldOfView: 73.7, focalLength35mm: 24, aperture: 1.78))645        for feature in CameraCapabilities.Feature.allCases { #expect(caps.explanation(for: feature) != nil) }646        caps.supportsBayerRAW = true; caps.supportsProRAW = true; caps.supportsManualFocus = true; caps.supportsManualExposure = true647        caps.hasFlash = true; caps.videoCodecs = [.h264, .hevc, .proRes422]; caps.maxBracketCount = 3; caps.supportsWhiteBalanceLock = true648        for feature in CameraCapabilities.Feature.allCases { #expect(caps.explanation(for: feature) == nil) }649    }650651    @Test func formatsGroupByResolution() {652        var caps = CameraCapabilities(lens: LensDescriptor(id: "x", position: .back, kind: "wide", label: "1×", fieldOfView: 70, focalLength35mm: 26, aperture: 1.8))653        caps.videoFormats = [.init(width: 1920, height: 1080, frameRate: 30), .init(width: 3840, height: 2160, frameRate: 60), .init(width: 1920, height: 1080, frameRate: 240),654                             .init(width: 3840, height: 2160, frameRate: 24), .init(width: 1920, height: 1080, frameRate: 60)]655        #expect(caps.resolutions.map(\.resolutionLabel) == ["4K", "1080p"])656        #expect(caps.frameRates(width: 1920, height: 1080) == [30, 60, 240])657        #expect(VideoFormatOption(width: 1920, height: 1080, frameRate: 240).isSlowMotion && !VideoFormatOption(width: 1920, height: 1080, frameRate: 60).isSlowMotion)658    }659}660
Files main
Menu

Theme