Cotton code
341 lines · 19.8 KB · SwiftRaw
// Cotton Music's intake on the phone: TagLib reads what a file says about// itself, the folder walk names each file by its path, and the songs of one// album go in together. Every file here is invented, built byte by byte: a// second of silence with tags, never a real song.import Foundationimport XCTest@testable import CottonKitfinal class MusicIntakeTests: XCTestCase {    private var folder: URL!    override func setUpWithError() throws {        folder = FileManager.default.temporaryDirectory.appendingPathComponent("music-intake-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)    }    override func tearDownWithError() throws {        try? FileManager.default.removeItem(at: folder)    }    // RULE (Music definition, 4 Nov 2026): the whitelisted fields of an ID3 tag are read, numbers and their counts apart, and the picture it carries is written out.    func testAWavsID3TagIsReadFieldForField() throws {        let png = Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) + Data(repeating: 7, count: 24)        let tag = ID3.tag([            ID3.text("TIT2", "Low Tide"),            ID3.text("TPE1", "Ana Vell feat. Rio"),            ID3.text("TALB", "Harbour Lights"),            ID3.text("TPE2", "Ana Vell"),            ID3.text("TRCK", "3/12"),            ID3.text("TPOS", "1/2"),            ID3.text("TDRC", "2019-05-01"),            ID3.text("TCON", "Ambient"),            ID3.text("TSRC", "XXA001900001"),            ID3.user("MusicBrainz Album Id", "00000000-0000-4000-8000-000000000001"),            ID3.user("REPLAYGAIN_TRACK_GAIN", "-6.50 dB"),            ID3.picture(png, mime: "image/png"),        ])        let url = folder.appendingPathComponent("Low Tide.wav")        try WAV.silence(seconds: 1, id3: tag).write(to: url)        let read = try XCTUnwrap(SongTagReader.read(url, pictureInto: folder))        let tags = read.tags        XCTAssertEqual(tags.title, "Low Tide")        XCTAssertEqual(tags.artist, "Ana Vell feat. Rio")        XCTAssertEqual(tags.album, "Harbour Lights")        XCTAssertEqual(tags.albumArtist, "Ana Vell")        XCTAssertEqual([tags.track, tags.disc, tags.discs], [3, 1, 2])        XCTAssertEqual(tags.year, "2019")        XCTAssertEqual(tags.genre, "Ambient")        XCTAssertEqual(tags.isrc, "XXA001900001")        XCTAssertEqual(tags.mbRelease, "00000000-0000-4000-8000-000000000001")        XCTAssertEqual(try XCTUnwrap(tags.trackGain), -6.5, accuracy: 0.001)        XCTAssertEqual(try XCTUnwrap(tags.duration), 1, accuracy: 0.01)        XCTAssertEqual(tags.sampleRate, 8000)        let picture = try XCTUnwrap(read.picture, "the embedded picture is written out")        XCTAssertEqual(picture.pathExtension, "png")        XCTAssertEqual(try Data(contentsOf: picture), png)        XCTAssertTrue(tags.namesASong)    }    // RULE (Music definition, 4 Nov 2026): a FLAC's Vorbis comments are read too, a compilation said as one, and lyrics written as LRC are the timed lyrics.    func testAFlacsVorbisCommentIsRead() throws {        let lrc = "[00:01.00] First line\n[00:03.50] Second line"        let url = folder.appendingPathComponent("02 Night Bus.flac")        try FLAC.empty(seconds: 3, comments: [            "TITLE=Night Bus", "ARTIST=Mo Arden", "ALBUM=Late Shift", "TRACKNUMBER=2", "DISCNUMBER=1",            "DATE=2021", "COMPILATION=1", "LYRICS=\(lrc)", "MUSICBRAINZ_TRACKID=00000000-0000-4000-8000-000000000002",        ]).write(to: url)        let tags = try XCTUnwrap(SongTagReader.read(url)?.tags)        XCTAssertEqual(tags.title, "Night Bus")        XCTAssertEqual(tags.track, 2)        XCTAssertEqual(tags.compilation, true)        XCTAssertEqual(tags.syncedLyrics, lrc, "an LRC lyrics tag is the timed lyrics")        XCTAssertNil(tags.lyrics)        XCTAssertEqual(tags.mbRecording, "00000000-0000-4000-8000-000000000002")        XCTAssertEqual(try XCTUnwrap(tags.duration), 3, accuracy: 0.01)        XCTAssertEqual(tags.sampleRate, 44100)    }    // RULE: a file TagLib cannot open as audio reads as nothing, never as an empty song.    func testAFileThatIsNoAudioReadsAsNothing() throws {        let url = folder.appendingPathComponent("notes.mp3")        try Data("not a song at all".utf8).write(to: url)        XCTAssertNil(SongTagReader.read(url)?.tags.title)    }    // RULE (Music definition, 4 Nov 2026): a folder is walked whole, deepest too, each song named by its path under the folder picked, a .lrc beside it read, a folder's cover found.    func testAFolderIsWalkedWholeAndEachSongNamedByItsPath() throws {        let album = folder.appendingPathComponent("Ana Vell/Harbour Lights (2019)/CD2", isDirectory: true)        try FileManager.default.createDirectory(at: album, withIntermediateDirectories: true)        try WAV.silence(seconds: 1, id3: nil).write(to: album.appendingPathComponent("01 Low Tide.wav"))        try "[00:00.50] Words".write(to: album.appendingPathComponent("01 Low Tide.lrc"), atomically: true, encoding: .utf8)        try Data([0xFF, 0xD8, 0xFF]).write(to: album.appendingPathComponent("cover.jpg"))        try Data("x".utf8).write(to: album.appendingPathComponent(".hidden.mp3"))        try Data("x".utf8).write(to: album.appendingPathComponent("booklet.pdf"))        let picked = folder.appendingPathComponent("Ana Vell", isDirectory: true)        // Named as the share intake names a folder brought through a door: its own name.        let found = MusicIntake.songs(in: picked, named: picked.lastPathComponent)        XCTAssertEqual(found.map(\.sourcePath), ["Ana Vell/Harbour Lights (2019)/CD2/01 Low Tide.wav"])        let song = MusicIntake.read(try XCTUnwrap(found.first), scratch: folder)        XCTAssertEqual(song.tags.syncedLyrics, "[00:00.50] Words")        XCTAssertEqual(song.tags.lyricsBeside, true)        XCTAssertEqual(song.coverPath.map { URL(fileURLWithPath: $0).lastPathComponent }, "cover.jpg")    }    // RULE: the songs of one album go in one write: its key is its album artist (or Various Artists for a compilation) and title, else its folders'.    func testAnAlbumsSongsAreKeptTogether() {        var a = SongTags()        a.album = "Late Shift"        a.artist = "Mo Arden"        a.compilation = true        var b = a        b.artist = "Rio"        XCTAssertEqual(MusicIntake.albumKey(a, sourcePath: "x/1.flac"), MusicIntake.albumKey(b, sourcePath: "y/2.flac"),                       "a compilation's songs gather whoever sings them")        XCTAssertEqual(MusicIntake.albumKey(SongTags(), sourcePath: "Ana Vell/Harbour Lights/01.mp3"), "ana vell\u{1f}harbour lights")    }    // RULE (Music definition, 4 Nov 2026): a MusicBrainz search answer is taken only at score 90 or more with the album's own title; iTunes's artwork only for the same title and artist, at 600 px.    func testALookupTakesOnlyAnAnswerThatIsTheAlbum() throws {        let answers = try JSONDecoder().decode([AlbumLookup.MBRelease].self, from: Data("""        [{"id": "r-1", "title": "Harbour Lights (Deluxe)", "score": 100},         {"id": "r-2", "title": "harbour lights", "score": 85, "date": "2019-05-01"},         {"id": "r-3", "title": "Harbour Lights", "score": 95, "date": "2019-05-01", "release-group": {"id": "g-3"}}]        """.utf8))        let picked = try XCTUnwrap(AlbumLookup.pick(answers, title: "Harbour Lights", scored: true))        XCTAssertEqual(picked.release, AlbumLookup.Release(id: "r-3", group: "g-3", year: "2019"))        XCTAssertEqual(AlbumLookup.pick(answers, title: "Harbour Lights", scored: false)?.id, "r-2", "an ISRC's releases carry no score")        let album = AlbumLookup.Album(id: "a", title: "Harbour Lights", artist: "Ana Vell", mbRelease: nil, hasCover: false, isrcs: [])        let results = [            AlbumLookup.ITunes.Album(collectionName: "Harbour Lights", artistName: "Someone Else", artworkUrl100: "https://example.com/x/100x100bb.jpg"),            AlbumLookup.ITunes.Album(collectionName: "Harbour Lights", artistName: "Ana Vell", artworkUrl100: "https://example.com/y/100x100bb.jpg"),        ]        XCTAssertEqual(AlbumLookup.artwork(results, album: album)?.absoluteString, "https://example.com/y/600x600bb.jpg")        XCTAssertNil(AlbumLookup.artwork(Array(results.prefix(1)), album: album))    }    // RULE (open standards, 7 Nov 2026): every container brings the release's standard fields, TagLib's spellings of each folded into the core's names (ID3's TSOP, TSO2, TDOR, TPUB and TXXX; MP4's soar, soaa and iTunes atoms; Vorbis comments), and a song's recording id is never its release-track id.    func testEveryContainerBringsTheStandardFields() throws {        let recording = "00000000-0000-4000-8000-0000000000a1"        let releaseTrack = "00000000-0000-4000-8000-0000000000b2"        let mp3 = folder.appendingPathComponent("01 Low Tide.mp3")        try MP3.silence(frames: 40, id3: ID3.tag([            ID3.text("TIT2", "Low Tide"), ID3.text("TPE1", "Ana Vell"), ID3.text("TALB", "Harbour Lights"),            ID3.text("TSOP", "Vell, Ana"), ID3.text("TSO2", "Vell, Ana"), ID3.text("TDOR", "2011-04-02"),            ID3.text("TPUB", "Tidal Records"), ID3.user("CATALOGNUMBER", "TID-001"), ID3.user("BARCODE", "0000000000017"),            ID3.user("MusicBrainz Album Type", "album\u{0}live"), ID3.user("MusicBrainz Release Track Id", releaseTrack),            ID3.ufid("http://musicbrainz.org", recording),        ])).write(to: mp3)        let m4a = folder.appendingPathComponent("01 Low Tide.m4a")        try MP4.alac(seconds: 2, items: [            MP4.text("\u{a9}nam", "Low Tide"), MP4.text("\u{a9}ART", "Ana Vell"), MP4.text("\u{a9}alb", "Harbour Lights"),            MP4.pair("disk", 1, 2), MP4.text("soar", "Vell, Ana"), MP4.text("soaa", "Vell, Ana"),            MP4.free("ORIGINALDATE", "2011-04-02"), MP4.free("LABEL", "Tidal Records"), MP4.free("CATALOGNUMBER", "TID-001"),            MP4.free("BARCODE", "0000000000017"), MP4.free("MusicBrainz Album Type", "album; live"),            MP4.free("MusicBrainz Track Id", recording), MP4.free("MusicBrainz Release Track Id", releaseTrack),        ]).write(to: m4a)        let flac = folder.appendingPathComponent("01 Low Tide.flac")        try FLAC.empty(seconds: 2, comments: [            "TITLE=Low Tide", "ARTIST=Ana Vell", "ALBUM=Harbour Lights", "DISCNUMBER=1", "DISCTOTAL=2",            "ARTISTSORT=Vell, Ana", "ALBUMARTISTSORT=Vell, Ana", "ORIGINALDATE=2011-04-02", "LABEL=Tidal Records",            "CATALOGNUMBER=TID-001", "BARCODE=0000000000017", "RELEASETYPE=album; live",            "MUSICBRAINZ_TRACKID=\(recording)", "MUSICBRAINZ_RELEASETRACKID=\(releaseTrack)",        ]).write(to: flac)        for url in [mp3, m4a, flac] {            let tags = try XCTUnwrap(SongTagReader.read(url)?.tags, url.lastPathComponent)            let said = url.pathExtension            XCTAssertEqual(tags.title, "Low Tide", said)            XCTAssertEqual(tags.artistSort, "Vell, Ana", said)            XCTAssertEqual(tags.albumArtistSort, "Vell, Ana", said)            XCTAssertEqual(tags.originalDate, "2011-04-02", said)            XCTAssertEqual(tags.year, "2011", "\(said): the original date is the year when nothing else dates it")            XCTAssertEqual(tags.label, "Tidal Records", said)            XCTAssertEqual(tags.catalogNumber, "TID-001", said)            XCTAssertEqual(tags.barcode, "0000000000017", said)            XCTAssertEqual(tags.releaseType, "album; live", "\(said): every kind tagged, as the core's release_type reads them")            XCTAssertEqual(tags.mbRecording, recording, said)            XCTAssertEqual(tags.mbReleaseTrack, releaseTrack, "\(said): the release track is its own id, never the recording's")        }        let m4aTags = try XCTUnwrap(SongTagReader.read(m4a)?.tags)        XCTAssertEqual(m4aTags.lossless, true, "an ALAC box is lossless")        XCTAssertEqual([m4aTags.disc, m4aTags.discs], [1, 2])        XCTAssertEqual(try XCTUnwrap(m4aTags.duration), 2, accuracy: 0.01)        XCTAssertEqual(try XCTUnwrap(SongTagReader.read(flac)?.tags.discs), 2, "a Vorbis DISCTOTAL counts the discs")        XCTAssertEqual(try XCTUnwrap(SongTagReader.read(mp3)?.tags.sampleRate), 44100)    }    // RULE (open standards, 7 Nov 2026): the phone's reader hands over exactly the fields the core's readers read (`cotton_core::music::TAG_FIELDS`): the C++ emits no key off the list and misses none but `lyricsBeside` (the intake's own), and `SongTags` decodes every one, so a field added to the core and not to TagLib's reader fails here.    func testTheReaderHandsOverExactlyTheCoresFieldList() throws {        let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("../../../..").standardizedFileURL        let rust = try String(contentsOf: root.appendingPathComponent("crates/cotton-core/src/music/mod.rs"), encoding: .utf8)        let list = try XCTUnwrap(rust.range(of: "pub const TAG_FIELDS").map { rust[$0.upperBound...] }.flatMap { rest in rest.range(of: "];").map { rest[..<$0.lowerBound] } })        let listed = Set(Self.quoted(in: String(list.drop(while: { $0 != "[" }))))        XCTAssertGreaterThanOrEqual(listed.count, 36)        let cpp = try String(contentsOf: root.appendingPathComponent("apps/cotton/Sources/CottonTagReader/CottonTagReader.cpp"), encoding: .utf8)        let pattern = try NSRegularExpression(pattern: #"tags\.(?:text|number|whole|field)\("([A-Za-z]+)""#)        let emitted = Set(pattern.matches(in: cpp, range: NSRange(cpp.startIndex..., in: cpp)).map { (cpp as NSString).substring(with: $0.range(at: 1)) })        XCTAssertEqual(emitted.subtracting(listed), [], "the reader emits a key the core does not read")        XCTAssertEqual(listed.subtracting(emitted), ["lyricsBeside"], "the reader misses a field the core reads")        let decoded = Set(Mirror(reflecting: SongTags()).children.compactMap(\.label))        XCTAssertEqual(decoded, listed, "SongTags decodes the core's fields, no more and no fewer")    }    private static func quoted(in text: String) -> [String] {        text.split(separator: "\"").enumerated().filter { $0.offset % 2 == 1 }.map { String($0.element) }    }    func testLRCIsTimedWhenMostLinesCarryATime() {        XCTAssertTrue(LRC.looksTimed("[00:01.00] a\n[00:02.00] b\nc"))        XCTAssertFalse(LRC.looksTimed("just words\nand more"))    }}// MARK: Invented files/// An ID3v2.4 tag, frame by frame.enum ID3 {    static func syncsafe(_ n: Int) -> Data {        Data([UInt8((n >> 21) & 0x7F), UInt8((n >> 14) & 0x7F), UInt8((n >> 7) & 0x7F), UInt8(n & 0x7F)])    }    static func frame(_ id: String, _ body: Data) -> Data {        Data(id.utf8) + syncsafe(body.count) + Data([0, 0]) + body    }    static func text(_ id: String, _ value: String) -> Data {        frame(id, Data([3]) + Data(value.utf8))    }    static func user(_ description: String, _ value: String) -> Data {        frame("TXXX", Data([3]) + Data(description.utf8) + Data([0]) + Data(value.utf8))    }    static func ufid(_ owner: String, _ identifier: String) -> Data {        frame("UFID", Data(owner.utf8) + Data([0]) + Data(identifier.utf8))    }    static func picture(_ bytes: Data, mime: String) -> Data {        frame("APIC", Data([0]) + Data(mime.utf8) + Data([0, 3, 0]) + bytes)    }    static func tag(_ frames: [Data]) -> Data {        let body = frames.reduce(Data(), +)        return Data("ID3".utf8) + Data([4, 0, 0]) + syncsafe(body.count) + body    }}/// A WAV of silence, 8 kHz mono 16-bit, with an ID3 chunk when given one.enum WAV {    static func le32(_ n: Int) -> Data { withUnsafeBytes(of: UInt32(n).littleEndian) { Data($0) } }    static func le16(_ n: Int) -> Data { withUnsafeBytes(of: UInt16(n).littleEndian) { Data($0) } }    static func silence(seconds: Int, id3: Data?) -> Data {        let rate = 8000        let fmt = le16(1) + le16(1) + le32(rate) + le32(rate * 2) + le16(2) + le16(16)        var chunks = Data("fmt ".utf8) + le32(fmt.count) + fmt        let samples = Data(repeating: 0, count: rate * 2 * seconds)        chunks += Data("data".utf8) + le32(samples.count) + samples        if let id3 {            chunks += Data("id3 ".utf8) + le32(id3.count) + id3            if id3.count % 2 == 1 { chunks += Data([0]) }        }        return Data("RIFF".utf8) + le32(4 + chunks.count) + Data("WAVE".utf8) + chunks    }}/// A FLAC of stream info and Vorbis comments, no frames.enum FLAC {    static func block(_ type: UInt8, last: Bool, _ body: Data) -> Data {        let n = body.count        return Data([(last ? 0x80 : 0) | type, UInt8((n >> 16) & 0xFF), UInt8((n >> 8) & 0xFF), UInt8(n & 0xFF)]) + body    }    static func empty(seconds: Int, comments: [String]) -> Data {        let rate: UInt64 = 44100        var info = Data([0x10, 0x00, 0x10, 0x00]) + Data(repeating: 0, count: 6)        let packed = (rate << 44) | (1 << 41) | (15 << 36) | (rate * UInt64(seconds))        info += withUnsafeBytes(of: packed.bigEndian) { Data($0) }        info += Data(repeating: 0, count: 16)        let vendor = Data("invented".utf8)        var vorbis = WAV.le32(vendor.count) + vendor + WAV.le32(comments.count)        for comment in comments {            let bytes = Data(comment.utf8)            vorbis += WAV.le32(bytes.count) + bytes        }        return Data("fLaC".utf8) + block(0, last: false, info) + block(4, last: true, vorbis)    }}/// An MP3 of silent MPEG-1 Layer III frames (128 kbit/s, 44.1 kHz, mono)/// behind an ID3v2 tag.enum MP3 {    static func silence(frames: Int, id3: Data) -> Data {        // 144 × 128000 / 44100 = 417 bytes a frame, header included.        let frame = Data([0xFF, 0xFB, 0x90, 0xC0]) + Data(repeating: 0, count: 413)        return id3 + (0 ..< frames).reduce(Data()) { all, _ in all + frame }    }}/// An MP4 of one ALAC track's boxes, no samples, and its iTunes items.enum MP4 {    static func be32(_ n: Int) -> Data { withUnsafeBytes(of: UInt32(n).bigEndian) { Data($0) } }    static func be16(_ n: Int) -> Data { withUnsafeBytes(of: UInt16(n).bigEndian) { Data($0) } }    /// A box: its size, its four-byte name (Latin-1, so `©nam` is one byte    /// short of five characters), its body.    static func box(_ name: String, _ body: Data) -> Data {        let named = Data(name.unicodeScalars.map { UInt8($0.value & 0xFF) })        return be32(8 + body.count) + named + body    }    static func data(_ type: Int, _ payload: Data) -> Data {        box("data", be32(type) + be32(0) + payload)    }    static func text(_ name: String, _ value: String) -> Data {        box(name, data(1, Data(value.utf8)))    }    static func pair(_ name: String, _ number: Int, _ of: Int) -> Data {        box(name, data(0, be16(0) + be16(number) + be16(of)))    }    /// An iTunes free-form item, `----:com.apple.iTunes:<name>`.    static func free(_ name: String, _ value: String) -> Data {        box("----", box("mean", be32(0) + Data("com.apple.iTunes".utf8)) + box("name", be32(0) + Data(name.utf8)) + data(1, Data(value.utf8)))    }    static func alac(seconds: Int, items: [Data]) -> Data {        let rate = 44100        let hdlr = box("hdlr", be32(0) + be32(0) + Data("soun".utf8) + Data(repeating: 0, count: 12) + Data([0]))        let mdhd = box("mdhd", be32(0) + be32(0) + be32(0) + be32(rate) + be32(rate * seconds) + be16(0) + be16(0))        // The ALAC sample entry, its magic cookie inside: 16-bit stereo, 44.1 kHz.        let cookie = box("alac", be32(0) + be32(4096) + Data([0, 16, 40, 10, 14, 2]) + be16(255) + be32(0) + be32(0) + be32(rate))        let entry = box("alac", Data(repeating: 0, count: 6) + be16(1) + Data(repeating: 0, count: 8) + be16(2) + be16(16) + be16(0) + be16(0) + be16(rate) + be16(0) + cookie)        let stsd = box("stsd", be32(0) + be32(1) + entry)        let trak = box("trak", box("mdia", hdlr + mdhd + box("minf", box("stbl", stsd))))        let udta = box("udta", box("meta", be32(0) + box("ilst", items.reduce(Data(), +))))        return box("ftyp", Data("M4A ".utf8) + be32(0) + Data("M4A mp42isom".utf8)) + box("moov", trak + udta)    }}