SPB Git

Repository Public

MediaImporterTests.swift 26.9 KB 558 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Tests/ORIXLibraryTests/MediaImporterTests.swift10// Description      : Tests of the importer on real generated audio files:11//                    format support, scanning, metadata, validation, bookmarks,12//                    missing media.13// Module           : ORIXLibraryTests14// Repository       : https://git.spboucher.ai/orix-dj15// 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          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import AVFoundation91import CoreGraphics92import Foundation93import ImageIO94import Testing95@testable import ORIXLibrary9697/// A solid-colour PNG, used as embedded artwork.98func makePNG(width: Int, height: Int) throws -> Data {99    let context = try #require(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,100                                         space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))101    context.setFillColor(red: 0.9, green: 0.3, blue: 0.1, alpha: 1)102    context.fill(CGRect(x: 0, y: 0, width: width, height: height))103    let image = try #require(context.makeImage())104    let output = NSMutableData()105    let destination = try #require(CGImageDestinationCreateWithData(output, "public.png" as CFString, 1, nil))106    CGImageDestinationAddImage(destination, image, nil)107    #expect(CGImageDestinationFinalize(destination))108    return output as Data109}110111/// Re-muxes an M4A with tags through AVAssetExportSession (AVAudioFile cannot write tags).112func writeTaggedM4A(from source: URL, to destination: URL, artwork: Data) async throws {113    func item(_ identifier: AVMetadataIdentifier, _ value: any NSCopying & NSObjectProtocol, dataType: String? = nil) -> AVMetadataItem {114        let item = AVMutableMetadataItem()115        item.identifier = identifier116        item.value = value117        item.extendedLanguageTag = "und"118        if let dataType { item.dataType = dataType }119        return item120    }121    let asset = AVURLAsset(url: source)122    let session = try #require(AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough))123    session.metadata = [124        item(.iTunesMetadataSongName, "Tagged Title" as NSString),125        item(.iTunesMetadataArtist, "Tagged Artíst" as NSString),126        item(.iTunesMetadataAlbum, "Tagged Album" as NSString),127        item(.iTunesMetadataUserGenre, "Deep House" as NSString),128        item(.iTunesMetadataReleaseDate, "2019-06-21" as NSString),129        item(.iTunesMetadataUserComment, "Recorded for tests" as NSString),130        item(.iTunesMetadataBeatsPerMin, NSNumber(value: 124), dataType: kCMMetadataBaseDataType_UInt16 as String),131        item(.iTunesMetadataCoverArt, artwork as NSData, dataType: kCMMetadataBaseDataType_PNG as String),132    ]133    try await session.export(to: destination, as: .m4a)134}135136@Suite struct MediaImporterFormatTests {137    /// Documents, on the macOS running the tests, which supported formats can be written and opened by AVAudioFile.138    @Test func everySupportedExtensionOpensWithAVAudioFile() async throws {139        let temp = TempDirectory()140        let importer = MediaImporter()141        var report: [String] = []142        var opened = Set<String>()143144        for fixture in AudioFixture.allCases {145            let url = temp.file("fixture-\(fixture.rawValue).\(fixture.fileExtension)")146            do {147                try fixture.write(to: url)148            } catch {149                report.append("\(fixture.rawValue) (.\(fixture.fileExtension)): AVAudioFile cannot WRITE it here (\(error.localizedDescription))")150                continue151            }152            do {153                let file = try AVAudioFile(forReading: url)154                let metadata = try await importer.readMetadata(url: url)155                report.append("\(fixture.rawValue) (.\(fixture.fileExtension)): written + opened, \(Int(file.fileFormat.sampleRate)) Hz, "156                    + "\(file.fileFormat.channelCount) ch, \(file.length) frames, importer duration \(String(format: "%.3f", metadata.duration)) s, "157                    + "bit rate \(metadata.bitRate / 1000) kbit/s")158                opened.insert(fixture.rawValue)159                #expect(file.length > 0)160                #expect(metadata.sampleRate == 44_100)161                #expect(metadata.channels == 2)162                #expect(abs(metadata.duration - 0.5) < 0.1)163                #expect(metadata.format == fixture.fileExtension)164            } catch {165                report.append("\(fixture.rawValue) (.\(fixture.fileExtension)): written but NOT readable (\(error))")166            }167        }168169        // .aif is the same container as .aiff.170        let aif = temp.file("fixture.aif")171        try AudioFixture.aiff.write(to: aif)172        #expect((try AVAudioFile(forReading: aif)).length > 0)173        #expect(try await importer.readMetadata(url: aif).format == "aif")174        report.append("aif (.aif): written + opened")175176        // MP3: macOS has a decoder but no encoder, so the stream is built by hand (silent frames).177        let mp3 = temp.file("fixture.mp3")178        try writeSilentMP3(to: mp3)179        var mp3Opened = false180        do {181            let file = try AVAudioFile(forReading: mp3)182            let metadata = try await importer.readMetadata(url: mp3)183            mp3Opened = file.length > 0184            report.append("mp3 (.mp3, hand-built silent frames): opened, \(Int(file.fileFormat.sampleRate)) Hz, \(file.fileFormat.channelCount) ch, "185                + "\(file.length) frames, importer duration \(String(format: "%.3f", metadata.duration)) s")186            #expect(metadata.sampleRate == 44_100)187            #expect(metadata.channels == 2)188        } catch {189            report.append("mp3 (.mp3, hand-built silent frames): NOT readable (\(error))")190        }191192        print("[ORIXLibrary format support on \(ProcessInfo.processInfo.operatingSystemVersionString)]")193        for line in report { print("  " + line) }194195        // What this macOS is known to support; a regression here means the importer's promise is broken.196        for required in ["wav", "aiff", "caf", "m4aAAC", "m4aALAC", "flac"] {197            #expect(opened.contains(required), "\(required) should be writable and readable with AVAudioFile")198        }199        #expect(mp3Opened)200        #expect(MediaImporter.supportedExtensions == ["mp3", "wav", "aif", "aiff", "flac", "m4a", "aac", "caf"])201    }202}203204@Suite struct MediaImporterTests {205    @Test func scanSkipsHiddenInvalidAndPackageContent() throws {206        let temp = TempDirectory()207        let root = temp.directory("Music")208        let sub = temp.directory("Music/House/Deep")209        let hidden = temp.directory("Music/.hidden-folder")210        let package = temp.directory("Music/Project.app/Contents")211        try AudioFixture.wav.write(to: root.appendingPathComponent("b.wav"))212        try AudioFixture.aiff.write(to: root.appendingPathComponent("a.AIFF"))213        try AudioFixture.wav.write(to: sub.appendingPathComponent("deep.wav"))214        try AudioFixture.wav.write(to: root.appendingPathComponent(".hidden.wav"))215        try AudioFixture.wav.write(to: hidden.appendingPathComponent("inside-hidden.wav"))216        try AudioFixture.wav.write(to: package.appendingPathComponent("inside-package.wav"))217        try Data("notes".utf8).write(to: root.appendingPathComponent("notes.txt"))218        try Data("cover".utf8).write(to: root.appendingPathComponent("cover.jpg"))219        try Data().write(to: root.appendingPathComponent("empty.mp3")) // scan is by extension; validation rejects it later220221        let importer = MediaImporter()222        func names(_ urls: [URL]) -> [String] { urls.map(\.lastPathComponent) }223        #expect(names(importer.scan(urls: [root], recursive: true)) == ["a.AIFF", "b.wav", "empty.mp3", "deep.wav"])224        #expect(names(importer.scan(urls: [root], recursive: false)) == ["a.AIFF", "b.wav", "empty.mp3"])225        // Files and folders can be mixed; duplicates collapse; hidden or unsupported files given directly are skipped.226        let mixed = importer.scan(urls: [root.appendingPathComponent("b.wav"), sub, root.appendingPathComponent("b.wav"),227                                         root.appendingPathComponent(".hidden.wav"), root.appendingPathComponent("notes.txt"),228                                         temp.file("does-not-exist.wav")])229        #expect(names(mixed) == ["b.wav", "deep.wav"])230        #expect(importer.scan(urls: [root], isCancelled: { true }).isEmpty)231    }232233    @Test func scanStopsWhenTheTaskIsCancelled() async throws {234        let temp = TempDirectory()235        let root = temp.directory("Many")236        for index in 0..<50 { try Data([1]).write(to: root.appendingPathComponent("f\(index).wav")) }237        let task = Task { () -> Int in238            while !Task.isCancelled { await Task.yield() }239            return MediaImporter().scan(urls: [root]).count240        }241        task.cancel()242        #expect(await task.value == 0)243        #expect(MediaImporter().scan(urls: [root]).count == 50)244    }245246    @Test func metadataFallsBackToTheFileName() async throws {247        let temp = TempDirectory()248        let importer = MediaImporter()249        let split = temp.file("Daft Punk - Around the World.wav")250        let plain = temp.file("untitled_take_3.aiff")251        try AudioFixture.wav.write(to: split, seconds: 1.0)252        try AudioFixture.aiff.write(to: plain)253254        let first = try await importer.readMetadata(url: split)255        #expect(first.artist == "Daft Punk")256        #expect(first.title == "Around the World")257        #expect(abs(first.duration - 1.0) < 0.01)258        #expect(first.sampleRate == 44_100)259        #expect(first.channels == 2)260        #expect(first.bitRate > 1_300_000 && first.bitRate < 1_600_000) // 16-bit stereo PCM is 1 411 kbit/s plus header overhead261        #expect(first.format == "wav")262        #expect(first.fileSize == Int64(try Data(contentsOf: split).count))263        #expect(first.bookmark != nil)264        #expect(first.artwork == nil)265        #expect(first.bpm == nil)266267        let second = try await importer.readMetadata(url: plain)268        #expect(second.title == "untitled_take_3")269        #expect(second.artist == "")270271        #expect(MediaImporter.splitFileName("A - B - C").artist == "A")272        #expect(MediaImporter.splitFileName("A - B - C").title == "B - C")273        #expect(MediaImporter.splitFileName("NoSeparator-Here").artist == nil)274        #expect(MediaImporter.splitFileName(" - Title").title == "- Title")275    }276277    @Test func tagsAndArtworkAreReadFromATaggedM4A() async throws {278        let temp = TempDirectory()279        let bare = temp.file("bare.m4a")280        let tagged = temp.file("Wrong Artist - Wrong Title.m4a")281        try AudioFixture.m4aAAC.write(to: bare, seconds: 1.0)282        let png = try makePNG(width: 900, height: 600)283        try await writeTaggedM4A(from: bare, to: tagged, artwork: png)284285        let metadata = try await MediaImporter().readMetadata(url: tagged)286        #expect(metadata.title == "Tagged Title") // tags win over the file name287        #expect(metadata.artist == "Tagged Artíst")288        #expect(metadata.album == "Tagged Album")289        #expect(metadata.genre == "Deep House")290        #expect(metadata.year == 2019)291        #expect(metadata.comment == "Recorded for tests")292        #expect(metadata.bpm == 124)293        #expect(metadata.sampleRate == 44_100)294        #expect(metadata.channels == 2)295        #expect(metadata.bitRate > 0)296297        let artwork = try #require(metadata.artwork)298        #expect(artwork.count < png.count || artwork.count < 20_000)299        #expect(artwork.prefix(2) == Data([0xFF, 0xD8])) // JPEG300        let source = try #require(CGImageSourceCreateWithData(artwork as CFData, nil))301        let image = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil))302        #expect(max(image.width, image.height) == 300)303        #expect(image.height == 200) // aspect ratio kept304305        // Import stores the thumbnail next to the track, outside list queries.306        let store = try LibraryStore(inMemory: true)307        let summary = await MediaImporter().importFiles([tagged], into: store)308        let track = try #require(summary.imported.first)309        #expect(track.title == "Tagged Title")310        #expect(track.bpm == 124)311        #expect(try store.artwork(for: track.id) == artwork)312    }313314    @Test func thumbnailHelper() throws {315        let small = try makePNG(width: 40, height: 20)316        let thumb = try #require(MediaImporter.thumbnail(from: small))317        let source = try #require(CGImageSourceCreateWithData(thumb as CFData, nil))318        let image = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil))319        #expect(image.width <= 300 && image.height <= 300)320        #expect(MediaImporter.thumbnail(from: Data("not an image".utf8)) == nil)321        #expect(MediaImporter.isCamelotCode("8a"))322        #expect(MediaImporter.isCamelotCode("12B"))323        #expect(!MediaImporter.isCamelotCode("13A"))324        #expect(!MediaImporter.isCamelotCode("Am"))325    }326327    @Test func validationRejectsUnusableFilesWithClearErrors() async throws {328        let temp = TempDirectory()329        let importer = MediaImporter()330        func error(_ url: URL) async -> LibraryError? {331            do {332                _ = try await importer.readMetadata(url: url)333                return nil334            } catch {335                return error as? LibraryError336            }337        }338339        let empty = temp.file("empty.wav")340        try Data().write(to: empty)341        #expect(await error(empty) == .emptyFile(path: empty.path))342343        let text = temp.file("notes.txt")344        try Data("hello".utf8).write(to: text)345        #expect(await error(text) == .unsupportedFormat(path: text.path))346347        let absent = temp.file("absent.flac")348        #expect(await error(absent) == .unreadableFile(path: absent.path, reason: "no such file"))349350        let folder = temp.directory("folder.wav")351        #expect(await error(folder) == .unreadableFile(path: folder.path, reason: "no such file"))352353        for name in ["garbage.wav", "garbage.mp3", "garbage.m4a", "garbage.flac"] {354            let garbage = temp.file(name)355            try Data((0..<4096).map { UInt8(truncatingIfNeeded: $0 &* 13 &+ 5) }).write(to: garbage)356            let failure = await error(garbage)357            guard case let .unreadableFile(path, reason)? = failure else {358                Issue.record("\(name) should be unreadable, got \(String(describing: failure))")359                continue360            }361            #expect(path == garbage.path)362            #expect(!reason.isEmpty)363        }364365        // A WAV header with no samples has a duration of zero.366        let headerOnly = temp.file("header-only.wav")367        try AudioFixture.wav.write(to: headerOnly, seconds: 0)368        if case .unreadableFile? = await error(headerOnly) {} else { Issue.record("a zero-length WAV should be rejected") }369370        let unreadable = temp.file("locked.wav")371        try AudioFixture.wav.write(to: unreadable)372        try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: unreadable.path)373        defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: unreadable.path) }374        if getuid() != 0 {375            #expect(await error(unreadable) == .unreadableFile(path: unreadable.path, reason: "permission denied"))376        }377        #expect(LibraryError.protectedContent(path: "/x.m4a").description.contains("DRM"))378    }379380    @Test func importFolderTreeWithMixedFiles() async throws {381        let temp = TempDirectory()382        let root = temp.directory("Library")383        let nested = temp.directory("Library/Artist/Album")384        try AudioFixture.wav.write(to: root.appendingPathComponent("Moderat - Bad Kingdom.wav"))385        try AudioFixture.aiff.write(to: nested.appendingPathComponent("01 Intro.aiff"))386        try AudioFixture.m4aAAC.write(to: nested.appendingPathComponent("song.m4a"))387        try AudioFixture.flac.write(to: nested.appendingPathComponent("lossless.flac"))388        try AudioFixture.wav.write(to: nested.appendingPathComponent(".hidden.wav"))389        try Data().write(to: root.appendingPathComponent("zero.wav"))390        try Data(repeating: 0x42, count: 2048).write(to: nested.appendingPathComponent("broken.mp3"))391        try Data("x".utf8).write(to: root.appendingPathComponent("readme.txt"))392        let audioBefore = try Data(contentsOf: root.appendingPathComponent("Moderat - Bad Kingdom.wav"))393394        let importer = MediaImporter()395        let store = try LibraryStore(url: temp.file("db/library.sqlite"))396        let files = importer.scan(urls: [root])397        #expect(files.count == 6) // 4 valid + zero.wav + broken.mp3; hidden and .txt never get that far398399        let progress = ProgressRecorder()400        let summary = await importer.importFiles(files, into: store) { progress.record($0) }401        #expect(!summary.cancelled)402        #expect(Set(summary.imported.map(\.title)) == ["Bad Kingdom", "01 Intro", "song", "lossless"])403        #expect(summary.failures.count == 2)404        #expect(summary.failures.contains { $0.error == .emptyFile(path: $0.url.path) && $0.url.lastPathComponent == "zero.wav" })405        #expect(summary.failures.contains {406            if case .unreadableFile = $0.error { return $0.url.lastPathComponent == "broken.mp3" } else { return false }407        })408        #expect(progress.values.map(\.completed) == [1, 2, 3, 4, 5, 6])409        #expect(progress.values.allSatisfy { $0.total == 6 })410411        let stored = try store.tracks()412        #expect(stored.count == 4)413        #expect(stored.first { $0.title == "Bad Kingdom" }?.artist == "Moderat")414        #expect(stored.allSatisfy { $0.duration > 0.4 && $0.sampleRate == 44_100 && $0.channels == 2 && $0.bookmark != nil && !$0.missing })415        #expect(Set(stored.map(\.format)) == ["wav", "aiff", "m4a", "flac"])416417        // Nothing was copied, moved or modified.418        #expect(try Data(contentsOf: root.appendingPathComponent("Moderat - Bad Kingdom.wav")) == audioBefore)419        #expect(stored.allSatisfy { $0.path.hasPrefix(root.path) })420        #expect(try FileManager.default.contentsOfDirectory(atPath: temp.file("db").path).allSatisfy { $0.hasPrefix("library.sqlite") })421422        // Importing again refreshes rows instead of duplicating them and keeps user data.423        let id = try #require(stored.first { $0.title == "song" }).id424        try store.setRating(trackID: id, rating: 5)425        let again = await importer.importFiles(files, into: store)426        #expect(again.imported.count == 4)427        #expect(try store.count() == 4)428        #expect(try store.track(id: id)?.rating == 5)429    }430431    @Test func importHonoursCancellation() async throws {432        let temp = TempDirectory()433        let files = try (0..<5).map { index -> URL in434            let url = temp.file("c\(index).wav")435            try AudioFixture.wav.write(to: url)436            return url437        }438        let store = try LibraryStore(inMemory: true)439        let task = Task { () -> ImportSummary in440            while !Task.isCancelled { await Task.yield() }441            return await MediaImporter().importFiles(files, into: store)442        }443        task.cancel()444        let summary = await task.value445        #expect(summary.cancelled)446        #expect(summary.imported.isEmpty)447        #expect(try store.count() == 0)448    }449450    @Test func movedAndRenamedFileIsFoundThroughItsBookmark() async throws {451        let temp = TempDirectory()452        let original = temp.file("Original Name.wav")453        try AudioFixture.wav.write(to: original)454        let importer = MediaImporter()455        let store = try LibraryStore(inMemory: true)456        let imported = await importer.importFiles([original], into: store)457        var track = try #require(imported.imported.first)458        try store.setRating(trackID: track.id, rating: 4)459        track = try #require(try store.track(id: track.id))460461        // Untouched file: resolves in place, nothing to refresh.462        let inPlace = importer.resolve(track: track)463        #expect(inPlace.url?.path == original.path)464        #expect(!inPlace.isMissing && !inPlace.moved)465466        // Move into another folder and rename.467        let moved = temp.directory("Sorted/2026").appendingPathComponent("Renamed.wav")468        try FileManager.default.moveItem(at: original, to: moved)469        #expect(!FileManager.default.fileExists(atPath: track.path))470471        let resolved = importer.resolve(track: track)472        #expect(!resolved.isMissing)473        #expect(resolved.moved)474        #expect(resolved.url?.resolvingSymlinksInPath().path == moved.resolvingSymlinksInPath().path)475        #expect(resolved.refreshedBookmark != nil)476        #expect(try store.track(id: track.id)?.path == original.path) // resolve(track:) alone does not write477478        let (media, updated) = try importer.resolve(track: track, updating: store)479        #expect(media.moved)480        #expect(updated.id == track.id)481        #expect(updated.path == media.url?.path)482        #expect(updated.rating == 4)483        #expect(!updated.missing)484        #expect(try store.track(id: track.id) == updated)485        #expect(try store.count() == 1)486487        // The refreshed bookmark resolves in place from now on.488        let afterwards = importer.resolve(track: updated)489        #expect(!afterwards.moved && !afterwards.isMissing)490        #expect(afterwards.url?.path == updated.path)491    }492493    @Test func missingMediaIsDetectedAndRecoversWhenTheFileReturns() async throws {494        let temp = TempDirectory()495        let url = temp.file("Gone.wav")496        try AudioFixture.wav.write(to: url)497        let importer = MediaImporter()498        let store = try LibraryStore(inMemory: true)499        let imported = await importer.importFiles([url], into: store)500        let track = try #require(imported.imported.first)501502        try FileManager.default.removeItem(at: url)503        let gone = importer.resolve(track: track)504        #expect(gone.isMissing)505        #expect(gone.url == nil)506        let (_, flagged) = try importer.resolve(track: track, updating: store)507        #expect(flagged.missing)508        #expect(try store.tracks(query: TrackQuery(scope: .missing)).map(\.id) == [track.id])509        #expect(try store.count() == 1) // a missing track stays in the library510511        // A track without bookmark and without file is missing too.512        var bare = track513        bare.bookmark = nil514        #expect(importer.resolve(track: bare).isMissing)515516        // The file comes back at the same path (a new file, so the old bookmark may not match): found by path.517        try AudioFixture.wav.write(to: url)518        let (media, recovered) = try importer.resolve(track: flagged, updating: store)519        #expect(!media.isMissing)520        #expect(!recovered.missing)521        #expect(recovered.bookmark != nil)522        #expect(try store.count(query: TrackQuery(scope: .missing)) == 0)523524        // Manual relocation to a different file.525        let elsewhere = temp.file("Elsewhere.aiff")526        try AudioFixture.aiff.write(to: elsewhere)527        let relocated = try store.relocate(trackID: track.id, to: elsewhere)528        #expect(relocated.path == elsewhere.path)529        #expect(relocated.format == "aiff")530        #expect(expectLibraryError({ if case .io = $0 { return true } else { return false } }) {531            _ = try store.relocate(trackID: track.id, to: temp.file("nowhere.wav"))532        })533        let otherURL = temp.file("Other.wav")534        try AudioFixture.wav.write(to: otherURL)535        let other = try store.upsertTrack(sampleTrack("Other", path: otherURL.path))536        #expect(expectLibraryError({ if case .conflict = $0 { return true } else { return false } }) {537            _ = try store.relocate(trackID: other.id, to: elsewhere)538        })539    }540}541542final class ProgressRecorder: @unchecked Sendable {543    private let lock = NSLock()544    private var storage: [ImportProgress] = []545546    func record(_ progress: ImportProgress) {547        lock.lock()548        storage.append(progress)549        lock.unlock()550    }551552    var values: [ImportProgress] {553        lock.lock()554        defer { lock.unlock() }555        return storage556    }557}558
Files main
Menu

Theme