SPB Git

Repository Public

Models.swift 7.3 KB 194 lines swift

1// SP Music iOS2// File: Core/Sources/SPMusicCore/Models/Models.swift3// Description: Library models and formatting helpers.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910/// A file of a track as the server stores it. `sha256` is known for originals; a rendition is checked by size.11public struct AssetInfo: Codable, Hashable, Sendable {12    public var assetId: String13    public var sizeBytes: Int6414    public var sha256: String?15    public var mime: String16    public init(assetId: String, sizeBytes: Int64, sha256: String?, mime: String) {17        self.assetId = assetId; self.sizeBytes = sizeBytes; self.sha256 = sha256; self.mime = mime18    }19}2021/// Which file of a track: the untouched original, or the AAC rendition the server can prepare.22public enum AudioVariant: String, Codable, Sendable, CaseIterable {23    case original, compat24}2526public struct Track: Hashable, Identifiable, Sendable {27    public var id: String28    public var title: String29    public var trackNo: Int?30    public var discNo: Int31    public var durationMs: Int32    public var year: Int?33    public var codec: String34    public var container: String35    public var sampleRate: Int?36    public var bitDepth: Int?37    public var channels: Int?38    public var bitrate: Int?39    public var compatState: String40    public var artistId: String41    public var artistName: String42    public var albumId: String43    public var albumTitle: String44    public var albumArtistName: String45    public var artworkId: String?46    public var genre: String?47    public var lyricsState: String?48    public var file: AssetInfo?49    public var compat: AssetInfo?50    public var favorite: Bool51    /// Deleted from the server's library but kept here because its file is on this device.52    public var removedRemotely: Bool53    /// Set when the track is read as a playlist entry.54    public var entryId: String?5556    public var duration: TimeInterval { Double(durationMs) / 1000 }57    public func asset(_ v: AudioVariant) -> AssetInfo? { v == .original ? file : compat }58}5960public struct Album: Hashable, Identifiable, Sendable {61    public var id: String62    public var title: String63    public var year: Int?64    public var artworkId: String?65    public var artistId: String66    public var artistName: String67    public var genre: String?68    public var createdAt: Date?69    public var trackCount: Int70    public var durationMs: Int71    public var favorite: Bool72}7374public struct Artist: Hashable, Identifiable, Sendable {75    public var id: String76    public var name: String77    public var albumCount: Int78    public var trackCount: Int79    public var artworkId: String?80}8182public struct Playlist: Hashable, Identifiable, Sendable {83    public var id: String84    public var name: String85    public var updatedAt: Date?86    public var trackCount: Int87    public var artworkIds: [String]88}8990public struct Me: Codable, Hashable, Sendable {91    public var id: String92    public var email: String93    public var displayName: String94    public var role: String95    public var isOwner: Bool96    public var locale: String97    public var accent: String98}99100// MARK: - Lyrics101102public struct LyricWord: Hashable, Sendable, Codable {103    public var start: Int, end: Int, text: String104    public init(start: Int, end: Int, text: String) { self.start = start; self.end = end; self.text = text }105    /// The server sends `[startMs, endMs, "word"]`.106    public init(from decoder: Decoder) throws {107        var c = try decoder.unkeyedContainer()108        start = try c.decode(Int.self); end = try c.decode(Int.self); text = try c.decode(String.self)109    }110    public func encode(to encoder: Encoder) throws {111        var c = encoder.unkeyedContainer()112        try c.encode(start); try c.encode(end); try c.encode(text)113    }114}115116public struct LyricLine: Hashable, Sendable, Codable, Identifiable {117    public var t: Int, e: Int, text: String, w: [LyricWord]?118    public var id: Int { t }119}120121public struct Lyrics: Hashable, Sendable, Codable {122    public var state: String123    public var language: String?124    public var lines: [LyricLine]125    public var hasText: Bool { state == "ready" && !lines.isEmpty }126}127128// MARK: - Formatting helpers shared by every screen129130public enum AudioFormat {131    /// "FLAC · 24 bits / 48 kHz" — what the FILE is, never a claim about the output path.132    public static func describe(codec: String, container: String, sampleRate: Int?, bitDepth: Int?, bitrate: Int?) -> String {133        let name: String = switch codec {134        case "flac": "FLAC"135        case "alac": "ALAC"136        case "mp3": "MP3"137        case "aac": "AAC"138        case "vorbis": "Ogg Vorbis"139        case "opus": "Opus"140        default: codec.hasPrefix("pcm") ? (container == "aiff" ? "AIFF" : "WAV") : (codec.hasPrefix("dsd") ? "DSD" : codec.uppercased())141        }142        var parts = [name]143        let lossless = isLossless(codec: codec)144        if lossless, let sr = sampleRate {145            let khz = Double(sr) / 1000146            let k = khz == khz.rounded() ? String(Int(khz)) : String(format: "%.1f", khz).replacingOccurrences(of: ".", with: ",")147            parts.append(bitDepth.map { "\($0) bits / \(k) kHz" } ?? "\(k) kHz")148        } else if let br = bitrate {149            parts.append("\(Int((Double(br) / 1000).rounded())) kbit/s")150        }151        return parts.joined(separator: " · ")152    }153    public static func isLossless(codec: String) -> Bool { codec == "flac" || codec == "alac" || codec.hasPrefix("pcm") || codec.hasPrefix("dsd") }154    public static func isHiRes(codec: String, sampleRate: Int?, bitDepth: Int?) -> Bool {155        isLossless(codec: codec) && ((bitDepth ?? 16) > 16 || (sampleRate ?? 44100) > 48000)156    }157    public static func fileExtension(mime: String, codec: String, container: String) -> String {158        switch mime {159        case "audio/flac": "flac"160        case "audio/mpeg": "mp3"161        case "audio/mp4": "m4a"162        case "audio/wav": "wav"163        case "audio/aiff": "aiff"164        case "audio/ogg": "ogg"165        case "audio/aac": "aac"166        default: container.isEmpty ? "bin" : container167        }168    }169}170171public extension Track {172    var formatDescription: String { AudioFormat.describe(codec: codec, container: container, sampleRate: sampleRate, bitDepth: bitDepth, bitrate: bitrate) }173    var isLossless: Bool { AudioFormat.isLossless(codec: codec) }174    var isHiRes: Bool { AudioFormat.isHiRes(codec: codec, sampleRate: sampleRate, bitDepth: bitDepth) }175}176177public enum Format {178    public static func duration(_ seconds: TimeInterval) -> String {179        let s = max(0, Int(seconds.rounded(.down)))180        return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, (s % 3600) / 60, s % 60) : String(format: "%d:%02d", s / 60, s % 60)181    }182    public static func longDuration(ms: Int) -> String {183        let m = ms / 60000184        return m >= 60 ? "\(m / 60) h \(m % 60) min" : "\(max(1, m)) min"185    }186    public static func bytes(_ n: Int64) -> String { ByteCountFormatter.string(fromByteCount: n, countStyle: .file) }187}188189/// Lower-cased, accent-stripped form used for search and sorting (same idea as the server's *_norm columns).190public func normalized(_ s: String) -> String {191    s.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: Locale(identifier: "fr_CA"))192        .lowercased().trimmingCharacters(in: .whitespacesAndNewlines)193}194
Files main
Menu

Theme