import UIKit import ImageIO /// Cover art: user override › embedded › folder image › online (iTunes, Deezer, Cover Art Archive, Last.fm). enum Covers { private static let mem: NSCache = { let c = NSCache() c.totalCostLimit = 48 << 20 return c }() private static let missing = NSMutableSet() private static let lock = NSLock() static var dir: URL { let d = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("covers") try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) return d } static var overrideDir: URL { let d = Library.support.appendingPathComponent("covers") try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) return d } static func albumKey(_ s: Song) -> String { let k = s.album.isEmpty ? s.path : s.albumKey return Data(k.utf8).base64EncodedString().replacingOccurrences(of: "/", with: "_").prefix(100).description } static func overrideFile(_ s: Song) -> URL { overrideDir.appendingPathComponent(albumKey(s) + ".jpg") } static func onlineFile(_ s: Song) -> URL { dir.appendingPathComponent("online-" + albumKey(s) + ".jpg") } static func thumbFile(_ s: Song, _ px: Int) -> URL { dir.appendingPathComponent("t\(px)-" + albumKey(s) + ".jpg") } static func cached(_ s: Song, _ px: Int) -> UIImage? { mem.object(forKey: "\(px)|\(albumKey(s))" as NSString) } /// Raw image bytes for a song, without network. static func localData(_ s: Song) -> Data? { if let d = try? Data(contentsOf: overrideFile(s)) { return d } guard !s.isStream else { return nil } if s.hasCover, let d = TagReader.read(s.url, wantCover: true).cover { return d } let folder = s.url.deletingLastPathComponent() for name in ["cover", "folder", "front", "album", "Cover", "Folder", "Front", "AlbumArt"] { for ext in ["jpg", "jpeg", "png", "webp"] { if let d = try? Data(contentsOf: folder.appendingPathComponent("\(name).\(ext)")) { return d } } } if let d = try? Data(contentsOf: onlineFile(s)) { return d } return nil } /// Downsampled decode (keeps memory low for long lists). static func decode(_ d: Data, maxPixels: Int) -> UIImage? { guard let src = CGImageSourceCreateWithData(d as CFData, nil) else { return nil } let opts: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxPixels] guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) else { return nil } return UIImage(cgImage: cg) } /// Thumbnail for lists (blocking; call off the main thread). static func thumb(_ s: Song, px: Int = 160) -> UIImage? { let key = "\(px)|\(albumKey(s))" as NSString if let i = mem.object(forKey: key) { return i } lock.lock(); let miss = missing.contains(key); lock.unlock() if miss { return nil } let tf = thumbFile(s, px) var img: UIImage? if let d = try? Data(contentsOf: tf) { img = UIImage(data: d) } else if let d = localData(s), let i = decode(d, maxPixels: px) { img = i try? i.jpegData(compressionQuality: 0.85)?.write(to: tf) } if let img { mem.setObject(img, forKey: key, cost: px * px * 4) } else { lock.lock(); missing.add(key); lock.unlock() } return img } /// Full-size cover for the now-playing screen; may hit the network if enabled. static func loadFull(_ s: Song) -> UIImage? { if let d = localData(s), let i = decode(d, maxPixels: 1200) { return i } guard Prefs.shared.onlineCovers, let d = best(artist: s.groupArtist, album: s.album, title: s.displayTitle) else { return nil } try? d.write(to: onlineFile(s)) forget(s) return decode(d, maxPixels: 1200) } static func setOverride(_ s: Song, _ d: Data?) { if let d { try? d.write(to: overrideFile(s)) } else { try? FileManager.default.removeItem(at: overrideFile(s)) } forget(s) } static func forget(_ s: Song) { let k = albumKey(s) for px in [96, 160, 300, 600] { mem.removeObject(forKey: "\(px)|\(k)" as NSString) try? FileManager.default.removeItem(at: thumbFile(s, px)) lock.lock(); missing.remove("\(px)|\(k)" as NSString); lock.unlock() } } static func clearCache() { try? FileManager.default.removeItem(at: dir) mem.removeAllObjects() lock.lock(); missing.removeAllObjects(); lock.unlock() } static func cacheSize() -> Int64 { var total: Int64 = 0 let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] for sub in ["covers", "lyrics"] { let en = FileManager.default.enumerator(at: caches.appendingPathComponent(sub), includingPropertiesForKeys: [.fileSizeKey]) while let u = en?.nextObject() as? URL { total += Int64((try? u.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) } } return total } // MARK: Online (desktop online.rs) struct Candidate: Identifiable, Hashable { var id: String { url } let url: String let thumb: String let source: String let label: String } static let lastfmKey = "654be90d519a1688bb90661f8f493c0a" static func candidates(artist: String, album: String, title: String) -> [Candidate] { let term = "\(artist) \(album.isEmpty ? title : album)".trimmingCharacters(in: .whitespaces) var out: [Candidate] = [] let lock = NSLock() let group = DispatchGroup() func add(_ c: Candidate) { lock.lock(); out.append(c); lock.unlock() } group.enter() DispatchQueue.global().async { defer { group.leave() } let ent = album.isEmpty ? "song" : "album" guard let r = try? Net.json("https://itunes.apple.com/search?" + Net.query([("term", term), ("entity", ent), ("limit", "8")])) as? [String: Any] else { return } for it in r.arr("results") where !it.str("artworkUrl100").isEmpty { let u = it.str("artworkUrl100") add(Candidate(url: u.replacingOccurrences(of: "100x100bb", with: "1200x1200bb"), thumb: u.replacingOccurrences(of: "100x100bb", with: "300x300bb"), source: "iTunes", label: "\(it.str("artistName")) – \(it.str("collectionName"))")) } } group.enter() DispatchQueue.global().async { defer { group.leave() } let q = "artist:\"\(artist)\" album:\"\(album.isEmpty ? title : album)\"" var r = try? Net.json("https://api.deezer.com/search/album?q=" + Net.enc(q)) as? [String: Any] if (r?.arr("data").isEmpty ?? true) { r = try? Net.json("https://api.deezer.com/search/album?q=" + Net.enc(term)) as? [String: Any] } for it in (r?.arr("data") ?? []).prefix(8) where !it.str("cover_xl").isEmpty { add(Candidate(url: it.str("cover_xl"), thumb: it.str("cover_medium"), source: "Deezer", label: "\(it.obj("artist")?.str("name") ?? "") – \(it.str("title"))")) } } if !album.isEmpty { group.enter() DispatchQueue.global().async { defer { group.leave() } let q = "release:\"\(album)\" AND artist:\"\(artist)\"" guard let r = try? Net.json("https://musicbrainz.org/ws/2/release?fmt=json&limit=5&query=" + Net.enc(q)) as? [String: Any] else { return } for rel in r.arr("releases").prefix(5) { let id = rel.str("id") add(Candidate(url: "https://coverartarchive.org/release/\(id)/front", thumb: "https://coverartarchive.org/release/\(id)/front-250", source: "Cover Art Archive", label: "\(rel.str("title")) (\(rel.str("date").prefix(4)))")) } } group.enter() DispatchQueue.global().async { defer { group.leave() } let q: [(String, String)] = [("method", "album.getinfo"), ("api_key", lastfmKey), ("artist", artist), ("album", album), ("format", "json"), ("autocorrect", "1")] guard let r = try? Net.json("https://ws.audioscrobbler.com/2.0/?" + Net.query(q)) as? [String: Any], let u = (r.obj("album")?["image"] as? [[String: Any]])?.last?.str("#text"), !u.isEmpty else { return } let big = u.replacingOccurrences(of: #"/\d+x\d+/"#, with: "/", options: .regularExpression) add(Candidate(url: big, thumb: u, source: "Last.fm", label: album)) } } group.wait() let order = ["Cover Art Archive": 0, "iTunes": 1, "Deezer": 2, "Last.fm": 3] var seen = Set() return out.sorted { (order[$0.source] ?? 9) < (order[$1.source] ?? 9) }.filter { seen.insert($0.url).inserted } } /// Automatic fetch for "Fetch missing covers": iTunes first, then Deezer, then Last.fm. static func best(artist: String, album: String, title: String) -> Data? { guard !artist.isEmpty || !album.isEmpty else { return nil } let term = "\(artist) \(album.isEmpty ? title : album)" if let r = try? Net.json("https://itunes.apple.com/search?" + Net.query([("term", term), ("entity", album.isEmpty ? "song" : "album"), ("limit", "5")])) as? [String: Any] { let want = Library.norm(album.isEmpty ? title : album) let hits = r.arr("results") let pick = hits.first { Library.norm($0.str(album.isEmpty ? "trackName" : "collectionName")).contains(want) } ?? hits.first if let u = pick?.str("artworkUrl100"), !u.isEmpty, let d = try? Net.data(u.replacingOccurrences(of: "100x100bb", with: "1200x1200bb")), UIImage(data: d) != nil { return d } } if let r = try? Net.json("https://api.deezer.com/search/album?q=" + Net.enc(term)) as? [String: Any], let u = r.arr("data").first?.str("cover_xl"), !u.isEmpty, let d = try? Net.data(u), UIImage(data: d) != nil { return d } return nil } }