commit 8e6f8a86a469ec3973a3e91a414b45d01806743f Author: astar76 Date: Tue Oct 27 19:30:49 2026 -0500 Mulberry for iOS: initial SwiftUI port of the Android app Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..36605d2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/ +*.ipa +*.deb +.DS_Store diff --git a/App/Audio/Decoder.swift b/App/Audio/Decoder.swift new file mode 100644 index 0000000..769c024 --- /dev/null +++ b/App/Audio/Decoder.swift @@ -0,0 +1,117 @@ +import AVFoundation + +/// A PCM source in the engine's format (stereo, non-interleaved Float32 at `Decoder.rate`). +protocol AudioSource: AnyObject { + /// Total frames in engine-rate frames (0 when unknown, e.g. streams). + var frames: AVAudioFramePosition { get } + /// Reads up to `buffer.frameCapacity` frames; returns false at end of stream. + func read(into buffer: AVAudioPCMBuffer) -> Bool + func seek(to frame: AVAudioFramePosition) +} + +enum Decoder { + static let rate: Double = 48000 + static let format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)! + + /// Opens a song (respecting cue start/end) with the best available decoder. + static func open(_ song: Song) -> AudioSource? { + let url = song.url + var src: AudioSource? + if let f = try? AVAudioFile(forReading: url) { + src = NativeSource(file: f) + } else if let ff = FFSource.open(url) { + src = ff + } + guard let s = src else { return nil } + if song.cueIndex > 0 { + return Segment(s, start: AVAudioFramePosition(song.start * rate), + end: song.end > song.start ? AVAudioFramePosition(song.end * rate) : s.frames) + } + return s + } + + static func probeDuration(_ url: URL) -> Double { + guard let s = FFSource.open(url), s.frames > 0 else { return 0 } + return Double(s.frames) / rate + } +} + +/// AVAudioFile (MP3, AAC, ALAC, FLAC, WAV, AIFF, CAF/Opus) resampled to the engine format. +final class NativeSource: AudioSource { + private let file: AVAudioFile + private let conv: AVAudioConverter? + private let inBuf: AVAudioPCMBuffer + private let ratio: Double + private var eof = false + + init?(file: AVAudioFile) { + self.file = file + let inFmt = file.processingFormat + ratio = Decoder.rate / inFmt.sampleRate + conv = inFmt == Decoder.format ? nil : AVAudioConverter(from: inFmt, to: Decoder.format) + if conv == nil && inFmt != Decoder.format { return nil } + guard let b = AVAudioPCMBuffer(pcmFormat: inFmt, frameCapacity: 8192) else { return nil } + inBuf = b + if inFmt.channelCount == 1 { conv?.channelMap = [0, 0] } + } + + var frames: AVAudioFramePosition { AVAudioFramePosition(Double(file.length) * ratio) } + + func seek(to frame: AVAudioFramePosition) { + file.framePosition = max(0, min(file.length, AVAudioFramePosition(Double(frame) / ratio))) + conv?.reset() + eof = false + } + + func read(into buffer: AVAudioPCMBuffer) -> Bool { + buffer.frameLength = 0 + guard let conv else { + do { try file.read(into: buffer) } catch { return false } + return buffer.frameLength > 0 + } + var error: NSError? + let status = conv.convert(to: buffer, error: &error) { [self] _, outStatus in + if eof { outStatus.pointee = .endOfStream; return nil } + do { + try file.read(into: inBuf, frameCount: inBuf.frameCapacity) + } catch { + eof = true; outStatus.pointee = .endOfStream; return nil + } + if inBuf.frameLength == 0 { eof = true; outStatus.pointee = .endOfStream; return nil } + outStatus.pointee = .haveData + return inBuf + } + return status != .error && buffer.frameLength > 0 + } +} + +/// A slice of another source (cue-sheet tracks). +final class Segment: AudioSource { + private let base: AudioSource + private let start: AVAudioFramePosition + private let end: AVAudioFramePosition + private var pos: AVAudioFramePosition + + init(_ base: AudioSource, start: AVAudioFramePosition, end: AVAudioFramePosition) { + self.base = base + self.start = start + self.end = max(start, end) + pos = start + base.seek(to: start) + } + + var frames: AVAudioFramePosition { end - start } + + func seek(to frame: AVAudioFramePosition) { + pos = start + max(0, min(frames, frame)) + base.seek(to: pos) + } + + func read(into buffer: AVAudioPCMBuffer) -> Bool { + guard pos < end, base.read(into: buffer) else { return false } + let left = end - pos + if AVAudioFramePosition(buffer.frameLength) > left { buffer.frameLength = AVAudioFrameCount(left) } + pos += AVAudioFramePosition(buffer.frameLength) + return buffer.frameLength > 0 + } +} diff --git a/App/Audio/FFSource.swift b/App/Audio/FFSource.swift new file mode 100644 index 0000000..66ca984 --- /dev/null +++ b/App/Audio/FFSource.swift @@ -0,0 +1,17 @@ +import AVFoundation + +/// Decoder for formats Apple doesn't handle (Ogg Vorbis/Opus, WMA, APE, WavPack, Musepack, DSD, trackers…). +/// Backed by FFmpeg when the build links it (MULBERRY_FFMPEG); otherwise nothing opens. +final class FFSource: AudioSource { + static func open(_ url: URL) -> FFSource? { + #if MULBERRY_FFMPEG + return FFSource(url: url) + #else + return nil + #endif + } + + var frames: AVAudioFramePosition { 0 } + func read(into buffer: AVAudioPCMBuffer) -> Bool { false } + func seek(to frame: AVAudioFramePosition) {} +} diff --git a/App/Audio/Player.swift b/App/Audio/Player.swift new file mode 100644 index 0000000..9de6ef5 --- /dev/null +++ b/App/Audio/Player.swift @@ -0,0 +1,752 @@ +import AVFoundation +import MediaPlayer +import SwiftUI +import Combine + +/// One AVAudioPlayerNode fed from a chain of sources (gapless: the next song's audio is queued right behind). +final class Deck { + let node = AVAudioPlayerNode() + private let q: DispatchQueue + private var gen = 0 + private var source: AudioSource? + private var inFlight = 0 + private let chunk: AVAudioFrameCount = 8192 + private let maxInFlight = 6 + /// Called on the deck queue when the current source ends; returns the next song's source (gapless) or nil. + var onSourceEnd: ((Int) -> (AudioSource, Int)?)? + /// Sample offsets (in node time) where each scheduled item starts: (queue index, node sample, start frame in song). + private(set) var marks: [(index: Int, at: AVAudioFramePosition, offset: AVAudioFramePosition)] = [] + private var scheduled: AVAudioFramePosition = 0 + private var drained = false + var onDrained: (() -> Void)? + + init(name: String) { q = DispatchQueue(label: "mulberry.deck." + name, qos: .userInitiated) } + + func load(_ src: AudioSource, index: Int, from frame: AVAudioFramePosition) { + q.sync { + gen += 1 + node.stop() + node.reset() + source = src + src.seek(to: frame) + inFlight = 0 + scheduled = 0 + drained = false + marks = [(index, 0, frame)] + fill(gen) + } + } + + func stop() { + q.sync { + gen += 1 + node.stop() + source = nil + marks = [] + } + } + + private func fill(_ g: Int) { + while g == gen && inFlight < maxInFlight, let src = source { + guard let buf = AVAudioPCMBuffer(pcmFormat: Decoder.format, frameCapacity: chunk) else { return } + if !src.read(into: buf) { + if let (next, idx) = onSourceEnd?(marks.last?.index ?? -1) { + source = next + marks.append((idx, scheduled, 0)) + continue + } + source = nil + if inFlight == 0 { finish(g) } + return + } + inFlight += 1 + scheduled += AVAudioFramePosition(buf.frameLength) + node.scheduleBuffer(buf, completionCallbackType: .dataPlayedBack) { [weak self] _ in + guard let self else { return } + self.q.async { + guard g == self.gen else { return } + self.inFlight -= 1 + if self.source != nil { self.fill(g) } else if self.inFlight == 0 { self.finish(g) } + } + } + } + } + + private func finish(_ g: Int) { + guard !drained, g == gen else { return } + drained = true + DispatchQueue.main.async { [weak self] in self?.onDrained?() } + } + + /// Current played sample position in node time. + var playedSamples: AVAudioFramePosition { + guard let nt = node.lastRenderTime, nt.isSampleTimeValid, + let pt = node.playerTime(forNodeTime: nt) else { return 0 } + return max(0, pt.sampleTime) + } + + /// (queue index, seconds into that song) for what is audible now. + func now() -> (Int, Double)? { + let s = playedSamples + var cur: (Int, Double)? + q.sync { + for m in marks where m.at <= s { + cur = (m.index, Double(s - m.at + m.offset) / Decoder.rate) + } + } + return cur + } +} + +@MainActor +final class Player: ObservableObject { + static let shared = Player() + + @Published private(set) var queue: [Song] = [] + @Published private(set) var index = -1 + @Published private(set) var isPlaying = false + @Published private(set) var duration: Double = 0 + @Published var stopAfterCurrent = false + @Published private(set) var sleepAt: Date? + @Published private(set) var sleepAtTrackEnd = false + @Published private(set) var art: UIImage? + @Published private(set) var seed: UInt32? + @Published private(set) var lyrics: Lyrics.Result? + @Published private(set) var error: String? + + let spectrum = Spectrum() + private let prefs = Prefs.shared + private let engine = AVAudioEngine() + private let eq = AVAudioUnitEQ(numberOfBands: 10) + private var decks = [Deck(name: "a"), Deck(name: "b")] + private var active = 0 + private var order: [Int] = [] // play order when shuffled (indices into queue) + private var basePos: Double = 0 // position when paused / for streams + private var stream: AVPlayer? + private var timer: Timer? + private var crossfading = false + private var listenStart = Date() + private var listened: Double = 0 + private var lastTick = Date() + + static let eqFreqs: [Float] = [31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] + + var current: Song? { queue.indices.contains(index) ? queue[index] : nil } + + private init() { + for (i, b) in eq.bands.enumerated() { + b.filterType = .parametric + b.frequency = Player.eqFreqs[i] + b.bandwidth = 1 + b.bypass = false + } + engine.attach(eq) + for d in decks { + engine.attach(d.node) + engine.connect(d.node, to: eq, format: Decoder.format) + } + engine.connect(eq, to: engine.mainMixerNode, format: Decoder.format) + applyEQ() + engine.mainMixerNode.installTap(onBus: 0, bufferSize: 1024, format: nil) { [spectrum] buf, _ in + spectrum.feed(buf) + } + for (i, d) in decks.enumerated() { + d.onSourceEnd = { [plan] last in Player.gaplessNext(plan, after: last) } + d.onDrained = { [weak self] in self?.deckDrained(i) } + } + setupSession() + setupRemote() + restore() + } + + // MARK: Session & remote + + private func setupSession() { + let s = AVAudioSession.sharedInstance() + try? s.setCategory(.playback, mode: .default, policy: .longFormAudio) + let nc = NotificationCenter.default + nc.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { [weak self] n in + guard let self, let raw = n.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt, + let type = AVAudioSession.InterruptionType(rawValue: raw) else { return } + MainActor.assumeIsolated { + if type == .began { + if self.isPlaying { self.pause(fade: false); self.resumeAfterInterruption = true } + } else if let o = n.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt, + AVAudioSession.InterruptionOptions(rawValue: o).contains(.shouldResume), + self.resumeAfterInterruption { + self.resumeAfterInterruption = false + self.play() + } + } + } + nc.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] n in + guard let self, let raw = n.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt, + AVAudioSession.RouteChangeReason(rawValue: raw) == .oldDeviceUnavailable else { return } + MainActor.assumeIsolated { + if self.prefs.pauseOnDetach && self.isPlaying { self.pause(fade: false) } + } + } + nc.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { + guard let self, self.isPlaying else { return } + try? self.engine.start() + self.decks[self.active].node.play() + } + } + } + + private var resumeAfterInterruption = false + + private func setupRemote() { + let c = MPRemoteCommandCenter.shared() + c.playCommand.addTarget { [weak self] _ in self?.play(); return .success } + c.pauseCommand.addTarget { [weak self] _ in self?.pause(); return .success } + c.togglePlayPauseCommand.addTarget { [weak self] _ in self?.toggle(); return .success } + c.nextTrackCommand.addTarget { [weak self] _ in self?.next(); return .success } + c.previousTrackCommand.addTarget { [weak self] _ in self?.prev(); return .success } + c.changePlaybackPositionCommand.addTarget { [weak self] e in + if let e = e as? MPChangePlaybackPositionCommandEvent { self?.seek(e.positionTime) } + return .success + } + c.changeShuffleModeCommand.addTarget { [weak self] _ in self?.setShuffle(!(self?.prefs.shuffle ?? false)); return .success } + c.changeRepeatModeCommand.addTarget { [weak self] _ in self?.cycleRepeat(); return .success } + c.likeCommand.addTarget { [weak self] _ in + if let s = self?.current { PlayStats.shared.setFav(s, !PlayStats.shared.fav(s)) } + return .success + } + } + + private func updateNowPlaying() { + guard let s = current else { + MPNowPlayingInfoCenter.default().nowPlayingInfo = nil + return + } + var info: [String: Any] = [ + MPMediaItemPropertyTitle: s.displayTitle, + MPMediaItemPropertyArtist: s.displayArtist, + MPMediaItemPropertyAlbumTitle: s.album, + MPMediaItemPropertyPlaybackDuration: duration, + MPNowPlayingInfoPropertyElapsedPlaybackTime: position, + MPNowPlayingInfoPropertyPlaybackRate: isPlaying ? 1.0 : 0.0, + MPNowPlayingInfoPropertyPlaybackQueueIndex: index, + MPNowPlayingInfoPropertyPlaybackQueueCount: queue.count, + ] + if let img = art { + info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: img.size) { _ in img } + } + MPNowPlayingInfoCenter.default().nowPlayingInfo = info + MPNowPlayingInfoCenter.default().playbackState = isPlaying ? .playing : .paused + } + + // MARK: Queue (Android MusicService API) + + func playList(_ list: [Song], start: Int = 0) { + guard !list.isEmpty else { return } + queue = list + rebuildOrder(keep: start) + load(start, play: true) + } + + func playShuffled(_ list: [Song]) { + guard !list.isEmpty else { return } + prefs.shuffle = true + queue = list + let start = Int.random(in: 0.. index ? $0 + list.count : $0 } + if let p = order.firstIndex(of: index) { order.insert(contentsOf: added, at: p + 1) } + saveSoon() + } + + func enqueue(_ list: [Song]) { + defer { updatePlan() } + guard current != nil else { playList(list); return } + let start = queue.count + queue.append(contentsOf: list) + order.append(contentsOf: start.. i ? $0 - 1 : $0 } + if i < index { index -= 1 } + if wasCurrent { + if queue.isEmpty { stop(); index = -1 } else { load(min(index, queue.count - 1), play: isPlaying) } + } + saveSoon() + } + + func move(_ from: Int, _ to: Int) { + guard queue.indices.contains(from), to >= 0, to <= queue.count else { return } + let cur = current + let s = queue.remove(at: from) + queue.insert(s, at: to > from ? to - 1 : to) + if let cur, let i = queue.firstIndex(where: { $0.id == cur.id }) { index = i } + rebuildOrder(keep: index) + saveSoon() + } + + func clearQueue() { + stop() + queue = [] + order = [] + index = -1 + art = nil + lyrics = nil + updateNowPlaying() + publishWidget() + saveSoon() + } + + func jump(_ i: Int) { load(i, play: true) } + + func setShuffle(_ on: Bool) { + prefs.shuffle = on + rebuildOrder(keep: index) + updatePlan() + updateNowPlaying() + publishWidget() + } + + func cycleRepeat() { + prefs.repeatMode = (prefs.repeatMode + 1) % 3 + updatePlan() + publishWidget() + } + + private func rebuildOrder(keep: Int) { + var o = Array(queue.indices) + if prefs.shuffle { + o.shuffle() + if let p = o.firstIndex(of: keep) { o.swapAt(0, p) } + } + order = o + } + + /// Next queue index after `i` following shuffle/repeat, or nil at the end. + func nextIndex(after i: Int, user: Bool) -> Int? { + guard !queue.isEmpty else { return nil } + if prefs.repeatMode == 2 && !user { return i } + guard let p = order.firstIndex(of: i) else { return queue.indices.contains(i + 1) ? i + 1 : nil } + if p + 1 < order.count { return order[p + 1] } + return prefs.repeatMode == 1 || user ? order.first : nil + } + + // MARK: Transport + + var position: Double { + if let stream { return stream.currentTime().seconds.isFinite ? stream.currentTime().seconds : 0 } + guard isPlaying, let (_, t) = decks[active].now() else { return basePos } + return t + } + + func toggle() { isPlaying ? pause() : play() } + + func play() { + guard let s = current else { + if !Library.shared.songs.isEmpty { playShuffled(Library.shared.songs) } + return + } + if stream != nil { + stream?.play() + isPlaying = true + } else { + if decks[active].node.engine == nil || decks[active].marks.isEmpty { + load(index, play: true, at: basePos) + return + } + try? AVAudioSession.sharedInstance().setActive(true) + if !engine.isRunning { try? engine.start() } + let node = decks[active].node + node.volume = prefs.fadePause ? 0 : gain(s) + node.play() + isPlaying = true + if prefs.fadePause { ramp(node, to: gain(s), ms: 220) } + } + lastTick = Date() + startTimer() + updateNowPlaying() + publishWidget() + Scrobbler.shared.nowPlaying(s) + } + + func pause(fade: Bool = true) { + guard isPlaying else { return } + basePos = position + isPlaying = false + if let stream { + stream.pause() + } else { + let node = decks[active].node + if fade && prefs.fadePause { + ramp(node, to: 0, ms: 220) { [weak self] in + guard let self, !self.isPlaying else { return } + node.pause() + } + } else { + node.pause() + } + decks[1 - active].stop() + crossfading = false + } + updateNowPlaying() + publishWidget() + saveSoon() + } + + func stop() { + isPlaying = false + stream?.pause() + stream = nil + decks.forEach { $0.stop() } + crossfading = false + spectrum.reset() + timer?.invalidate() + timer = nil + } + + func next() { + finishListen() + guard let n = nextIndex(after: index, user: true) else { return } + load(n, play: isPlaying || true) + } + + func prev() { + if position > 3 { seek(0); return } + finishListen() + guard let p = order.firstIndex(of: index) else { return } + let target = p > 0 ? order[p - 1] : (prefs.repeatMode == 1 ? order.last ?? index : index) + load(target, play: true) + } + + func seek(_ t: Double) { + guard let s = current else { return } + let t = max(0, min(duration > 0 ? duration - 0.25 : t, t)) + if let stream { + stream.seek(to: CMTime(seconds: t, preferredTimescale: 1000)) + return + } + basePos = t + decks[1 - active].stop() + crossfading = false + if let src = Decoder.open(s) { + decks[active].load(src, index: index, from: AVAudioFramePosition(t * Decoder.rate)) + decks[active].node.volume = gain(s) + if isPlaying { decks[active].node.play() } + } + updateNowPlaying() + } + + /// Loads queue index `i` on the active deck. + func load(_ i: Int, play: Bool, at start: Double = 0) { + guard queue.indices.contains(i) else { return } + stop() + index = i + let s = queue[i] + updatePlan() + basePos = start + duration = s.duration + error = nil + listenStart = Date() + listened = 0 + lastTick = Date() + loadArtAndLyrics(s) + if s.isStream { + let p = AVPlayer(url: s.url) + stream = p + if play { p.play(); isPlaying = true; startTimer() } + } else if let src = Decoder.open(s) { + if duration <= 0 { duration = Double(src.frames) / Decoder.rate } + active = 0 + decks[0].load(src, index: i, from: AVAudioFramePosition(start * Decoder.rate)) + decks[0].node.volume = gain(s) + if play { + try? AVAudioSession.sharedInstance().setActive(true) + if !engine.isRunning { try? engine.start() } + decks[0].node.play() + isPlaying = true + startTimer() + Scrobbler.shared.nowPlaying(s) + } + } else { + error = "Can't play \(s.fileName)" + if play, let n = nextIndex(after: i, user: false), n != i { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in self?.load(n, play: true) } + } + } + updateNowPlaying() + publishWidget() + saveSoon() + } + + /// What a deck should play gaplessly after a given queue index. Written on main, read on deck queues. + final class Plan: @unchecked Sendable { + private let lock = NSLock() + private var after = -1 + private var next: (Song, Int)? + func set(after: Int, _ n: (Song, Int)?) { lock.lock(); self.after = after; next = n; lock.unlock() } + func get(after: Int) -> (Song, Int)? { lock.lock(); defer { lock.unlock() }; return after == self.after ? next : nil } + } + + private let plan = Plan() + + /// Refreshes the gapless plan; call after anything that changes what comes next. + private func updatePlan() { + guard prefs.gapless, prefs.crossfade == 0, !stopAfterCurrent, !sleepAtTrackEnd, stream == nil, + let n = nextIndex(after: index, user: false), queue.indices.contains(n), !queue[n].isStream else { + plan.set(after: index, nil) + return + } + plan.set(after: index, (queue[n], n)) + } + + /// Gapless hand-over, called on the deck queue when the playing source runs out. + nonisolated private static func gaplessNext(_ plan: Plan, after last: Int) -> (AudioSource, Int)? { + guard let (song, n) = plan.get(after: last), let src = Decoder.open(song) else { return nil } + return (src, n) + } + + private func deckDrained(_ d: Int) { + guard d == active, isPlaying, !crossfading else { return } + finishListen() + if stopAfterCurrent || sleepAtTrackEnd { + stopAfterCurrent = false + sleepAtTrackEnd = false + sleepAt = nil + pause(fade: false) + basePos = 0 + if let n = nextIndex(after: index, user: false) { load(n, play: false) } + return + } + if let n = nextIndex(after: index, user: false) { + load(n, play: true) + } else { + pause(fade: false) + basePos = 0 + seekOnResume = true + } + } + + private var seekOnResume = false + + private func beginCrossfade(to n: Int) { + guard !crossfading, queue.indices.contains(n), !queue[n].isStream, let src = Decoder.open(queue[n]) else { return } + crossfading = true + let old = decks[active] + let newIdx = 1 - active + let nd = decks[newIdx] + nd.load(src, index: n, from: 0) + nd.node.volume = 0 + nd.node.play() + let ms = Double(prefs.crossfade) * 1000 + ramp(old.node, to: 0, ms: ms) { old.stop() } + ramp(nd.node, to: gain(queue[n]), ms: ms) { [weak self] in self?.crossfading = false } + finishListen() + active = newIdx + index = n + duration = queue[n].duration > 0 ? queue[n].duration : Double(src.frames) / Decoder.rate + listenStart = Date() + listened = 0 + loadArtAndLyrics(queue[n]) + updateNowPlaying() + publishWidget() + Scrobbler.shared.nowPlaying(queue[n]) + saveSoon() + } + + private func ramp(_ node: AVAudioPlayerNode, to target: Float, ms: Double, done: (() -> Void)? = nil) { + let start = node.volume + let steps = max(1, Int(ms / 20)) + var k = 0 + Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { t in + k += 1 + let f = Float(k) / Float(steps) + node.volume = start + (target - start) * min(1, f * f * (3 - 2 * f)) + if k >= steps { t.invalidate(); done?() } + } + } + + private func gain(_ s: Song) -> Float { + guard prefs.replayGain else { return 1 } + let t = ReplayGainCache.shared.gain(s) + return Float(min(1, pow(10, t / 20))) + } + + func applyEQ() { + eq.bypass = !prefs.eqOn + for (i, b) in eq.bands.enumerated() where i < prefs.eqBands.count { b.gain = Float(prefs.eqBands[i]) } + } + + // MARK: Timer: track hand-over, crossfade start, listening time, sleep + + private func startTimer() { + guard timer == nil else { return } + timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.tick() } + } + } + + private func tick() { + guard isPlaying else { return } + updatePlan() + let now = Date() + listened += now.timeIntervalSince(lastTick) + lastTick = now + // Gapless boundary passed: the deck now plays a different queue index. + if !crossfading, let (i, _) = decks[active].now(), i != index, queue.indices.contains(i) { + finishListen() + index = i + duration = queue[i].duration + listenStart = now + listened = 0 + loadArtAndLyrics(queue[i]) + updateNowPlaying() + publishWidget() + Scrobbler.shared.nowPlaying(queue[i]) + saveSoon() + } + if prefs.crossfade > 0, !crossfading, !stopAfterCurrent, !sleepAtTrackEnd, stream == nil, duration > 0, + position >= duration - Double(prefs.crossfade), duration > Double(prefs.crossfade) * 2, + let n = nextIndex(after: index, user: false) { + beginCrossfade(to: n) + } + if let s = current { Scrobbler.shared.progress(s, listened: listened, duration: duration) } + if let at = sleepAt, now >= at { + sleepAt = nil + fadeOutAndPause() + } + if Int(now.timeIntervalSince1970 * 4) % 20 == 0 { saveSoon(); updateNowPlaying() } + } + + private func finishListen() { + guard let s = current else { return } + if listened >= min(30, max(1, duration * 0.5)) { PlayStats.shared.played(s) } + Scrobbler.shared.finished(s, listened: listened, started: listenStart) + listened = 0 + } + + func sleep(minutes: Int) { + sleepAtTrackEnd = false + sleepAt = minutes > 0 ? Date().addingTimeInterval(Double(minutes) * 60) : nil + } + + func sleepAtEndOfTrack() { + sleepAt = nil + sleepAtTrackEnd = true + } + + func cancelSleep() { + sleepAt = nil + sleepAtTrackEnd = false + } + + private func fadeOutAndPause() { + let node = decks[active].node + ramp(node, to: 0, ms: 4000) { [weak self] in self?.pause(fade: false) } + } + + // MARK: Art & lyrics + + private var artToken = 0 + + func loadArtAndLyrics(_ s: Song) { + artToken += 1 + let tok = artToken + lyrics = nil + Task.detached(priority: .userInitiated) { + let img = Covers.loadFull(s) + let seed = img.flatMap { Palette.dominant($0.cgImage) } + await MainActor.run { + let p = Player.shared + guard tok == p.artToken else { return } + p.art = img + p.seed = seed + Theme.shared.update() + p.updateNowPlaying() + p.publishWidget() + } + let lr = Lyrics.load(s) + await MainActor.run { + let p = Player.shared + guard tok == p.artToken else { return } + p.lyrics = lr + p.publishWidget() + } + } + } + + func reloadLyrics(online: Bool) { + guard let s = current else { return } + Lyrics.clearCache(s) + let tok = artToken + Task.detached { + let lr = Lyrics.load(s, forceOnline: online) + await MainActor.run { + guard tok == Player.shared.artToken else { return } + Player.shared.lyrics = lr + } + } + } + + // MARK: Widget snapshot + + func publishWidget() { + WidgetBridge.publish(song: current, playing: isPlaying, position: position, duration: duration, + art: art, palette: Theme.shared.palette, lyrics: lyrics, + shuffle: prefs.shuffle, repeatMode: prefs.repeatMode) + } + + // MARK: Persist queue (Android saveQueue/restoreQueue) + + private struct Saved: Codable { + var paths: [String] + var index: Int + var position: Double + } + + private var saveScheduled = false + private var queueFile: URL { Library.support.appendingPathComponent("queue.json") } + + func saveSoon() { + guard !saveScheduled else { return } + saveScheduled = true + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in + guard let self else { return } + self.saveScheduled = false + let saved = Saved(paths: self.queue.map(\.id), index: self.index, position: self.position) + if let d = try? JSONEncoder().encode(saved) { try? d.write(to: self.queueFile, options: .atomic) } + } + } + + private func restore() { + guard prefs.resume, let d = try? Data(contentsOf: queueFile), + let saved = try? JSONDecoder().decode(Saved.self, from: d) else { return } + let lib = Library.shared + let songs = saved.paths.compactMap { lib.song(path: $0) ?? (($0.hasPrefix("http")) ? Song(path: $0) : nil) } + guard !songs.isEmpty else { return } + queue = songs + index = min(max(0, saved.index), songs.count - 1) + rebuildOrder(keep: index) + basePos = saved.position + duration = songs[index].duration + loadArtAndLyrics(songs[index]) + updateNowPlaying() + } + + /// Called when the app enters the background or is terminated. + func persistNow() { + let saved = Saved(paths: queue.map(\.id), index: index, position: position) + if let d = try? JSONEncoder().encode(saved) { try? d.write(to: queueFile, options: .atomic) } + } +} diff --git a/App/Audio/Spectrum.swift b/App/Audio/Spectrum.swift new file mode 100644 index 0000000..0c9b9b3 --- /dev/null +++ b/App/Audio/Spectrum.swift @@ -0,0 +1,132 @@ +import AVFoundation + +/// 48 log-spaced bands plus a bass level, computed from the engine output (Android Spectrum.analyse). +/// The Android app decoded ahead; here we tap the mixer, so it needs no microphone either. +final class Spectrum { + static let bands = 48 + private static let n = 1024 + + private var ring = [Float](repeating: 0, count: n) + private var ringPos = 0 + private var re = [Float](repeating: 0, count: n) + private var im = [Float](repeating: 0, count: n) + private let win: [Float] + private let cosT: [Float] + private let sinT: [Float] + private let rev: [Int] + private var bandLo = [Int](repeating: 0, count: bands) + private var bandHi = [Int](repeating: 0, count: bands) + private var tableRate = 0 + private let lock = NSLock() + + private var levelsOut = [Float](repeating: 0, count: bands) + private var bassOut: Float = -1 + private var lastAnalyse: CFAbsoluteTime = 0 + private var fresh = false + + init() { + let n = Spectrum.n + win = (0..>= 1 } + r[i] = y + } + rev = r + buildBands(Int(Decoder.rate)) + } + + private func buildBands(_ rate: Int) { + guard rate != tableRate else { return } + tableRate = rate + let top = min(16000, Double(rate) / 2 - 1) + for i in 0..= 1.0 / 30 { + lastAnalyse = now + analyse() + } + lock.unlock() + } + + private func analyse() { + let n = Spectrum.n + for i in 0..> 1, step = n / size + var start = 0 + while start < n { + for k in 0.. Bool { + lock.lock(); defer { lock.unlock() } + guard fresh else { return false } + for i in 0.. Float { + lock.lock(); defer { lock.unlock() } + return fresh ? bassOut : -1 + } + + func reset() { + lock.lock() + fresh = false + for i in ring.indices { ring[i] = 0 } + lock.unlock() + } +} diff --git a/App/Model/Library.swift b/App/Model/Library.swift new file mode 100644 index 0000000..b673de9 --- /dev/null +++ b/App/Model/Library.swift @@ -0,0 +1,406 @@ +import Foundation +import AVFoundation +import Combine + +/// The music library: everything under the app's Documents folder ("On My iPhone › Mulberry" in Files), +/// scanned incrementally and cached as JSON. +@MainActor +final class Library: ObservableObject { + static let shared = Library() + + nonisolated static let audioExts: Set = ["mp3", "m4a", "m4b", "aac", "alac", "flac", "wav", "aif", "aiff", + "aifc", "caf", "ogg", "oga", "opus", "wma", "ape", "wv", "mpc", "dsf", "dff", "mka", "webm", "ac3", "eac3", + "tta", "mp2", "amr", "3gp", "mod", "xm", "it", "s3m"] + nonisolated static let playlistExts: Set = ["m3u", "m3u8", "pls", "xspf", "wpl", "asx"] + + nonisolated static var root: URL { + FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + } + + nonisolated static var support: URL { + let u = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("Mulberry", isDirectory: true) + try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true) + return u + } + + @Published private(set) var songs: [Song] = [] + @Published private(set) var scanning = false + @Published private(set) var scanned = 0 + + struct Group: Identifiable, Hashable { + let id: String + let title: String + let subtitle: String + let songs: [Song] + var cover: Song? { songs.first(where: { $0.hasCover }) ?? songs.first } + } + + private var byPath: [String: Song] = [:] + private var cacheURL: URL { Library.support.appendingPathComponent("library.json") } + private var watcher: DispatchSourceFileSystemObject? + private var rescanPending = false + + private init() { + ensureFolders() + if let d = try? Data(contentsOf: cacheURL), let s = try? JSONDecoder().decode([Song].self, from: d) { + set(s) + } + } + + /// Creates the visible folders in Files so the user knows where to put things. + func ensureFolders() { + let fm = FileManager.default + for name in ["Music", "Playlists", "Lyrics"] { + try? fm.createDirectory(at: Library.root.appendingPathComponent(name), withIntermediateDirectories: true) + } + let readme = Library.root.appendingPathComponent("Music/Put your music here.txt") + if !fm.fileExists(atPath: readme.path) { + try? """ + Copy music into this folder (or any folder next to it) from the Files app, a computer or AirDrop. + Mulberry picks up new files automatically. Playlists (.m3u, .m3u8, .pls, .xspf, .wpl) can go in + the Playlists folder and appear in the Playlists tab; .lrc lyrics files can sit next to songs or in Lyrics. + """.write(to: readme, atomically: true, encoding: .utf8) + } + } + + private func set(_ list: [Song]) { + let minDur = Double(Prefs.shared.minDuration) + songs = list.filter { $0.duration == 0 || $0.duration >= minDur || $0.cueIndex > 0 } + .sorted { $0.displayTitle.localizedStandardCompare($1.displayTitle) == .orderedAscending } + byPath = Dictionary(list.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) + } + + func song(path: String) -> Song? { byPath[path] } + + // MARK: Scanning + + func startWatching() { + let fd = open(Library.root.path, O_EVTONLY) + guard fd >= 0 else { return } + let src = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.write, .rename, .delete], + queue: .main) + src.setEventHandler { [weak self] in self?.rescanSoon() } + src.setCancelHandler { close(fd) } + src.resume() + watcher = src + } + + func rescanSoon() { + guard !rescanPending else { return } + rescanPending = true + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in + self?.rescanPending = false + self?.scan() + } + } + + func scan(force: Bool = false) { + guard !scanning else { rescanSoon(); return } + scanning = true + scanned = 0 + let old = force ? [:] : byPath + Task.detached(priority: .utility) { + let result = Library.scanTree(old: old) { n in + Task { @MainActor in Library.shared.scanned = n } + } + await MainActor.run { + let lib = Library.shared + lib.set(result) + lib.scanning = false + if let d = try? JSONEncoder().encode(result) { try? d.write(to: lib.cacheURL, options: .atomic) } + Playlists.shared.syncFolder() + } + } + } + + nonisolated static func relPath(_ url: URL) -> String { + let r = root.standardizedFileURL.path + let p = url.standardizedFileURL.path + return p.hasPrefix(r + "/") ? String(p.dropFirst(r.count + 1)) : p + } + + nonisolated static func scanTree(old: [String: Song], progress: (Int) -> Void) -> [Song] { + let fm = FileManager.default + let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .creationDateKey] + guard let en = fm.enumerator(at: root, includingPropertiesForKeys: keys, + options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] } + var out: [Song] = [] + var cues: [URL] = [] + var n = 0 + for case let url as URL in en { + let ext = url.pathExtension.lowercased() + if ext == "cue" { cues.append(url); continue } + guard audioExts.contains(ext), + let rv = try? url.resourceValues(forKeys: Set(keys)), rv.isRegularFile == true else { continue } + let rel = relPath(url) + let size = Int64(rv.fileSize ?? 0) + let mtime = rv.contentModificationDate?.timeIntervalSince1970 ?? 0 + if let prev = old[rel], prev.size == size, prev.mtime == mtime { + out.append(prev) + } else { + var s = Song(path: rel) + s.size = size + s.mtime = mtime + s.dateAdded = old[rel]?.dateAdded ?? (rv.creationDate?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) + fill(&s, url) + out.append(s) + } + n += 1 + if n % 25 == 0 { progress(n) } + } + // Cue sheets: replace the whole-file entry with one entry per track. + for cue in cues { + let tracks = CueSheet.parse(cue, existing: out) + guard !tracks.isEmpty else { continue } + let files = Set(tracks.map(\.path)) + out.removeAll { files.contains($0.path) && $0.cueIndex == 0 } + out.append(contentsOf: tracks) + } + progress(n) + return out + } + + nonisolated static func fill(_ s: inout Song, _ url: URL) { + let t = TagReader.read(url, wantCover: true) + s.title = t.title; s.artist = t.artist; s.album = t.album; s.albumArtist = t.albumArtist + s.genre = t.genre; s.track = t.track; s.disc = t.disc; s.year = t.year + s.duration = t.duration + s.hasCover = t.cover != nil + if s.duration <= 0 || (s.title.isEmpty && s.artist.isEmpty) { + // Fall back to AVFoundation for formats it understands (MP3 duration, odd containers). + let asset = AVURLAsset(url: url) + if s.duration <= 0 { + if let f = try? AVAudioFile(forReading: url), f.processingFormat.sampleRate > 0 { + s.duration = Double(f.length) / f.processingFormat.sampleRate + } else { + let d = asset.duration.seconds + if d.isFinite { s.duration = d } + } + } + if s.title.isEmpty && s.artist.isEmpty { + for item in asset.commonMetadata { + guard let key = item.commonKey else { continue } + switch key { + case .commonKeyTitle: s.title = item.stringValue ?? "" + case .commonKeyArtist: s.artist = item.stringValue ?? "" + case .commonKeyAlbumName: s.album = item.stringValue ?? "" + case .commonKeyArtwork: s.hasCover = item.dataValue != nil + default: break + } + } + } + } + if s.duration <= 0, !["mp3", "m4a", "aac", "wav", "aiff", "aif", "caf", "flac"].contains(url.pathExtension.lowercased()) { + s.duration = Decoder.probeDuration(url) + } + } + + // MARK: Groups (Android Library.build) + + var albums: [Group] { + let g = Dictionary(grouping: songs, by: \.albumKey) + return g.map { _, list in + let sorted = list.sorted { ($0.disc, $0.track, $0.displayTitle) < ($1.disc, $1.track, $1.displayTitle) } + return Group(id: "album:" + sorted[0].albumKey, title: sorted[0].displayAlbum, + subtitle: sorted[0].groupArtist, songs: sorted) + }.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + } + + var artists: [Group] { + let g = Dictionary(grouping: songs, by: { $0.groupArtist }) + return g.map { name, list in + let albums = Set(list.map(\.albumKey)).count + let sorted = list.sorted { ($0.year, $0.album, $0.disc, $0.track) < ($1.year, $1.album, $1.disc, $1.track) } + return Group(id: "artist:" + name, title: name, + subtitle: "\(albums) album\(albums == 1 ? "" : "s") · \(list.count) songs", songs: sorted) + }.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + } + + var genres: [Group] { + let g = Dictionary(grouping: songs, by: { $0.genre.isEmpty ? "Unknown genre" : $0.genre }) + return g.map { name, list in + Group(id: "genre:" + name, title: name, subtitle: "\(list.count) songs", songs: list) + }.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + } + + var folders: [Group] { + let g = Dictionary(grouping: songs, by: \.folder) + return g.map { folder, list in + let name = folder.isEmpty ? "Mulberry" : (folder as NSString).lastPathComponent + let sorted = list.sorted { $0.fileName.localizedStandardCompare($1.fileName) == .orderedAscending } + return Group(id: "folder:" + folder, title: name, + subtitle: "On My iPhone/Mulberry/" + folder, songs: sorted) + }.sorted { $0.subtitle.localizedStandardCompare($1.subtitle) == .orderedAscending } + } + + func sorted(_ list: [Song], by key: String) -> [Song] { + switch key { + case "artist": return list.sorted { ($0.displayArtist.lowercased(), $0.album, $0.track) < ($1.displayArtist.lowercased(), $1.album, $1.track) } + case "album": return list.sorted { ($0.album.lowercased(), $0.disc, $0.track) < ($1.album.lowercased(), $1.disc, $1.track) } + case "year": return list.sorted { ($0.year, $0.album, $0.track) > ($1.year, $1.album, $1.track) } + case "added": return list.sorted { $0.dateAdded > $1.dateAdded } + case "duration": return list.sorted { $0.duration > $1.duration } + default: return list + } + } + + // MARK: Search — plain words plus desktop-style filters: artist: album: genre: year:>2000 rating:>3 + + func search(_ q: String) -> [Song] { + let query = q.trimmingCharacters(in: .whitespaces) + guard !query.isEmpty else { return songs } + var words: [String] = [] + var filters: [(String, String)] = [] + for tok in query.split(separator: " ").map(String.init) { + if let c = tok.firstIndex(of: ":"), c != tok.startIndex { + filters.append((tok[.. Bool { + var op = "=" + var rest = Substring(expr) + for o in [">=", "<=", ">", "<", "="] where rest.hasPrefix(o) { op = o; rest = rest.dropFirst(o.count); break } + if let dash = rest.firstIndex(of: "-"), let a = Double(rest[..= a && x <= b + } + guard let v = Double(rest) else { return true } + switch op { + case ">": return x > v + case "<": return x < v + case ">=": return x >= v + case "<=": return x <= v + default: return x == v + } + } + + nonisolated static func norm(_ s: String) -> String { + s.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: nil) + } + + /// Finds a library song for a playlist entry path (absolute from another device, relative, or file name only). + func match(_ entry: String, title: String = "", artist: String = "") -> Song? { + var p = entry.replacingOccurrences(of: "\\", with: "/") + if p.hasPrefix("file://"), let u = URL(string: p) { p = u.path } + p = p.removingPercentEncoding ?? p + if let s = byPath[p] { return s } + let rootPath = Library.root.path + "/" + if p.hasPrefix(rootPath), let s = byPath[String(p.dropFirst(rootPath.count))] { return s } + // Longest matching path suffix wins. + let parts = p.split(separator: "/").map(String.init) + for k in stride(from: min(parts.count, 4), through: 1, by: -1) { + let suffix = parts.suffix(k).joined(separator: "/").lowercased() + if let s = songs.first(where: { $0.path.lowercased().hasSuffix(suffix) }) { return s } + } + if !title.isEmpty { + let t = Library.norm(title), a = Library.norm(artist) + return songs.first { Library.norm($0.displayTitle) == t && (a.isEmpty || Library.norm($0.displayArtist) == a) } + } + return nil + } + + func delete(_ s: Song) { + try? FileManager.default.removeItem(at: s.url) + songs.removeAll { $0.id == s.id } + byPath[s.id] = nil + } + + func updated(_ s: Song) { + var copy = s + Library.fill(©, s.url) + if let rv = try? s.url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) { + copy.size = Int64(rv.fileSize ?? 0) + copy.mtime = rv.contentModificationDate?.timeIntervalSince1970 ?? 0 + } + byPath[s.id] = copy + if let i = songs.firstIndex(where: { $0.id == s.id }) { songs[i] = copy } + if let d = try? JSONEncoder().encode(Array(byPath.values)) { try? d.write(to: cacheURL, options: .atomic) } + } +} + +/// Cue sheets: one virtual track per INDEX 01, as on the desktop app. +enum CueSheet { + static func parse(_ url: URL, existing: [Song]) -> [Song] { + guard let data = try? Data(contentsOf: url) else { return [] } + let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) ?? "" + let dir = url.deletingLastPathComponent() + var album = "", albumArtist = "", genre = "", year = 0 + var file: URL? + var tracks: [Song] = [] + var cur: Song? + func unq(_ s: Substring) -> String { + var t = s.trimmingCharacters(in: .whitespaces) + if t.hasPrefix("\""), let e = t.dropFirst().firstIndex(of: "\"") { t = String(t[t.index(after: t.startIndex).. 1 ? parts[1] : "" + switch cmd { + case "REM": + let rp = arg.split(separator: " ", maxSplits: 1) + if rp.first?.uppercased() == "GENRE", rp.count > 1 { genre = unq(rp[1]) } + if rp.first?.uppercased() == "DATE", rp.count > 1 { year = Int(unq(rp[1]).prefix(4)) ?? 0 } + case "TITLE": if cur == nil { album = unq(arg) } else { cur?.title = unq(arg) } + case "PERFORMER": if cur == nil { albumArtist = unq(arg) } else { cur?.artist = unq(arg) } + case "FILE": + var name = unq(arg) + if let sp = name.range(of: " ", options: .backwards), !arg.hasPrefix("\"") { name = String(name[.. 1 { + let mmssff = ip[1].split(separator: ":").compactMap { Double($0) } + if mmssff.count == 3 { cur?.start = mmssff[0] * 60 + mmssff[1] + mmssff[2] / 75 } + } + default: break + } + } + if let c = cur { tracks.append(c) } + guard !tracks.isEmpty else { return [] } + let whole = Dictionary(existing.map { ($0.path, $0) }, uniquingKeysWith: { a, _ in a }) + for i in tracks.indices { + let base = whole[tracks[i].path] + let next = i + 1 < tracks.count && tracks[i + 1].path == tracks[i].path ? tracks[i + 1].start : (base?.duration ?? 0) + tracks[i].end = next + tracks[i].duration = max(0, next - tracks[i].start) + if tracks[i].artist.isEmpty { tracks[i].artist = albumArtist } + tracks[i].hasCover = base?.hasCover ?? false + tracks[i].dateAdded = base?.dateAdded ?? Date().timeIntervalSince1970 + tracks[i].size = base?.size ?? 0 + tracks[i].mtime = base?.mtime ?? 0 + } + return tracks.filter { whole[$0.path] != nil } + } +} diff --git a/App/Model/PlayStats.swift b/App/Model/PlayStats.swift new file mode 100644 index 0000000..85725dd --- /dev/null +++ b/App/Model/PlayStats.swift @@ -0,0 +1,105 @@ +import Foundation + +/// Play counts, last played, favourites and 0–5 ratings (Android PlayStats plus desktop ratings). +@MainActor +final class PlayStats: ObservableObject { + static let shared = PlayStats() + + struct Entry: Codable { + var count = 0 + var last: Double = 0 + var fav = false + var rating = 0 + var skips = 0 + } + + @Published private(set) var map: [String: Entry] = [:] + private var file: URL { Library.support.appendingPathComponent("stats.json") } + private var saveScheduled = false + + private init() { + if let d = try? Data(contentsOf: file), let m = try? JSONDecoder().decode([String: Entry].self, from: d) { map = m } + } + + private func key(_ s: Song) -> String { s.id } + + func played(_ s: Song) { + var e = map[key(s)] ?? Entry() + e.count += 1 + e.last = Date().timeIntervalSince1970 + map[key(s)] = e + saveLater() + } + + func skipped(_ s: Song) { + var e = map[key(s)] ?? Entry() + e.skips += 1 + map[key(s)] = e + saveLater() + } + + func count(_ s: Song) -> Int { map[key(s)]?.count ?? 0 } + func fav(_ s: Song) -> Bool { map[key(s)]?.fav ?? false } + func rating(_ s: Song) -> Int { map[key(s)]?.rating ?? 0 } + + func setFav(_ s: Song, _ on: Bool) { + var e = map[key(s)] ?? Entry() + e.fav = on + map[key(s)] = e + saveLater() + Scrobbler.shared.love(s, on) + Player.shared.publishWidget() + } + + func setRating(_ s: Song, _ r: Int) { + var e = map[key(s)] ?? Entry() + e.rating = max(0, min(5, r)) + map[key(s)] = e + saveLater() + } + + private func saveLater() { + guard !saveScheduled else { return } + saveScheduled = true + DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in + guard let self else { return } + self.saveScheduled = false + if let d = try? JSONEncoder().encode(self.map) { try? d.write(to: self.file, options: .atomic) } + } + } + + // Smart lists (Android Playlists tab) + func mostPlayed(_ all: [Song], _ n: Int = 100) -> [Song] { + all.filter { count($0) > 0 }.sorted { count($0) > count($1) }.prefix(n).map { $0 } + } + + func recentlyPlayed(_ all: [Song], _ n: Int = 100) -> [Song] { + all.filter { (map[key($0)]?.last ?? 0) > 0 } + .sorted { (map[key($0)]?.last ?? 0) > (map[key($1)]?.last ?? 0) }.prefix(n).map { $0 } + } + + func recentlyAdded(_ all: [Song], _ n: Int = 100) -> [Song] { + all.sorted { $0.dateAdded > $1.dateAdded }.prefix(n).map { $0 } + } + + func favourites(_ all: [Song]) -> [Song] { all.filter { fav($0) } } + func neverPlayed(_ all: [Song]) -> [Song] { all.filter { count($0) == 0 } } + func topRated(_ all: [Song]) -> [Song] { all.filter { rating($0) > 0 }.sorted { rating($0) > rating($1) } } +} + +/// ReplayGain values read lazily from tags. +final class ReplayGainCache: @unchecked Sendable { + static let shared = ReplayGainCache() + private var cache: [String: Double] = [:] + private let lock = NSLock() + + func gain(_ s: Song) -> Double { + lock.lock() + if let g = cache[s.path] { lock.unlock(); return g } + lock.unlock() + let t = TagReader.read(s.url) + let g = t.albumGain ?? t.trackGain ?? 0 + lock.lock(); cache[s.path] = g; lock.unlock() + return g + } +} diff --git a/App/Model/Playlists.swift b/App/Model/Playlists.swift new file mode 100644 index 0000000..10d1921 --- /dev/null +++ b/App/Model/Playlists.swift @@ -0,0 +1,303 @@ +import Foundation + +/// User playlists plus import/export (Android Playlists.java, desktop playlistio.rs). +@MainActor +final class Playlists: ObservableObject { + static let shared = Playlists() + + struct PL: Codable, Identifiable, Hashable { + var id = UUID() + var name: String + var paths: [String] + var created = Date().timeIntervalSince1970 + /// Entries that didn't match any library file at import time (shown greyed). + var missing: [String] = [] + } + + @Published private(set) var all: [PL] = [] + private var file: URL { Library.support.appendingPathComponent("playlists.json") } + private var importedFile: URL { Library.support.appendingPathComponent("playlists_imported.json") } + private var imported: [String: Double] = [:] + + static var folder: URL { Library.root.appendingPathComponent("Playlists") } + + private init() { + if let d = try? Data(contentsOf: file), let a = try? JSONDecoder().decode([PL].self, from: d) { all = a } + if let d = try? Data(contentsOf: importedFile), let m = try? JSONDecoder().decode([String: Double].self, from: d) { imported = m } + } + + private func save() { + if let d = try? JSONEncoder().encode(all) { try? d.write(to: file, options: .atomic) } + } + + func songs(_ pl: PL) -> [Song] { + let lib = Library.shared + return pl.paths.compactMap { lib.song(path: $0) ?? ($0.hasPrefix("http") ? Song(path: $0, title: $0) : nil) } + } + + func uniqueName(_ base: String) -> String { + let names = Set(all.map { $0.name.lowercased() }) + if !names.contains(base.lowercased()) { return base } + var i = 2 + while names.contains("\(base) (\(i))".lowercased()) { i += 1 } + return "\(base) (\(i))" + } + + @discardableResult + func create(_ name: String, _ songs: [Song]) -> PL { + let pl = PL(name: uniqueName(name.isEmpty ? "New playlist" : name), paths: songs.map(\.id)) + all.append(pl) + save() + return pl + } + + /// Creates or replaces by name (used for "Save queue" and folder sync). + func put(_ name: String, _ songs: [Song], missing: [String] = []) { + if let i = all.firstIndex(where: { $0.name == name }) { + all[i].paths = songs.map(\.id) + all[i].missing = missing + } else { + all.append(PL(name: name, paths: songs.map(\.id), missing: missing)) + } + save() + } + + func delete(_ pl: PL) { all.removeAll { $0.id == pl.id }; save() } + + func rename(_ pl: PL, _ name: String) { + guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return } + all[i].name = name + save() + } + + func add(_ pl: PL, _ songs: [Song]) { + guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return } + all[i].paths += songs.map(\.id) + save() + } + + func removeAt(_ pl: PL, _ idx: IndexSet) { + guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return } + all[i].paths.remove(atOffsets: idx) + save() + } + + func move(_ pl: PL, _ from: IndexSet, _ to: Int) { + guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return } + all[i].paths.move(fromOffsets: from, toOffset: to) + save() + } + + func removeDuplicates(_ pl: PL) { + guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return } + var seen = Set() + all[i].paths = all[i].paths.filter { seen.insert($0).inserted } + save() + } + + func removeMissing(_ pl: PL) { + guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return } + let lib = Library.shared + all[i].paths = all[i].paths.filter { lib.song(path: $0) != nil || $0.hasPrefix("http") } + all[i].missing = [] + save() + } + + // MARK: Import + + struct Entry { + var path: String + var title = "" + var artist = "" + var duration: Double = 0 + } + + /// Imports a playlist file; returns (playlist, matched, total). + @discardableResult + func importFile(_ url: URL, name: String? = nil) throws -> (PL, Int, Int) { + let data = try Data(contentsOf: url) + let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .utf16) ?? + String(data: data, encoding: .isoLatin1) ?? "" + let entries = Playlists.parse(text, ext: url.pathExtension.lowercased()) + let dir = url.deletingLastPathComponent() + let lib = Library.shared + var songs: [Song] = [] + var missing: [String] = [] + for e in entries { + if e.path.hasPrefix("http://") || e.path.hasPrefix("https://") { + var s = Song(path: e.path) + s.title = e.title.isEmpty ? e.path : e.title + s.artist = e.artist + songs.append(s) + continue + } + // Relative to the playlist first, then anywhere in the library. + let rel = e.path.hasPrefix("/") ? e.path : dir.appendingPathComponent(e.path).standardizedFileURL.path + if let s = lib.match(rel, title: e.title, artist: e.artist) ?? lib.match(e.path, title: e.title, artist: e.artist) { + songs.append(s) + } else { + missing.append(e.title.isEmpty ? e.path : "\(e.artist) – \(e.title)") + } + } + let n = name ?? url.deletingPathExtension().lastPathComponent + put(n, songs, missing: missing) + return (all.first { $0.name == n }!, songs.count, entries.count) + } + + /// Auto-imports playlist files dropped into Documents/Playlists (re-imports when they change). + func syncFolder() { + let fm = FileManager.default + guard let files = try? fm.contentsOfDirectory(at: Playlists.folder, includingPropertiesForKeys: [.contentModificationDateKey]) else { return } + var changed = false + for f in files where Library.playlistExts.contains(f.pathExtension.lowercased()) { + let m = (try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate?.timeIntervalSince1970) ?? 0 + if imported[f.lastPathComponent] == m { continue } + if (try? importFile(f)) != nil { imported[f.lastPathComponent] = m; changed = true } + } + if changed, let d = try? JSONEncoder().encode(imported) { try? d.write(to: importedFile, options: .atomic) } + } + + nonisolated static func parse(_ text: String, ext: String) -> [Entry] { + let t = text.trimmingCharacters(in: CharacterSet(charactersIn: "\u{FEFF}").union(.whitespacesAndNewlines)) + if ext == "pls" || t.lowercased().hasPrefix("[playlist]") { return parsePLS(t) } + if ext == "xspf" || t.contains(" [Entry] { + var out: [Entry] = [] + var pending: Entry? + for raw in t.components(separatedBy: .newlines) { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.isEmpty { continue } + if line.hasPrefix("#EXTINF:") { + var e = Entry(path: "") + let body = line.dropFirst(8) + if let comma = body.firstIndex(of: ",") { + e.duration = Double(body[.. [Entry] { + var files: [Int: Entry] = [:] + for raw in t.components(separatedBy: .newlines) { + guard let eq = raw.firstIndex(of: "=") else { continue } + let k = raw[.. String { + s.replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">") + .replacingOccurrences(of: """, with: "\"").replacingOccurrences(of: "'", with: "'") + .replacingOccurrences(of: "&", with: "&") + } + + nonisolated static func inner(_ s: String, _ tag: String) -> String? { + guard let a = s.range(of: "<\(tag)>", options: .caseInsensitive), + let b = s.range(of: "", options: .caseInsensitive, range: a.upperBound.. [Entry] { + t.components(separatedBy: "<\(wrapper)>").dropFirst().compactMap { chunk in + guard var loc = inner(chunk, tag) else { return nil } + if loc.hasPrefix("file://"), let u = URL(string: loc) { loc = u.path } + return Entry(path: loc.removingPercentEncoding ?? loc, title: inner(chunk, titleTag) ?? "", + artist: inner(chunk, artistTag) ?? "", duration: (Double(inner(chunk, "duration") ?? "") ?? 0) / 1000) + } + } + + nonisolated static func parseAttr(_ t: String, element: String, attr: String) -> [Entry] { + let re = try! NSRegularExpression(pattern: "<\(element)[^>]*\\b\(attr)\\s*=\\s*\"([^\"]*)\"", options: .caseInsensitive) + return re.matches(in: t, range: NSRange(t.startIndex..., in: t)).compactMap { m in + Range(m.range(at: 1), in: t).map { Entry(path: xmlUnescape(String(t[$0]))) } + } + } + + // MARK: Export (M3U, M3U8, PLS, XSPF, WPL) + + nonisolated static func xmlEscape(_ s: String) -> String { + s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<") + .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) + } + + /// Paths are written relative to the Mulberry folder so the playlist works next to the music on any device. + func render(_ pl: PL, format: String) -> String { + let songs = self.songs(pl) + func loc(_ s: Song) -> String { s.isStream ? s.path : "../" + s.path } + switch format { + case "pls": + var out = "[playlist]\n" + for (i, s) in songs.enumerated() { + out += "File\(i + 1)=\(loc(s))\nTitle\(i + 1)=\(s.displayArtist) - \(s.displayTitle)\nLength\(i + 1)=\(Int(s.duration))\n" + } + return out + "NumberOfEntries=\(songs.count)\nVersion=2\n" + case "xspf": + var out = "\n\n" + out += " \(Playlists.xmlEscape(pl.name))\n \n" + for s in songs { + let path = loc(s).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? loc(s) + out += " \(Playlists.xmlEscape(path))\(Playlists.xmlEscape(s.displayTitle))" + out += "\(Playlists.xmlEscape(s.displayArtist))\(Playlists.xmlEscape(s.album))" + out += "\(Int(s.duration * 1000))\n" + } + return out + " \n\n" + case "wpl": + var out = "\n\n \(Playlists.xmlEscape(pl.name))\n \n \n" + for s in songs { out += " \n" } + return out + " \n \n\n" + default: + var out = "#EXTM3U\n#PLAYLIST:\(pl.name)\n" + for s in songs { out += "#EXTINF:\(Int(s.duration)),\(s.displayArtist) - \(s.displayTitle)\n\(loc(s))\n" } + return out + } + } + + nonisolated static func safeName(_ s: String) -> String { + let bad = CharacterSet(charactersIn: "/\\:*?\"<>|") + return s.components(separatedBy: bad).joined(separator: "_").trimmingCharacters(in: .whitespaces) + } + + /// Writes a playlist into Documents/Playlists (visible in Files) and returns the file URL. + @discardableResult + func export(_ pl: PL, format: String) throws -> URL { + try FileManager.default.createDirectory(at: Playlists.folder, withIntermediateDirectories: true) + let url = Playlists.folder.appendingPathComponent(Playlists.safeName(pl.name) + "." + format) + try render(pl, format: format).write(to: url, atomically: true, encoding: .utf8) + let m = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate?.timeIntervalSince1970) ?? 0 + imported[url.lastPathComponent] = m // don't re-import our own export + if let d = try? JSONEncoder().encode(imported) { try? d.write(to: importedFile, options: .atomic) } + return url + } + + func exportAll(format: String) -> Int { + all.reduce(0) { n, pl in (try? export(pl, format: format)) != nil ? n + 1 : n } + } +} diff --git a/App/Model/Prefs.swift b/App/Model/Prefs.swift new file mode 100644 index 0000000..80d4f1d --- /dev/null +++ b/App/Model/Prefs.swift @@ -0,0 +1,70 @@ +import Foundation +import SwiftUI + +/// Settings, same keys and defaults as the Android Prefs class. +final class Prefs: ObservableObject { + static let shared = Prefs() + private let d = UserDefaults.standard + + @Published var themeMode: String { didSet { d.set(themeMode, forKey: "theme_mode") } } // system/dark/light + @Published var colorSource: String { didSet { d.set(colorSource, forKey: "color_source") } } // album/custom/system + @Published var customColor: Int { didSet { d.set(customColor, forKey: "custom_color") } } + @Published var visualizer: Bool { didSet { d.set(visualizer, forKey: "visualizer") } } + @Published var bassShape: Bool { didSet { d.set(bassShape, forKey: "bass_shape") } } + @Published var widgetAnim: Int { didSet { d.set(widgetAnim, forKey: "widget_anim") } } // fps, 0 = off + @Published var lowPower: Bool { didSet { d.set(lowPower, forKey: "low_power") } } + @Published var crossfade: Int { didSet { d.set(crossfade, forKey: "crossfade") } } // seconds + @Published var fadePause: Bool { didSet { d.set(fadePause, forKey: "fade_pause") } } + @Published var gapless: Bool { didSet { d.set(gapless, forKey: "gapless") } } + @Published var resume: Bool { didSet { d.set(resume, forKey: "resume") } } + @Published var pauseOnDetach: Bool { didSet { d.set(pauseOnDetach, forKey: "pause_detach") } } + @Published var minDuration: Int { didSet { d.set(minDuration, forKey: "min_duration") } } // seconds + @Published var lyricsSource: String { didSet { d.set(lyricsSource, forKey: "lyrics_source") } } // auto/local/lrclib/netease/off + @Published var lyricsPlain: Bool { didSet { d.set(lyricsPlain, forKey: "lyrics_plain") } } + @Published var onlineLyrics: Bool { didSet { d.set(onlineLyrics, forKey: "online_lyrics") } } + @Published var onlineCovers: Bool { didSet { d.set(onlineCovers, forKey: "online_covers") } } + @Published var lfmEnabled: Bool { didSet { d.set(lfmEnabled, forKey: "lfm_enabled") } } + @Published var lfmUser: String { didSet { d.set(lfmUser, forKey: "lfm_user") } } + @Published var lfmSession: String { didSet { d.set(lfmSession, forKey: "lfm_session") } } + @Published var lbToken: String { didSet { d.set(lbToken, forKey: "lb_token") } } + @Published var shuffle: Bool { didSet { d.set(shuffle, forKey: "shuffle") } } + @Published var repeatMode: Int { didSet { d.set(repeatMode, forKey: "repeat") } } // 0 off, 1 all, 2 one + @Published var libTab: Int { didSet { d.set(libTab, forKey: "lib_tab") } } + @Published var sortKey: String { didSet { d.set(sortKey, forKey: "sort_key") } } + @Published var replayGain: Bool { didSet { d.set(replayGain, forKey: "replay_gain") } } + @Published var eqBands: [Double] { didSet { d.set(eqBands, forKey: "eq_bands") } } + @Published var eqOn: Bool { didSet { d.set(eqOn, forKey: "eq_on") } } + + private init() { + let d = UserDefaults.standard + func g(_ k: String, _ v: T) -> T { (d.object(forKey: k) as? T) ?? v } + themeMode = g("theme_mode", "system") + colorSource = g("color_source", "album") + customColor = g("custom_color", Int(Palette.defaultSeed)) + visualizer = g("visualizer", true) + bassShape = g("bass_shape", true) + widgetAnim = g("widget_anim", 15) + lowPower = g("low_power", false) + crossfade = g("crossfade", 5) + fadePause = g("fade_pause", true) + gapless = g("gapless", true) + resume = g("resume", true) + pauseOnDetach = g("pause_detach", true) + minDuration = g("min_duration", 20) + lyricsSource = g("lyrics_source", "auto") + lyricsPlain = g("lyrics_plain", false) + onlineLyrics = g("online_lyrics", true) + onlineCovers = g("online_covers", true) + lfmEnabled = g("lfm_enabled", false) + lfmUser = g("lfm_user", "") + lfmSession = g("lfm_session", "") + lbToken = g("lb_token", "") + shuffle = g("shuffle", false) + repeatMode = g("repeat", 0) + libTab = g("lib_tab", 0) + sortKey = g("sort_key", "title") + replayGain = g("replay_gain", false) + eqBands = g("eq_bands", [Double](repeating: 0, count: 10)) + eqOn = g("eq_on", false) + } +} diff --git a/App/Model/Song.swift b/App/Model/Song.swift new file mode 100644 index 0000000..3b8dad0 --- /dev/null +++ b/App/Model/Song.swift @@ -0,0 +1,59 @@ +import Foundation + +struct Song: Codable, Hashable, Identifiable { + /// Path relative to the music root (Documents) for local files, or a full URL for streams. + var path: String + var title = "" + var artist = "" + var album = "" + var albumArtist = "" + var genre = "" + var track = 0 + var disc = 0 + var year = 0 + var duration: Double = 0 + var dateAdded: Double = 0 + var size: Int64 = 0 + var mtime: Double = 0 + var hasCover = false + /// For cue-sheet tracks: start/end inside the file, in seconds. + var start: Double = 0 + var end: Double = 0 + var cueIndex = 0 + + var id: String { cueIndex > 0 ? "\(path)#\(cueIndex)" : path } + + var isStream: Bool { path.hasPrefix("http://") || path.hasPrefix("https://") } + + var url: URL { + isStream ? URL(string: path)! : Library.root.appendingPathComponent(path) + } + + var fileName: String { (path as NSString).lastPathComponent } + + var folder: String { (path as NSString).deletingLastPathComponent } + + var displayTitle: String { + if !title.isEmpty { return title } + return (fileName as NSString).deletingPathExtension + } + + var displayArtist: String { + if artist.isEmpty || artist == "" { return albumArtist } + return artist + } + + var groupArtist: String { + let a = albumArtist.isEmpty ? displayArtist : albumArtist + return a.isEmpty ? "Unknown artist" : a + } + + var displayAlbum: String { album.isEmpty ? "Unknown album" : album } + + var albumKey: String { "\(groupArtist.lowercased())\u{1}\(album.lowercased())" } + + /// "Artist · Album" subtitle used across lists (Android SongAdapter). + var subtitle: String { + [displayArtist, album].filter { !$0.isEmpty }.joined(separator: " · ") + } +} diff --git a/App/Model/TagReader.swift b/App/Model/TagReader.swift new file mode 100644 index 0000000..2bc747e --- /dev/null +++ b/App/Model/TagReader.swift @@ -0,0 +1,548 @@ +import Foundation + +/// Tag reader for the common audio containers: ID3v2/ID3v1 (MP3, AIFF, WAV chunks), FLAC, MP4/M4A, +/// Ogg Vorbis/Opus/FLAC and APEv2 (APE, WavPack, Musepack). Reads only the header region of the file. +struct Tags { + var title = "", artist = "", album = "", albumArtist = "", genre = "", lyrics = "" + var track = 0, disc = 0, year = 0 + var duration: Double = 0 + var cover: Data? + var trackGain: Double? + var albumGain: Double? +} + +enum TagReader { + static func read(_ url: URL, wantCover: Bool = false) -> Tags { + guard let fh = try? FileHandle(forReadingFrom: url) else { return Tags() } + defer { try? fh.close() } + let ext = url.pathExtension.lowercased() + var t = Tags() + let head = (try? fh.read(upToCount: 12)) ?? Data() + if head.starts(with: [0x49, 0x44, 0x33]) { // "ID3" + id3v2(fh, &t, wantCover) + if ext == "flac" { flac(fh, &t, wantCover, skipID3: true) } + } else if head.starts(with: Array("fLaC".utf8)) { + flac(fh, &t, wantCover, skipID3: false) + } else if head.count >= 8 && head[4..<8] == Data("ftyp".utf8) { + mp4(fh, &t, wantCover) + } else if head.starts(with: Array("OggS".utf8)) { + ogg(fh, &t, wantCover) + } else if head.starts(with: Array("RIFF".utf8)) || head.starts(with: Array("FORM".utf8)) { + riff(fh, &t, wantCover, big: head.starts(with: Array("FORM".utf8))) + } + if t.title.isEmpty && t.artist.isEmpty { ape(fh, &t, wantCover) } + if t.title.isEmpty && t.artist.isEmpty { id3v1(fh, &t) } + return t + } + + // MARK: helpers + + static func read(_ fh: FileHandle, _ off: UInt64, _ n: Int) -> Data { + guard n > 0, (try? fh.seek(toOffset: off)) != nil else { return Data() } + return (try? fh.read(upToCount: n)) ?? Data() + } + + static func be32(_ d: Data, _ i: Int) -> UInt32 { + guard i + 4 <= d.count else { return 0 } + let b = d.startIndex + i + return UInt32(d[b]) << 24 | UInt32(d[b + 1]) << 16 | UInt32(d[b + 2]) << 8 | UInt32(d[b + 3]) + } + + static func le32(_ d: Data, _ i: Int) -> UInt32 { + guard i + 4 <= d.count else { return 0 } + let b = d.startIndex + i + return UInt32(d[b + 3]) << 24 | UInt32(d[b + 2]) << 16 | UInt32(d[b + 1]) << 8 | UInt32(d[b]) + } + + static func syncsafe(_ d: Data, _ i: Int) -> Int { + let b = d.startIndex + i + return Int(d[b]) << 21 | Int(d[b + 1]) << 14 | Int(d[b + 2]) << 7 | Int(d[b + 3]) + } + + static func num(_ s: String) -> Int { + Int(s.split(whereSeparator: { $0 == "/" || $0 == "-" || $0 == " " }).first.map(String.init)? + .trimmingCharacters(in: .whitespaces) ?? "") ?? 0 + } + + static func gain(_ s: String) -> Double? { + Double(s.lowercased().replacingOccurrences(of: "db", with: "").trimmingCharacters(in: .whitespaces)) + } + + /// Applies one "KEY=value" style field (Vorbis comments / APE / MP4 freeform). + static func apply(_ key: String, _ value: String, _ t: inout Tags) { + let v = value.trimmingCharacters(in: .whitespacesAndNewlines.union(.controlCharacters)) + guard !v.isEmpty else { return } + switch key.uppercased() { + case "TITLE": if t.title.isEmpty { t.title = v } + case "ARTIST": if t.artist.isEmpty { t.artist = v } + case "ALBUM": if t.album.isEmpty { t.album = v } + case "ALBUMARTIST", "ALBUM ARTIST", "ALBUM_ARTIST": if t.albumArtist.isEmpty { t.albumArtist = v } + case "GENRE": if t.genre.isEmpty { t.genre = v } + case "TRACKNUMBER", "TRACK": if t.track == 0 { t.track = num(v) } + case "DISCNUMBER", "DISC": if t.disc == 0 { t.disc = num(v) } + case "DATE", "YEAR", "ORIGINALDATE": if t.year == 0 { t.year = num(String(v.prefix(4))) } + case "LYRICS", "UNSYNCEDLYRICS", "UNSYNCED LYRICS": if t.lyrics.isEmpty { t.lyrics = v } + case "REPLAYGAIN_TRACK_GAIN": t.trackGain = gain(v) + case "REPLAYGAIN_ALBUM_GAIN": t.albumGain = gain(v) + default: break + } + } + + // MARK: ID3v2 + + static func id3text(_ d: Data) -> String { + guard let enc = d.first else { return "" } + let body = d.dropFirst() + let s: String? + switch enc { + case 1: s = String(data: body, encoding: .utf16) + case 2: s = String(data: body, encoding: .utf16BigEndian) + case 3: s = String(data: body, encoding: .utf8) + default: s = String(data: body, encoding: .isoLatin1) + } + // Multiple values are NUL separated; keep them joined with "; ". + return (s ?? "").split(separator: "\0").map(String.init).filter { !$0.isEmpty }.joined(separator: "; ") + } + + /// Splits at the first terminator for the given ID3 text encoding. + static func splitTerm(_ d: Data, enc: UInt8) -> (Data, Data) { + let wide = enc == 1 || enc == 2 + var i = d.startIndex + while i < d.endIndex { + if wide { + if i + 1 < d.endIndex && d[i] == 0 && d[i + 1] == 0 && (i - d.startIndex) % 2 == 0 { + return (d[d.startIndex.. String { + switch enc { + case 1: return String(data: d, encoding: .utf16) ?? "" + case 2: return String(data: d, encoding: .utf16BigEndian) ?? "" + case 3: return String(data: d, encoding: .utf8) ?? "" + default: return String(data: d, encoding: .isoLatin1) ?? "" + } + } + + static let id3Genres = ["Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", + "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", + "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", + "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", + "Gospel", "Noise", "Alternative Rock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", + "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", + "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", + "Jungle", "Native American", "Cabaret", "New Wave", "Psychedelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", + "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock"] + + static func genreName(_ g: String) -> String { + // "(17)", "17" or "(17)Rock" forms. + var s = g + if s.hasPrefix("("), let close = s.firstIndex(of: ")") { + let n = Int(s[s.index(after: s.startIndex)..= 4 { // extended header + i = ver >= 4 ? syncsafe(d, 0) : Int(be32(d, 0)) + 4 + } + let idLen = ver == 2 ? 3 : 4 + let hdrLen = ver == 2 ? 6 : 10 + while i + hdrLen <= d.count { + let b = d.startIndex + i + guard d[b] != 0 else { break } + let id = String(data: d[b..<(b + idLen)], encoding: .ascii) ?? "" + var fsz: Int + if ver == 2 { + fsz = Int(d[b + 3]) << 16 | Int(d[b + 4]) << 8 | Int(d[b + 5]) + } else if ver >= 4 { + fsz = syncsafe(d, i + 4) + } else { + fsz = Int(be32(d, i + 4)) + } + var fflags: UInt8 = 0 + if ver >= 3 { fflags = d[b + 9] } + let start = i + hdrLen + guard fsz > 0, start + fsz <= d.count else { break } + var body = d[(d.startIndex + start)..<(d.startIndex + start + fsz)] + if ver >= 4 && fflags & 0x02 != 0 { body = unsync(Data(body))[...] } + if ver >= 4 && fflags & 0x01 != 0 && body.count > 4 { body = body.dropFirst(4) } + frame(id, Data(body), &t, wantCover) + i = start + fsz + } + } + + static func unsync(_ d: Data) -> Data { + var out = Data(capacity: d.count) + var prevFF = false + for byte in d { + if prevFF && byte == 0 { prevFF = false; continue } + out.append(byte) + prevFF = byte == 0xFF + } + return out + } + + static func frame(_ id: String, _ body: Data, _ t: inout Tags, _ wantCover: Bool) { + switch id { + case "TIT2", "TT2": if t.title.isEmpty { t.title = id3text(body) } + case "TPE1", "TP1": if t.artist.isEmpty { t.artist = id3text(body) } + case "TALB", "TAL": if t.album.isEmpty { t.album = id3text(body) } + case "TPE2", "TP2": if t.albumArtist.isEmpty { t.albumArtist = id3text(body) } + case "TCON", "TCO": if t.genre.isEmpty { t.genre = genreName(id3text(body)) } + case "TRCK", "TRK": if t.track == 0 { t.track = num(id3text(body)) } + case "TPOS", "TPA": if t.disc == 0 { t.disc = num(id3text(body)) } + case "TYER", "TYE", "TDRC", "TDOR": if t.year == 0 { t.year = num(String(id3text(body).prefix(4))) } + case "TXXX", "TXX": + guard let enc = body.first else { return } + let (k, v) = splitTerm(body.dropFirst(), enc: enc) + apply(decode(k, enc: enc), decode(v, enc: enc).replacingOccurrences(of: "\0", with: ""), &t) + case "USLT", "ULT": + guard t.lyrics.isEmpty, body.count > 4, let enc = body.first else { return } + let (_, text) = splitTerm(body.dropFirst(4), enc: enc) + t.lyrics = decode(text, enc: enc) + case "APIC", "PIC": + guard wantCover, t.cover == nil, let enc = body.first else { return } + var rest = body.dropFirst() + if id == "PIC" { + rest = rest.dropFirst(3) + } else { + rest = splitTerm(rest, enc: 0).1 // mime is always Latin-1 + } + guard !rest.isEmpty else { return } + let picType = rest.first! + let (_, img) = splitTerm(rest.dropFirst(), enc: enc) + if !img.isEmpty && (picType == 3 || picType == 0 || t.cover == nil) { t.cover = Data(img) } + default: break + } + } + + static func id3v1(_ fh: FileHandle, _ t: inout Tags) { + guard let end = try? fh.seekToEnd(), end > 128 else { return } + let d = read(fh, end - 128, 128) + guard d.count == 128, d.starts(with: Array("TAG".utf8)) else { return } + func s(_ a: Int, _ n: Int) -> String { + let sub = d[(d.startIndex + a)..<(d.startIndex + a + n)] + return (String(data: sub, encoding: .isoLatin1) ?? "") + .trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: "\0"))) + } + t.title = s(3, 30); t.artist = s(33, 30); t.album = s(63, 30); t.year = Int(s(93, 4)) ?? 0 + if d[d.startIndex + 125] == 0 && d[d.startIndex + 126] != 0 { t.track = Int(d[d.startIndex + 126]) } + let g = Int(d[d.startIndex + 127]) + if g < id3Genres.count { t.genre = id3Genres[g] } + } + + // MARK: FLAC / Vorbis comments + + static func id3Size(_ fh: FileHandle) -> UInt64 { + let h = read(fh, 0, 10) + guard h.count == 10, h.starts(with: [0x49, 0x44, 0x33]) else { return 0 } + return UInt64(10 + syncsafe(h, 6) + (h[5] & 0x10 != 0 ? 10 : 0)) + } + + static func flac(_ fh: FileHandle, _ t: inout Tags, _ wantCover: Bool, skipID3: Bool) { + var off = skipID3 ? id3Size(fh) : 0 + guard read(fh, off, 4) == Data("fLaC".utf8) else { return } + off += 4 + while true { + let h = read(fh, off, 4) + guard h.count == 4 else { return } + let last = h[h.startIndex] & 0x80 != 0 + let type = h[h.startIndex] & 0x7F + let len = Int(h[h.startIndex + 1]) << 16 | Int(h[h.startIndex + 2]) << 8 | Int(h[h.startIndex + 3]) + off += 4 + if type == 0 { + let si = read(fh, off, 18) + if si.count == 18 { + let b = si.startIndex + let rate = Int(si[b + 10]) << 12 | Int(si[b + 11]) << 4 | Int(si[b + 12]) >> 4 + let total = (UInt64(si[b + 13]) & 0x0F) << 32 | UInt64(be32(si, 14)) + if rate > 0 { t.duration = Double(total) / Double(rate) } + } + } else if type == 4 { + vorbisComments(read(fh, off, len), &t, wantCover) + } else if type == 6 && wantCover && t.cover == nil { + t.cover = flacPicture(read(fh, off, len)) + } + off += UInt64(len) + if last { return } + } + } + + static func flacPicture(_ d: Data) -> Data? { + var i = 4 + let mimeLen = Int(be32(d, i)); i += 4 + mimeLen + let descLen = Int(be32(d, i)); i += 4 + descLen + 16 + let dataLen = Int(be32(d, i)); i += 4 + guard dataLen > 0, i + dataLen <= d.count else { return nil } + return d.subdata(in: (d.startIndex + i)..<(d.startIndex + i + dataLen)) + } + + static func vorbisComments(_ d: Data, _ t: inout Tags, _ wantCover: Bool) { + var i = 0 + let vlen = Int(le32(d, i)); i += 4 + vlen + let n = Int(le32(d, i)); i += 4 + for _ in 0..= 0, i + l <= d.count else { return } + let s = String(data: d.subdata(in: (d.startIndex + i)..<(d.startIndex + i + l)), encoding: .utf8) ?? "" + i += l + guard let eq = s.firstIndex(of: "=") else { continue } + let key = String(s[.. 16 << 20 { break } + } + guard packets.count == 2 else { return } + let ident = packets[0], comment = packets[1] + var rate = 0, preskip = 0 + if ident.starts(with: Array("OpusHead".utf8)) { + rate = 48000 + preskip = ident.count > 11 ? Int(ident[ident.startIndex + 10]) | Int(ident[ident.startIndex + 11]) << 8 : 0 + if comment.starts(with: Array("OpusTags".utf8)) { vorbisComments(comment.dropFirst(8), &t, wantCover) } + } else if ident.starts(with: [0x01] + Array("vorbis".utf8)) { + rate = Int(le32(ident, 12)) + if comment.starts(with: [0x03] + Array("vorbis".utf8)) { vorbisComments(comment.dropFirst(7), &t, wantCover) } + } else if ident.starts(with: [0x7F] + Array("FLAC".utf8)) { + if ident.count > 36 { + let si = ident.subdata(in: (ident.startIndex + 17)..<(ident.startIndex + 35)) + rate = Int(si[10]) << 12 | Int(si[11]) << 4 | Int(si[12]) >> 4 + } + vorbisComments(comment.dropFirst(4), &t, wantCover) + } + // Duration from the last page's granule position. + if rate > 0, let end = try? fh.seekToEnd() { + let span = min(end, 65536) + let tail = read(fh, end - span, Int(span)) + if let r = tail.lastRange(of: Data("OggS".utf8)) { + let p = r.lowerBound - tail.startIndex + if p + 14 <= tail.count { + let lo = UInt64(le32(tail, p + 6)), hi = UInt64(le32(tail, p + 10)) + let g = Int64(bitPattern: hi << 32 | lo) + if g > 0 { t.duration = Double(max(0, g - Int64(preskip))) / Double(rate) } + } + } + } + } + + // MARK: MP4 + + static func mp4(_ fh: FileHandle, _ t: inout Tags, _ wantCover: Bool) { + guard let end = try? fh.seekToEnd() else { return } + func atoms(_ start: UInt64, _ stop: UInt64, _ visit: (String, UInt64, UInt64) -> Void) { + var off = start + while off + 8 <= stop { + let h = read(fh, off, 16) + guard h.count >= 8 else { return } + var size = UInt64(be32(h, 0)) + let type = String(data: h.subdata(in: (h.startIndex + 4)..<(h.startIndex + 8)), encoding: .isoLatin1) ?? "" + var hdr: UInt64 = 8 + if size == 1, h.count == 16 { size = UInt64(be32(h, 8)) << 32 | UInt64(be32(h, 12)); hdr = 16 } + if size == 0 { size = stop - off } + guard size >= hdr else { return } + visit(type, off + hdr, off + size) + off += size + } + } + atoms(0, end) { type, s, e in + guard type == "moov" else { return } + atoms(s, e) { type, s, e in + if type == "mvhd" { + let d = read(fh, s, 32) + if d.first == 1 { + let scale = be32(d, 20) + let dur = UInt64(be32(d, 24)) << 32 | UInt64(be32(d, 28)) + if scale > 0 { t.duration = Double(dur) / Double(scale) } + } else { + let scale = be32(d, 12), dur = be32(d, 16) + if scale > 0 { t.duration = Double(dur) / Double(scale) } + } + } + guard type == "udta" else { return } + atoms(s, e) { type, s, e in + guard type == "meta" else { return } + atoms(s + 4, e) { type, s, e in + guard type == "ilst" else { return } + atoms(s, e) { key, s, e in ilstItem(fh, key, s, e, &t, wantCover) } + } + } + } + } + } + + static func ilstItem(_ fh: FileHandle, _ key: String, _ s: UInt64, _ e: UInt64, _ t: inout Tags, _ wantCover: Bool) { + let len = Int(e - s) + if key == "covr" && !wantCover { return } + guard len > 0, len < 32 << 20 else { return } + let d = read(fh, s, len) + var name = "", mean = "" + var value: Data? + var dtype: UInt32 = 0 + var i = 0 + while i + 8 <= d.count { + let sz = Int(be32(d, i)) + guard sz >= 8, i + sz <= d.count else { break } + let typ = String(data: d.subdata(in: (d.startIndex + i + 4)..<(d.startIndex + i + 8)), encoding: .isoLatin1) + let payload = d.subdata(in: (d.startIndex + i + 8)..<(d.startIndex + i + sz)) + switch typ { + case "data": + if value == nil, payload.count >= 8 { dtype = be32(payload, 0) & 0xFFFFFF; value = payload.dropFirst(8) } + case "name": name = String(data: payload.dropFirst(4), encoding: .utf8) ?? "" + case "mean": mean = String(data: payload.dropFirst(4), encoding: .utf8) ?? "" + default: break + } + i += sz + } + guard let v = value else { return } + _ = mean + let str = { String(data: v, encoding: .utf8) ?? "" } + switch key { + case "\u{A9}nam": t.title = str() + case "\u{A9}ART": t.artist = str() + case "\u{A9}alb": t.album = str() + case "aART": t.albumArtist = str() + case "\u{A9}gen": t.genre = str() + case "gnre": if v.count >= 2 { let g = Int(v[v.startIndex]) << 8 | Int(v[v.startIndex + 1]); if g > 0 && g <= id3Genres.count { t.genre = id3Genres[g - 1] } } + case "\u{A9}day": t.year = num(String(str().prefix(4))) + case "\u{A9}lyr": t.lyrics = str() + case "trkn": if v.count >= 4 { t.track = Int(v[v.startIndex + 2]) << 8 | Int(v[v.startIndex + 3]) } + case "disk": if v.count >= 4 { t.disc = Int(v[v.startIndex + 2]) << 8 | Int(v[v.startIndex + 3]) } + case "covr": if t.cover == nil && (dtype == 13 || dtype == 14 || dtype == 0) { t.cover = Data(v) } + case "----": apply(name, str(), &t) + default: break + } + } + + // MARK: RIFF/AIFF (WAV, AIFF) – ID3 chunk and LIST/INFO + + static func riff(_ fh: FileHandle, _ t: inout Tags, _ wantCover: Bool, big: Bool) { + guard let end = try? fh.seekToEnd() else { return } + var off: UInt64 = 12 + while off + 8 <= end { + let h = read(fh, off, 8) + guard h.count == 8 else { return } + let id = String(data: h.prefix(4), encoding: .isoLatin1)?.lowercased() ?? "" + let size = UInt64(big ? be32(h, 4) : le32(h, 4)) + if id == "id3 " { + let d = read(fh, off + 8, Int(size)) + let tmp = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + if (try? d.write(to: tmp)) != nil, let f2 = try? FileHandle(forReadingFrom: tmp) { + id3v2(f2, &t, wantCover) + try? f2.close() + } + try? FileManager.default.removeItem(at: tmp) + } else if id == "list" { + let d = read(fh, off + 8, Int(min(size, 1 << 20))) + if d.starts(with: Array("INFO".utf8)) { + var i = 4 + while i + 8 <= d.count { + let k = String(data: d.subdata(in: (d.startIndex + i)..<(d.startIndex + i + 4)), encoding: .isoLatin1) ?? "" + let l = Int(le32(d, i + 4)) + guard i + 8 + l <= d.count else { break } + let v = String(data: d.subdata(in: (d.startIndex + i + 8)..<(d.startIndex + i + 8 + l)), encoding: .utf8)? + .trimmingCharacters(in: CharacterSet(charactersIn: "\0 ")) ?? "" + switch k { + case "INAM": if t.title.isEmpty { t.title = v } + case "IART": if t.artist.isEmpty { t.artist = v } + case "IPRD": if t.album.isEmpty { t.album = v } + case "IGNR": if t.genre.isEmpty { t.genre = v } + case "ICRD": if t.year == 0 { t.year = num(String(v.prefix(4))) } + case "ITRK", "IPRT": if t.track == 0 { t.track = num(v) } + default: break + } + i += 8 + l + (l & 1) + } + } + } + off += 8 + size + (size & 1) + } + } + + // MARK: APEv2 + + static func ape(_ fh: FileHandle, _ t: inout Tags, _ wantCover: Bool) { + guard let end = try? fh.seekToEnd(), end > 64 else { return } + var footerOff = end - 32 + var foot = read(fh, footerOff, 32) + if !foot.starts(with: Array("APETAGEX".utf8)) { + footerOff = end - 128 - 32 // behind an ID3v1 tag + guard end > 160 else { return } + foot = read(fh, footerOff, 32) + guard foot.starts(with: Array("APETAGEX".utf8)) else { return } + } + let size = Int(le32(foot, 12)), count = Int(le32(foot, 16)) + guard size > 32, UInt64(size) <= footerOff + 32 else { return } + let d = read(fh, footerOff + 32 - UInt64(size), size - 32) + var i = 0 + for _ in 0..> 1) & 3 == 1 { // binary + if wantCover, t.cover == nil, key.lowercased().hasPrefix("cover art"), let z = val.firstIndex(of: 0) { + t.cover = val.subdata(in: (z + 1).. = ["mp3", "flac", "m4a", "m4b", "aac", "alac", "mp4", "ogg", "oga", "opus", "aif", "aiff", "wav"] + + static func canWrite(_ url: URL) -> Bool { writable.contains(url.pathExtension.lowercased()) } + + static func write(_ url: URL, _ e: TagEdit) throws { + guard !e.isEmpty else { return } + var data = try Data(contentsOf: url, options: .mappedIfSafe) + let head = data.prefix(12) + if head.starts(with: Array("fLaC".utf8)) || (head.starts(with: [0x49, 0x44, 0x33]) && url.pathExtension.lowercased() == "flac") { + data = try flac(data, e) + } else if head.count >= 8 && head[4..<8] == Data("ftyp".utf8) { + data = try mp4(data, e) + } else if head.starts(with: Array("OggS".utf8)) { + data = try ogg(data, e) + } else if ["aif", "aiff", "wav"].contains(url.pathExtension.lowercased()) { + data = try riffID3(data, e, big: head.starts(with: Array("FORM".utf8))) + } else if ["mp3", "aac", "mp2"].contains(url.pathExtension.lowercased()) || head.starts(with: [0x49, 0x44, 0x33]) { + data = try mp3(data, e) + } else { + throw Failure.unsupported(url.pathExtension) + } + let tmp = url.deletingLastPathComponent().appendingPathComponent(".\(UUID().uuidString).tmp") + try data.write(to: tmp) + _ = try FileManager.default.replaceItemAt(url, withItemAt: tmp) + } + + // MARK: bytes + + static func be32(_ v: Int) -> Data { Data([UInt8(v >> 24 & 0xFF), UInt8(v >> 16 & 0xFF), UInt8(v >> 8 & 0xFF), UInt8(v & 0xFF)]) } + static func le32(_ v: Int) -> Data { Data([UInt8(v & 0xFF), UInt8(v >> 8 & 0xFF), UInt8(v >> 16 & 0xFF), UInt8(v >> 24 & 0xFF)]) } + static func syncsafe(_ v: Int) -> Data { Data([UInt8(v >> 21 & 0x7F), UInt8(v >> 14 & 0x7F), UInt8(v >> 7 & 0x7F), UInt8(v & 0x7F)]) } + static func rd32(_ d: Data, _ i: Int) -> Int { Int(TagReader.be32(d, i)) } + static func rdle32(_ d: Data, _ i: Int) -> Int { Int(TagReader.le32(d, i)) } + + static func imageMime(_ d: Data) -> String { + if d.starts(with: [0x89, 0x50, 0x4E, 0x47]) { return "image/png" } + if d.count > 12 && d[d.startIndex + 8.. [String: Data?] { + func text(_ s: String) -> Data { Data([3]) + Data(s.utf8) } + var f: [String: Data?] = [:] + func set(_ id: String, _ v: String?) { if let v { f[id] = v.isEmpty ? .some(nil) : text(v) } } + set("TIT2", e.title); set("TPE1", e.artist); set("TALB", e.album); set("TPE2", e.albumArtist) + set("TCON", e.genre); set("TDRC", e.year); set("TRCK", e.track); set("TPOS", e.disc) + if let l = e.lyrics { f["USLT"] = l.isEmpty ? .some(nil) : Data([3]) + Data("eng".utf8) + Data([0]) + Data(l.utf8) } + if let c = e.cover { + if let c { f["APIC"] = Data([0]) + Data(imageMime(c).utf8) + Data([0, 3, 0]) + c } else { f["APIC"] = .some(nil) } + } + return f + } + + /// Builds a new ID3v2.4 tag from an existing one (if any) plus the edits. Returns (tag, oldTagLength). + static func buildID3(_ old: Data?, _ e: TagEdit, padding: Int) -> Data { + let edits = id3Frames(e) + var frames = Data() + var replaced = Set() + if let old, old.count >= 10, old.starts(with: [0x49, 0x44, 0x33]) { + let ver = old[old.startIndex + 3] + let flags = old[old.startIndex + 5] + var body = old.dropFirst(10) + if flags & 0x80 != 0 && ver < 4 { body = TagReader.unsync(Data(body))[...] } + let b = Data(body) + var i = 0 + if flags & 0x40 != 0 && b.count >= 4 { i = ver >= 4 ? TagReader.syncsafe(b, 0) : rd32(b, 0) + 4 } + if ver >= 3 { + while i + 10 <= b.count { + guard b[i] != 0 else { break } + let id = String(data: b[i..= 4 ? TagReader.syncsafe(b, i + 4) : rd32(b, i + 4) + guard sz > 0, i + 10 + sz <= b.count else { break } + let fflags = Data(b[(i + 8)..<(i + 10)]) + var payload = b[(i + 10)..<(i + 10 + sz)] + let key = (id == "TYER" || id == "TDAT") ? "TDRC" : id + if edits.keys.contains(key) || id == "TYER" && edits.keys.contains("TDRC") { + replaced.insert(key) + } else { + // v2.3 frames copy over unchanged except for the size encoding; drop v2.3-only flags. + if ver == 3 && fflags[fflags.startIndex + 1] & 0x80 != 0 { i += 10 + sz; continue } // compressed + if ver >= 4 && fflags[fflags.startIndex + 1] & 0x02 != 0 { payload = TagReader.unsync(Data(payload))[...] } + frames += Data(id.utf8) + syncsafe(payload.count) + Data([0, 0]) + payload + } + i += 10 + sz + } + } + } + for (id, v) in edits.sorted(by: { $0.key < $1.key }) { + guard let v else { continue } + frames += Data(id.utf8) + syncsafe(v.count) + Data([0, 0]) + v + } + _ = replaced + let size = frames.count + padding + return Data("ID3".utf8) + Data([4, 0, 0]) + syncsafe(size) + frames + Data(count: padding) + } + + static func id3Length(_ d: Data) -> Int { + guard d.count >= 10, d.starts(with: [0x49, 0x44, 0x33]) else { return 0 } + return 10 + TagReader.syncsafe(d, 6) + (d[d.startIndex + 5] & 0x10 != 0 ? 10 : 0) + } + + static func mp3(_ d: Data, _ e: TagEdit) throws -> Data { + let oldLen = id3Length(d) + let old = oldLen > 0 ? d.prefix(oldLen) : nil + var tag = buildID3(old, e, padding: 0) + // Reuse existing space when the new tag fits, so the audio doesn't have to move much. + if oldLen >= tag.count && oldLen - tag.count < 64 << 10 { + tag = buildID3(old, e, padding: oldLen - tag.count) + } else { + tag = buildID3(old, e, padding: 2048) + } + var audio = d.dropFirst(oldLen) + // Drop a stale ID3v1 tag so readers don't prefer the old values. + if audio.count > 128, audio.suffix(128).starts(with: Array("TAG".utf8)) { audio = audio.dropLast(128) } + return tag + audio + } + + static func riffID3(_ d: Data, _ e: TagEdit, big: Bool) throws -> Data { + var out = d.prefix(12) + var off = 12 + var old: Data? + var chunks = Data() + while off + 8 <= d.count { + let id = String(data: d[(d.startIndex + off)..<(d.startIndex + off + 4)], encoding: .isoLatin1)?.lowercased() ?? "" + let size = big ? rd32(d, off + 4) : rdle32(d, off + 4) + let total = 8 + size + (size & 1) + guard off + 8 + size <= d.count else { break } + if id == "id3 " { old = d.subdata(in: (d.startIndex + off + 8)..<(d.startIndex + off + 8 + size)) } + else { chunks += d.subdata(in: (d.startIndex + off)..<(d.startIndex + min(d.count, off + total))) } + off += total + } + let tag = buildID3(old, e, padding: 0) + let tagChunk = Data((big ? "ID3 " : "id3 ").utf8) + (big ? be32(tag.count) : le32(tag.count)) + tag + (tag.count & 1 == 1 ? Data([0]) : Data()) + out += chunks + tagChunk + let formSize = out.count - 8 + out.replaceSubrange((out.startIndex + 4)..<(out.startIndex + 8), with: big ? be32(formSize) : le32(formSize)) + return out + } + + // MARK: Vorbis comments (FLAC, Ogg) + + static func vorbisBlock(_ old: Data?, _ e: TagEdit, vendor fallback: String = "Mulberry") -> Data { + var vendor = fallback + var fields: [(String, String)] = [] + let editKeys = Set(e.vorbis.map { $0.0 }) + var removeKeys = editKeys + if e.cover != nil { removeKeys.insert("METADATA_BLOCK_PICTURE") } + if e.year != nil { removeKeys.formUnion(["YEAR"]) } + if e.lyrics != nil { removeKeys.formUnion(["UNSYNCEDLYRICS"]) } + if let d = old, d.count >= 8 { + var i = 0 + let vl = rdle32(d, 0); i = 4 + if vl >= 0 && 4 + vl <= d.count { vendor = String(data: d.subdata(in: (d.startIndex + 4)..<(d.startIndex + 4 + vl)), encoding: .utf8) ?? fallback } + i += vl + let n = rdle32(d, i); i += 4 + for _ in 0..= 0, i + l <= d.count else { break } + let s = String(data: d.subdata(in: (d.startIndex + i)..<(d.startIndex + i + l)), encoding: .utf8) ?? "" + i += l + guard let eq = s.firstIndex(of: "=") else { continue } + let k = String(s[.. Data { + let mime = Data(imageMime(img).utf8) + return be32(3) + be32(mime.count) + mime + be32(0) + be32(0) + be32(0) + be32(0) + be32(0) + be32(img.count) + img + } + + static func flac(_ d: Data, _ e: TagEdit) throws -> Data { + let start = id3Length(d) + guard d.count >= start + 4, d.subdata(in: (d.startIndex + start)..<(d.startIndex + start + 4)) == Data("fLaC".utf8) else { + throw Failure.corrupt("Not a FLAC file") + } + var off = start + 4 + var blocks: [(UInt8, Data)] = [] + var padding = 0 + var oldComment: Data? + while true { + guard off + 4 <= d.count else { throw Failure.corrupt("Broken FLAC metadata") } + let h = d[d.startIndex + off] + let len = Int(d[d.startIndex + off + 1]) << 16 | Int(d[d.startIndex + off + 2]) << 8 | Int(d[d.startIndex + off + 3]) + let type = h & 0x7F + let body = d.subdata(in: (d.startIndex + off + 4)..<(d.startIndex + min(d.count, off + 4 + len))) + switch type { + case 1: padding += 4 + len + case 4: oldComment = body + case 6 where e.cover != nil: break + default: blocks.append((type, body)) + } + off += 4 + len + if h & 0x80 != 0 { break } + } + let oldMetaLen = off - start - 4 + blocks.append((4, vorbisBlock(oldComment, e, vendor: "reference libFLAC 1.4.3"))) + if let c = e.cover, let img = c { blocks.append((6, flacPicture(img))) } + var meta = Data() + for (t, b) in blocks { meta += Data([t, UInt8(b.count >> 16 & 0xFF), UInt8(b.count >> 8 & 0xFF), UInt8(b.count & 0xFF)]) + b } + // Keep the audio in place when the new metadata fits into the old metadata + padding. + var pad = oldMetaLen - meta.count - 4 + if pad < 0 || pad > 1 << 20 { pad = 4096 } + meta += Data([0x81, UInt8(pad >> 16 & 0xFF), UInt8(pad >> 8 & 0xFF), UInt8(pad & 0xFF)]) + Data(count: pad) + _ = padding + return Data("fLaC".utf8) + meta + d.dropFirst(off) + } + + // MARK: MP4 (iTunes ilst) + + struct Atom { let type: String; let start: Int; let size: Int; let header: Int } + + static func atoms(_ d: Data, _ from: Int, _ to: Int) -> [Atom] { + var out: [Atom] = [] + var off = from + while off + 8 <= to { + var size = rd32(d, off) + let type = String(data: d.subdata(in: (d.startIndex + off + 4)..<(d.startIndex + off + 8)), encoding: .isoLatin1) ?? "" + var hdr = 8 + if size == 1 { size = rd32(d, off + 8) << 32 | rd32(d, off + 12); hdr = 16 } + if size == 0 { size = to - off } + guard size >= hdr, off + size <= to else { break } + out.append(Atom(type: type, start: off, size: size, header: hdr)) + off += size + } + return out + } + + /// Atom types are 4 Latin-1 bytes ("©nam" is A9 6E 61 6D). + static func box(_ type: String, _ payload: Data) -> Data { be32(payload.count + 8) + latin1(type) + payload } + + static func dataAtom(_ type: UInt32, _ v: Data) -> Data { box("data", be32(Int(type)) + be32(0) + v) } + + static func ilstItems(_ e: TagEdit) -> [String: Data?] { + var f: [String: Data?] = [:] + func str(_ key: String, _ v: String?) { if let v { f[key] = v.isEmpty ? .some(nil) : box(key, dataAtom(1, Data(v.utf8))) } } + str("\u{A9}nam", e.title); str("\u{A9}ART", e.artist); str("\u{A9}alb", e.album); str("aART", e.albumArtist) + str("\u{A9}gen", e.genre); str("\u{A9}day", e.year); str("\u{A9}lyr", e.lyrics) + func pair(_ key: String, _ v: String?) { + guard let v else { return } + let parts = v.split(separator: "/").map { Int($0.trimmingCharacters(in: .whitespaces)) ?? 0 } + let n = parts.first ?? 0, t = parts.count > 1 ? parts[1] : 0 + f[key] = n == 0 ? .some(nil) : box(key, dataAtom(0, Data([0, 0, UInt8(n >> 8), UInt8(n & 0xFF), UInt8(t >> 8), UInt8(t & 0xFF), 0, 0]))) + } + pair("trkn", e.track); pair("disk", e.disc) + if let c = e.cover { + if let c { f["covr"] = box("covr", dataAtom(imageMime(c) == "image/png" ? 14 : 13, c)) } else { f["covr"] = .some(nil) } + } + if e.genre != nil { f["gnre"] = .some(nil) } + return f + } + + static func latin1(_ s: String) -> Data { Data(s.unicodeScalars.map { UInt8(truncatingIfNeeded: $0.value) }) } + + static func mp4(_ d: Data, _ e: TagEdit) throws -> Data { + let top = atoms(d, 0, d.count) + guard let moov = top.first(where: { $0.type == "moov" }) else { throw Failure.corrupt("No moov atom") } + let mdat = top.first { $0.type == "mdat" } + // Locate udta/meta/ilst inside moov. + let moovKids = atoms(d, moov.start + moov.header, moov.start + moov.size) + let udta = moovKids.first { $0.type == "udta" } + let meta = udta.flatMap { u in atoms(d, u.start + u.header, u.start + u.size).first { $0.type == "meta" } } + let ilst = meta.flatMap { m in atoms(d, m.start + m.header + 4, m.start + m.size).first { $0.type == "ilst" } } + // New ilst: old items minus edited ones, plus new values. + let items = ilstItems(e) + var newIlst = Data() + if let ilst { + for a in atoms(d, ilst.start + ilst.header, ilst.start + ilst.size) { + let key = String(data: latin1(a.type), encoding: .isoLatin1) ?? a.type + if items.keys.contains(key) { continue } + newIlst += d.subdata(in: (d.startIndex + a.start)..<(d.startIndex + a.start + a.size)) + } + } + for (k, v) in items.sorted(by: { $0.key < $1.key }) { if let v { newIlst += v } } + let ilstBox = be32(newIlst.count + 8) + Data("ilst".utf8) + newIlst + let hdlr = box("hdlr", Data(count: 8) + Data("mdirappl".utf8) + Data(count: 9)) + var metaPayload = Data([0, 0, 0, 0]) + if let meta { + for a in atoms(d, meta.start + meta.header + 4, meta.start + meta.size) where a.type != "ilst" && a.type != "free" { + metaPayload += d.subdata(in: (d.startIndex + a.start)..<(d.startIndex + a.start + a.size)) + } + if !atoms(d, meta.start + meta.header + 4, meta.start + meta.size).contains(where: { $0.type == "hdlr" }) { metaPayload += hdlr } + } else { + metaPayload += hdlr + } + metaPayload += ilstBox + let metaBox = box("meta", metaPayload) + var udtaPayload = Data() + if let udta { + for a in atoms(d, udta.start + udta.header, udta.start + udta.size) where a.type != "meta" { + udtaPayload += d.subdata(in: (d.startIndex + a.start)..<(d.startIndex + a.start + a.size)) + } + } + udtaPayload += metaBox + let udtaBox = box("udta", udtaPayload) + var moovPayload = Data() + for a in moovKids where a.type != "udta" { + moovPayload += d.subdata(in: (d.startIndex + a.start)..<(d.startIndex + a.start + a.size)) + } + moovPayload += udtaBox + var newMoov = box("moov", moovPayload) + // If moov sits before mdat, every chunk offset moves by the size difference. + if let mdat, moov.start < mdat.start { + var delta = newMoov.count - moov.size + // Absorb the change with a following free atom when possible. + let after = top.first { $0.start == moov.start + moov.size } + if let free = after, free.type == "free", free.size - delta >= 8 || delta == free.size { + let remain = free.size - delta + var out = d.prefix(moov.start) + newMoov + if remain >= 8 { out += box("free", Data(count: remain - 8)) } + out += d.dropFirst(free.start + free.size) + return out + } + newMoov = patchOffsets(newMoov, delta: delta) + delta = newMoov.count - moov.size + return d.prefix(moov.start) + newMoov + d.dropFirst(moov.start + moov.size) + } + // moov after mdat: replace in place (offsets point before it). + return d.prefix(moov.start) + newMoov + d.dropFirst(moov.start + moov.size) + } + + /// Adds `delta` to every stco/co64 entry inside a moov box. + static func patchOffsets(_ moov: Data, delta: Int) -> Data { + var m = moov + func walk(_ from: Int, _ to: Int) { + for a in atoms(m, from, to) { + switch a.type { + case "trak", "mdia", "minf", "stbl", "edts": + walk(a.start + a.header, a.start + a.size) + case "stco": + let n = rd32(m, a.start + a.header + 4) + for k in 0..> 32) + be32(v & 0xFFFFFFFF)) + } + default: break + } + } + } + walk(8, m.count) + return m + } + + // MARK: Ogg (Vorbis, Opus, FLAC-in-Ogg): rebuild the header packets and renumber pages + + static let crcTable: [UInt32] = (0..<256).map { i -> UInt32 in + var r = UInt32(i) << 24 + for _ in 0..<8 { r = r & 0x8000_0000 != 0 ? (r << 1) ^ 0x04C1_1DB7 : r << 1 } + return r + } + + static func crc(_ d: Data) -> UInt32 { + var c: UInt32 = 0 + for b in d { c = (c << 8) ^ crcTable[Int((c >> 24) ^ UInt32(b))] } + return c + } + + struct Page { var header: Data; var segs: [UInt8]; var body: Data } + + static func pages(_ d: Data) -> [(Page, Int)] { + var out: [(Page, Int)] = [] + var off = 0 + while off + 27 <= d.count { + guard d.subdata(in: (d.startIndex + off)..<(d.startIndex + off + 4)) == Data("OggS".utf8) else { break } + let n = Int(d[d.startIndex + off + 26]) + guard off + 27 + n <= d.count else { break } + let segs = Array(d[(d.startIndex + off + 27)..<(d.startIndex + off + 27 + n)]) + let len = segs.reduce(0) { $0 + Int($1) } + guard off + 27 + n + len <= d.count else { break } + let header = d.subdata(in: (d.startIndex + off)..<(d.startIndex + off + 27)) + let body = d.subdata(in: (d.startIndex + off + 27 + n)..<(d.startIndex + off + 27 + n + len)) + out.append((Page(header: header, segs: segs, body: body), off)) + off += 27 + n + len + } + return out + } + + static func ogg(_ d: Data, _ e: TagEdit) throws -> Data { + let all = pages(d) + guard let first = all.first else { throw Failure.corrupt("Not an Ogg file") } + let serial = TagReader.le32(first.0.header, 14) + // Collect header packets: Vorbis has 3 (ident, comment, setup), Opus 2, FLAC-in-Ogg 1 + metadata. + var packets: [Data] = [] + var cur = Data() + var used = 0 + var nHeaders = 3 + outer: for (pi, (p, _)) in all.enumerated() { + guard TagReader.le32(p.header, 14) == serial else { continue } + var pos = 0 + for s in p.segs { + cur += p.body.subdata(in: pos..<(pos + Int(s))) + pos += Int(s) + if s < 255 { + packets.append(cur) + cur = Data() + if packets.count == 1 { + if packets[0].starts(with: Array("OpusHead".utf8)) { nHeaders = 2 } + else if packets[0].starts(with: [0x7F] + Array("FLAC".utf8)) { nHeaders = 2 } + } + if packets.count == nHeaders { + guard pos == p.body.count else { throw Failure.corrupt("Audio shares a page with the tags") } + used = pi + 1 + break outer + } + } + } + } + guard packets.count == nHeaders else { throw Failure.corrupt("Couldn't read the Ogg headers") } + let ident = packets[0] + var comment = packets[1] + var picture: String? + if let c = e.cover, let img = c { picture = flacPicture(img).base64EncodedString() } + var edit = e + if ident.starts(with: Array("OpusHead".utf8)) { + var block = vorbisBlock(comment.dropFirst(8), edit) + if let picture { block = appendField(block, "METADATA_BLOCK_PICTURE", picture) } + comment = Data("OpusTags".utf8) + block + } else if ident.starts(with: [0x01] + Array("vorbis".utf8)) { + var block = vorbisBlock(comment.dropFirst(7).dropLast(1), edit) + if let picture { block = appendField(block, "METADATA_BLOCK_PICTURE", picture) } + comment = Data([0x03]) + Data("vorbis".utf8) + block + Data([1]) + } else if ident.starts(with: [0x7F] + Array("FLAC".utf8)) { + edit.cover = edit.cover.map { _ in nil } + var block = vorbisBlock(comment.dropFirst(4), edit) + if let picture { block = appendField(block, "METADATA_BLOCK_PICTURE", picture) } + let flags = comment.first ?? 0x84 + comment = Data([flags]) + Data([UInt8(block.count >> 16 & 0xFF), UInt8(block.count >> 8 & 0xFF), UInt8(block.count & 0xFF)]) + block + } else { + throw Failure.unsupported("ogg") + } + packets[1] = comment + // Paginate: ident alone on the first (BOS) page, the other headers on the following pages. + var out = Data() + var seq: UInt32 = 0 + func emit(_ group: [Data], bos: Bool) { + // Lacing values for the whole group; a packet that is a multiple of 255 ends with a 0. + var lacing: [(UInt8, Int, Bool)] = [] // (segment length, packet index, ends packet) + for (pi, p) in group.enumerated() { + var left = p.count + while left >= 255 { lacing.append((255, pi, false)); left -= 255 } + lacing.append((UInt8(left), pi, true)) + } + var offsets = group.map { _ in 0 } + var i = 0 + var continued = false + var first = true + while i < lacing.count { + let chunk = lacing[i.. Data { + var b = block + let vl = rdle32(b, 0) + let countAt = 4 + vl + let n = rdle32(b, countAt) + b.replaceSubrange(countAt..<(countAt + 4), with: le32(n + 1)) + let s = Data("\(k)=\(v)".utf8) + return b + le32(s.count) + s + } +} diff --git a/App/MulberryApp.swift b/App/MulberryApp.swift new file mode 100644 index 0000000..29d8942 --- /dev/null +++ b/App/MulberryApp.swift @@ -0,0 +1,77 @@ +import SwiftUI +import AVFoundation + +@main +struct MulberryApp: App { + @Environment(\.scenePhase) var phase + + init() { + _ = Player.shared + Library.shared.startWatching() + Library.shared.scan() + IntentRouter.handler = { cmd in + let p = Player.shared + switch cmd { + case .toggle: p.toggle() + case .next: p.next() + case .previous: p.prev() + case .shuffle: p.setShuffle(!Prefs.shared.shuffle) + case .repeatMode: p.cycleRepeat() + case .favourite: if let s = p.current { PlayStats.shared.setFav(s, !PlayStats.shared.fav(s)) } + } + } + Theme.shared.update() + Player.shared.publishWidget() + } + + var body: some Scene { + WindowGroup { + RootView() + .environmentObjects() + .onOpenURL { url in + // mulberry://nowplaying from the widget, files opened "in place" from other apps. + if url.scheme == "mulberry" { + if url.host == "nowplaying" { UIState.shared.nowPlaying = Player.shared.current != nil } + } else if url.isFileURL { + openFile(url) + } + } + } + .onChange(of: phase) { p in + switch p { + case .background: + Player.shared.persistNow() + Player.shared.publishWidget() + case .active: + Library.shared.rescanSoon() + Scrobbler.shared.flush() + default: break + } + } + } + + /// Files shared to Mulberry: copy audio into Music and play it; import playlists. + private func openFile(_ url: URL) { + let ok = url.startAccessingSecurityScopedResource() + defer { if ok { url.stopAccessingSecurityScopedResource() } } + let ext = url.pathExtension.lowercased() + if Library.playlistExts.contains(ext) { + if let (pl, n, total) = try? Playlists.shared.importFile(url) { + UIState.shared.show("\(pl.name): \(n)/\(total) songs found") + UIState.shared.tab = 1 + } + return + } + guard Library.audioExts.contains(ext) else { return } + var target = url + if !url.path.hasPrefix(Library.root.path) { + target = Library.root.appendingPathComponent("Music").appendingPathComponent(url.lastPathComponent) + try? FileManager.default.removeItem(at: target) + try? FileManager.default.copyItem(at: url, to: target) + } + var s = Song(path: Library.relPath(target)) + Library.fill(&s, target) + Player.shared.playList([s]) + Library.shared.scan() + } +} diff --git a/App/Services/Covers.swift b/App/Services/Covers.swift new file mode 100644 index 0000000..8aebb66 --- /dev/null +++ b/App/Services/Covers.swift @@ -0,0 +1,205 @@ +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 + } +} diff --git a/App/Services/Lyrics.swift b/App/Services/Lyrics.swift new file mode 100644 index 0000000..261b8f4 --- /dev/null +++ b/App/Services/Lyrics.swift @@ -0,0 +1,240 @@ +import Foundation + +/// Synced/plain lyrics from LRCLIB, NetEase, .lrc files and embedded tags (Android Lyrics.java). +enum Lyrics { + struct Line: Hashable { + let t: Double // seconds, -1 when unsynced + let text: String + } + + struct Result { + var lines: [Line] = [] + var synced = false + var source = "" + var message = "" + var raw = "" + } + + private static let ts = try! NSRegularExpression(pattern: #"\[(\d+):(\d+(?:[.:]\d+)?)\]"#) + private static let credit = try! NSRegularExpression( + pattern: #"^\s*\[[^\]]*\]\s*(作词|作曲|编曲|制作人|监制|混音|母带|词|曲|Lyricist|Lyrics by|Composer|Composed by|Arranger|Producer|Written by)\s*[::].*"#, + options: .caseInsensitive) + private static let neHeaders = [ + "Referer": "https://music.163.com/", + "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148", + ] + + static func isSynced(_ s: String) -> Bool { + ts.firstMatch(in: s, range: NSRange(s.startIndex..., in: s)) != nil + } + + static func parse(_ text: String, plain: Bool) -> Result { + var r = Result() + r.raw = text + var offset = 0.0 + if let m = try? NSRegularExpression(pattern: #"\[offset:\s*([-+]?\d+)\]"#, options: .caseInsensitive) + .firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), + let g = Range(m.range(at: 1), in: text) { + offset = (Double(text[g]) ?? 0) / 1000 + } + var lines: [Line] = [] + var synced = false + let word = try! NSRegularExpression(pattern: #"<\d+:\d+(?:\.\d+)?>"#) + let tag = try! NSRegularExpression(pattern: #"^\[[a-zA-Z]+:.*\]$"#) + for raw in text.components(separatedBy: .newlines) { + let ns = NSRange(raw.startIndex..., in: raw) + var times: [Double] = [] + for m in ts.matches(in: raw, range: ns) { + guard let a = Range(m.range(at: 1), in: raw), let b = Range(m.range(at: 2), in: raw) else { continue } + let sec = Double(raw[b].replacingOccurrences(of: ":", with: ".")) ?? 0 + times.append((Double(raw[a]) ?? 0) * 60 + sec - offset) + } + var clean = ts.stringByReplacingMatches(in: raw, range: ns, withTemplate: "") + clean = word.stringByReplacingMatches(in: clean, range: NSRange(clean.startIndex..., in: clean), withTemplate: "") + clean = clean.trimmingCharacters(in: .whitespaces) + if !times.isEmpty { + synced = true + for t in times { lines.append(Line(t: max(0, t), text: clean)) } + } else { + let tr = raw.trimmingCharacters(in: .whitespaces) + if tag.firstMatch(in: tr, range: NSRange(tr.startIndex..., in: tr)) == nil { + lines.append(Line(t: -1, text: tr)) + } + } + } + if synced { lines = lines.filter { $0.t >= 0 }.sorted { $0.t < $1.t } } + if plain && synced { + lines = lines.map { Line(t: -1, text: $0.text) } + synced = false + } + while let f = lines.first, f.text.isEmpty, !synced { lines.removeFirst() } + r.lines = lines + r.synced = synced + return r + } + + static func lineAt(_ lines: [Line], _ t: Double) -> Int { + var lo = 0, hi = lines.count - 1, ans = -1 + while lo <= hi { + let mid = (lo + hi) / 2 + if lines[mid].t <= t + 0.15 { ans = mid; lo = mid + 1 } else { hi = mid - 1 } + } + return ans + } + + static func clean(_ s: String) -> String { + s.replacingOccurrences(of: #"\s*[\(\[](feat|ft|with|remaster|live|explicit|bonus)[^\)\]]*[\)\]]"#, + with: "", options: [.regularExpression, .caseInsensitive]) + .trimmingCharacters(in: .whitespaces) + } + + static func norm(_ s: String) -> String { + Library.norm(s).components(separatedBy: CharacterSet.alphanumerics.inverted).joined() + } + + // MARK: Providers + + static func lrclib(_ s: Song) throws -> String { + var q: [(String, String)] = [("artist_name", s.displayArtist), ("track_name", clean(s.displayTitle))] + var full = q + if !s.album.isEmpty { full.append(("album_name", s.album)) } + if s.duration > 0 { full.append(("duration", String(Int(s.duration.rounded())))) } + if let o = try? Net.json("https://lrclib.net/api/get?" + Net.query(full)) as? [String: Any], !o.isEmpty { + if (o["instrumental"] as? Bool) == true { return "[instrumental]" } + var l = o.str("syncedLyrics") + if l.isEmpty { l = o.str("plainLyrics") } + if !l.isEmpty { return l } + } + q = [("artist_name", s.displayArtist), ("track_name", clean(s.displayTitle))] + guard let arr = try Net.json("https://lrclib.net/api/search?" + Net.query(q)) as? [[String: Any]] else { return "" } + var fallback: [String: Any]? + for o in arr { + let d = o.num("duration") + guard s.duration <= 0 || d <= 0 || abs(d - s.duration) <= 6 else { continue } + if !o.str("syncedLyrics").isEmpty { return o.str("syncedLyrics") } + if fallback == nil { fallback = o } + } + return fallback?.str("plainLyrics") ?? "" + } + + static func netease(_ s: String, artist: String, duration: Double) throws -> String { + let term = (clean(s) + " " + artist).trimmingCharacters(in: .whitespaces) + guard let res = (try Net.json("https://music.163.com/api/cloudsearch/pc?type=1&offset=0&limit=10&s=" + Net.enc(term), + headers: neHeaders) as? [String: Any])?.obj("result") else { return "" } + var best: [String: Any]? + var bestScore = -1e9 + for o in res.arr("songs") { + var score = 0.0 + let ar = norm(o.arr("ar").map { $0.str("name") }.joined(separator: " ")) + let want = norm(artist) + if !want.isEmpty && (ar.contains(want) || want.contains(ar)) { score += 50 } + if norm(clean(s)) == norm(clean(o.str("name"))) { score += 30 } + let dt = o.num("dt") / 1000 + if duration > 0 && dt > 0 { score -= min(40, abs(dt - duration) * 4) } + if score > bestScore { bestScore = score; best = o } + } + guard let b = best, bestScore >= 0 else { return "" } + let id = Int(b.num("id")) + let lj = try Net.json("https://music.163.com/api/song/lyric?lv=1&kv=1&tv=-1&id=\(id)", headers: neHeaders) as? [String: Any] + let lrc = lj?.obj("lrc")?.str("lyric") ?? "" + return lrc.components(separatedBy: "\n").filter { line in + credit.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)) == nil + }.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func local(_ s: Song) -> String { + guard !s.isStream else { return "" } + let base = s.url.deletingPathExtension() + let candidates = [base.appendingPathExtension("lrc"), base.appendingPathExtension("LRC"), + base.appendingPathExtension("txt"), + Library.root.appendingPathComponent("Lyrics").appendingPathComponent(base.lastPathComponent + ".lrc"), + Library.root.appendingPathComponent("Lyrics") + .appendingPathComponent("\(s.displayArtist) - \(s.displayTitle).lrc")] + for c in candidates { + if let d = try? Data(contentsOf: c) { + return String(data: d, encoding: .utf8) ?? String(data: d, encoding: .isoLatin1) ?? "" + } + } + return TagReader.read(s.url).lyrics + } + + // MARK: Cache + + static func cacheFile(_ s: Song, _ src: String) -> URL { + let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("lyrics") + try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let key = "\(src)|\(s.displayArtist)|\(s.displayTitle)|\(s.album)".data(using: .utf8)!.base64EncodedString() + .replacingOccurrences(of: "/", with: "_").prefix(120) + return dir.appendingPathComponent(String(key) + ".txt") + } + + static func readCache(_ s: Song, _ src: String) -> String? { try? String(contentsOf: cacheFile(s, src), encoding: .utf8) } + static func writeCache(_ s: Song, _ src: String, _ text: String) { try? text.write(to: cacheFile(s, src), atomically: true, encoding: .utf8) } + + static func clearCache(_ s: Song) { + for src in ["auto", "lrclib", "netease"] { try? FileManager.default.removeItem(at: cacheFile(s, src)) } + } + + static func clearAllCache() { + let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("lyrics") + try? FileManager.default.removeItem(at: dir) + } + + // MARK: Loading (Auto — synced first, local last) + + static func load(_ s: Song, forceOnline: Bool = false) -> Result { + let p = Prefs.shared + let source = p.lyricsSource + let plain = p.lyricsPlain + let online = p.onlineLyrics || forceOnline + if source == "off" { return Result(message: "Lyrics are turned off in Settings.") } + var text = "" + var label = "" + var message = "" + switch source { + case "local": + text = local(s); label = "Local .lrc" + if text.isEmpty { message = "No .lrc file or embedded lyrics for this song." } + case "lrclib", "netease": + label = source == "lrclib" ? "LRCLIB" : "NetEase" + if let c = forceOnline ? nil : readCache(s, source) { + text = c + } else if online { + do { + text = source == "lrclib" ? try lrclib(s) : try netease(s.displayTitle, artist: s.displayArtist, duration: s.duration) + writeCache(s, source, text) + } catch { message = "Couldn't reach the lyrics service" } + } + if text.isEmpty && message.isEmpty { message = "\(label) has no lyrics for this song." } + default: + if let c = forceOnline ? nil : readCache(s, "auto") { + if let nl = c.firstIndex(of: "\n") { + label = String(c[.. String { + s.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? s + } + + static func query(_ params: [(String, String)]) -> String { + params.map { "\(enc($0.0))=\(enc($0.1))" }.joined(separator: "&") + } + + static func data(_ url: String, headers: [String: String] = [:], method: String = "GET", body: Data? = nil, + contentType: String? = nil) throws -> Data { + guard let u = URL(string: url) else { throw URLError(.badURL) } + var req = URLRequest(url: u) + req.httpMethod = method + req.httpBody = body + if let contentType { req.setValue(contentType, forHTTPHeaderField: "Content-Type") } + for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) } + let sem = DispatchSemaphore(value: 0) + var out: Result = .failure(URLError(.unknown)) + session.dataTask(with: req) { d, r, e in + if let e { out = .failure(e) } + else if let h = r as? HTTPURLResponse, h.statusCode >= 400, h.statusCode != 404 { + out = .failure(URLError(.badServerResponse)) + } else { out = .success(d ?? Data()) } + sem.signal() + }.resume() + sem.wait() + return try out.get() + } + + static func get(_ url: String, headers: [String: String] = [:]) throws -> String { + String(data: try data(url, headers: headers), encoding: .utf8) ?? "" + } + + static func json(_ url: String, headers: [String: String] = [:]) throws -> Any { + try JSONSerialization.jsonObject(with: try data(url, headers: headers)) + } + + static func postForm(_ url: String, _ form: [(String, String)]) throws -> Any { + let d = try data(url, method: "POST", body: Data(query(form).utf8), + contentType: "application/x-www-form-urlencoded; charset=utf-8") + return try JSONSerialization.jsonObject(with: d) + } + + static func postJSON(_ url: String, _ body: Any, headers: [String: String] = [:]) throws -> Data { + try data(url, headers: headers, method: "POST", body: try JSONSerialization.data(withJSONObject: body), + contentType: "application/json") + } +} + +extension Dictionary where Key == String, Value == Any { + func str(_ k: String) -> String { + if let s = self[k] as? String, s != "" { return s } + if let n = self[k] as? NSNumber { return n.stringValue } + return "" + } + func num(_ k: String) -> Double { (self[k] as? NSNumber)?.doubleValue ?? Double(str(k)) ?? 0 } + func obj(_ k: String) -> [String: Any]? { self[k] as? [String: Any] } + func arr(_ k: String) -> [[String: Any]] { self[k] as? [[String: Any]] ?? [] } +} diff --git a/App/Services/Scrobbler.swift b/App/Services/Scrobbler.swift new file mode 100644 index 0000000..2aa5068 --- /dev/null +++ b/App/Services/Scrobbler.swift @@ -0,0 +1,215 @@ +import Foundation +import CryptoKit +import AuthenticationServices +import UIKit + +/// Last.fm and ListenBrainz scrobbling with an offline cache (desktop scrobble.rs). +@MainActor +final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentationContextProviding { + static let shared = Scrobbler() + + static let api = "https://ws.audioscrobbler.com/2.0/" + static let key = Covers.lastfmKey + static let secret = "df1f1a14348a083d9aef80820b274931" + + struct Entry: Codable, Equatable { + var svc: String + var artist: String + var title: String + var album: String + var albumArtist: String + var duration: Double + var track: Int + var ts: Int + } + + @Published private(set) var pending: [Entry] = [] + @Published var toast: String? + private var announced: (String, Date)? + private var lastFlush = Date() + private var file: URL { Library.support.appendingPathComponent("scrobble_cache.json") } + private var authSession: ASWebAuthenticationSession? + + private override init() { + super.init() + if let d = try? Data(contentsOf: file), let p = try? JSONDecoder().decode([Entry].self, from: d) { pending = p } + } + + private var prefs: Prefs { Prefs.shared } + var lfmOn: Bool { prefs.lfmEnabled && !prefs.lfmSession.isEmpty } + var lbOn: Bool { !prefs.lbToken.isEmpty } + + nonisolated static func sign(_ params: [(String, String)]) -> [(String, String)] { + let sorted = params.filter { $0.0 != "format" && $0.0 != "callback" }.sorted { $0.0 < $1.0 } + let s = sorted.map { $0.0 + $0.1 }.joined() + secret + let sig = Insecure.MD5.hash(data: Data(s.utf8)).map { String(format: "%02x", $0) }.joined() + return params + [("api_sig", sig)] + } + + nonisolated static func call(_ method: String, _ params: [(String, String)], post: Bool, session: String?) throws -> [String: Any] { + var p: [(String, String)] = [("method", method), ("api_key", key)] + params.filter { !$0.1.isEmpty } + if let session { p.append(("sk", session)) } + p = sign(p) + [("format", "json")] + let res: Any = post ? try Net.postForm(api, p) : try Net.json(api + "?" + Net.query(p)) + guard let o = res as? [String: Any] else { throw URLError(.cannotParseResponse) } + if o["error"] != nil { throw NSError(domain: "Last.fm", code: 1, userInfo: [NSLocalizedDescriptionKey: "Last.fm: " + o.str("message")]) } + return o + } + + nonisolated static func trackParams(_ e: Entry, _ i: Int?) -> [(String, String)] { + let sfx = i.map { "[\($0)]" } ?? "" + var p = [("artist" + sfx, e.artist), ("track" + sfx, e.title), ("album" + sfx, e.album)] + if !e.albumArtist.isEmpty && e.albumArtist != e.artist { p.append(("albumArtist" + sfx, e.albumArtist)) } + if e.duration > 0 { p.append(("duration" + sfx, String(Int(e.duration)))) } + if e.track > 0 { p.append(("trackNumber" + sfx, String(e.track))) } + return p + } + + private func entry(_ s: Song, svc: String, ts: Int) -> Entry { + Entry(svc: svc, artist: s.displayArtist, title: s.displayTitle, album: s.album, albumArtist: s.albumArtist, + duration: s.duration, track: s.track, ts: ts) + } + + // MARK: Login (Last.fm web auth with a mulberry:// callback) + + func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first ?? ASPresentationAnchor() + } + + func login() { + let cb = "mulberry://lastfm" + guard let url = URL(string: "https://www.last.fm/api/auth/?api_key=\(Scrobbler.key)&cb=\(Net.enc(cb))") else { return } + let s = ASWebAuthenticationSession(url: url, callbackURLScheme: "mulberry") { [weak self] u, err in + guard let u, let token = URLComponents(url: u, resolvingAgainstBaseURL: false)? + .queryItems?.first(where: { $0.name == "token" })?.value else { + if err != nil { Task { @MainActor in self?.toast = "Last.fm sign-in cancelled" } } + return + } + Task.detached { + do { + let r = try Scrobbler.call("auth.getSession", [("token", token)], post: false, session: nil) + let sk = r.obj("session")?.str("key") ?? "", name = r.obj("session")?.str("name") ?? "" + await MainActor.run { + Prefs.shared.lfmSession = sk + Prefs.shared.lfmUser = name + Prefs.shared.lfmEnabled = true + Scrobbler.shared.toast = "Signed in to Last.fm as \(name)" + } + } catch { + await MainActor.run { Scrobbler.shared.toast = error.localizedDescription } + } + } + } + s.presentationContextProvider = self + s.prefersEphemeralWebBrowserSession = false + authSession = s + s.start() + } + + func logout() { + prefs.lfmSession = "" + prefs.lfmUser = "" + prefs.lfmEnabled = false + } + + // MARK: Events from the player + + func nowPlaying(_ s: Song) { + if let (k, t) = announced, k == s.id, Date().timeIntervalSince(t) < 240 { return } + announced = (s.id, Date()) + let e = entry(s, svc: "", ts: 0) + let sk = prefs.lfmSession, lfm = lfmOn, lb = lbOn, token = prefs.lbToken + Task.detached { + if lfm { _ = try? Scrobbler.call("track.updateNowPlaying", Scrobbler.trackParams(e, nil), post: true, session: sk) } + if lb { _ = try? Scrobbler.lbSubmit("playing_now", [Scrobbler.lbPayload(e, ts: nil)], token: token) } + } + } + + func progress(_ s: Song, listened: Double, duration: Double) { + if Date().timeIntervalSince(lastFlush) > 300 { lastFlush = Date(); flush() } + } + + func finished(_ s: Song, listened: Double, started: Date) { + let dur = s.duration + let ok = s.isStream ? listened >= 30 : dur >= 30 && listened >= min(dur / 2, 240) + guard ok, !s.displayArtist.isEmpty, !s.displayTitle.isEmpty else { return } + let ts = Int(started.timeIntervalSince1970) + if lfmOn { pending.append(entry(s, svc: "lastfm", ts: ts)) } + if lbOn { pending.append(entry(s, svc: "listenbrainz", ts: ts)) } + save() + flush() + } + + func love(_ s: Song, _ on: Bool) { + guard lfmOn else { return } + let sk = prefs.lfmSession + let a = s.displayArtist, t = s.displayTitle + Task.detached { + do { + _ = try Scrobbler.call(on ? "track.love" : "track.unlove", [("artist", a), ("track", t)], post: true, session: sk) + await MainActor.run { Scrobbler.shared.toast = on ? "Loved on Last.fm" : "Unloved on Last.fm" } + } catch { + await MainActor.run { Scrobbler.shared.toast = error.localizedDescription } + } + } + } + + private func save() { + if let d = try? JSONEncoder().encode(pending) { try? d.write(to: file, options: .atomic) } + } + + private var flushing = false + + func flush() { + guard !pending.isEmpty, !flushing else { return } + flushing = true + let lfm = Array(pending.filter { $0.svc == "lastfm" }.prefix(50)) + let lb = Array(pending.filter { $0.svc == "listenbrainz" }.prefix(100)) + let sk = prefs.lfmSession, token = prefs.lbToken, lfmOn = lfmOn, lbOn = lbOn + Task.detached { + var done: [Entry] = [] + var err: String? + if !lfm.isEmpty && lfmOn { + var params: [(String, String)] = [] + for (i, e) in lfm.enumerated() { + params += Scrobbler.trackParams(e, i) + params.append(("timestamp[\(i)]", String(e.ts))) + } + do { _ = try Scrobbler.call("track.scrobble", params, post: true, session: sk); done += lfm } + catch { err = error.localizedDescription } + } + if !lb.isEmpty && lbOn { + do { + try Scrobbler.lbSubmit(lb.count > 1 ? "import" : "single", lb.map { Scrobbler.lbPayload($0, ts: $0.ts) }, token: token) + done += lb + } catch { err = error.localizedDescription } + } + await MainActor.run { + let sc = Scrobbler.shared + sc.flushing = false + sc.pending.removeAll { done.contains($0) } + sc.save() + if let err { sc.toast = "Scrobbling deferred: \(err)" } + } + } + } + + // MARK: ListenBrainz + + nonisolated static func lbPayload(_ e: Entry, ts: Int?) -> [String: Any] { + var meta: [String: Any] = ["artist_name": e.artist, "track_name": e.title] + if !e.album.isEmpty { meta["release_name"] = e.album } + var info: [String: Any] = ["media_player": "Mulberry", "submission_client": "Mulberry iOS"] + if e.duration > 0 { info["duration_ms"] = Int(e.duration * 1000) } + if e.track > 0 { info["tracknumber"] = e.track } + meta["additional_info"] = info + var p: [String: Any] = ["track_metadata": meta] + if let ts { p["listened_at"] = ts } + return p + } + + nonisolated static func lbSubmit(_ type: String, _ payload: [[String: Any]], token: String) throws { + _ = try Net.postJSON("https://api.listenbrainz.org/1/submit-listens", ["listen_type": type, "payload": payload], + headers: ["Authorization": "Token \(token)"]) + } +} diff --git a/App/Services/Theme.swift b/App/Services/Theme.swift new file mode 100644 index 0000000..dda5e6a --- /dev/null +++ b/App/Services/Theme.swift @@ -0,0 +1,31 @@ +import SwiftUI + +/// Current palette: from album art, a custom colour or the default seed, in light/dark (Android Palette.build). +@MainActor +final class Theme: ObservableObject { + static let shared = Theme() + @Published private(set) var palette = Palette.fromSeed(Palette.defaultSeed, dark: true) + var systemDark = true { didSet { if oldValue != systemDark { update() } } } + + var dark: Bool { + switch Prefs.shared.themeMode { + case "dark": return true + case "light": return false + default: return systemDark + } + } + + func update() { + let p = Prefs.shared + let seed: UInt32 + switch p.colorSource { + case "album": seed = Player.shared.seed ?? Palette.defaultSeed + case "custom": seed = UInt32(truncatingIfNeeded: p.customColor) & 0xFFFFFF + default: seed = Palette.defaultSeed + } + let np = Palette.fromSeed(seed, dark: dark) + if np != palette { + withAnimation(.easeInOut(duration: 0.45)) { palette = np } + } + } +} diff --git a/App/Services/WidgetBridge.swift b/App/Services/WidgetBridge.swift new file mode 100644 index 0000000..e0c6db7 --- /dev/null +++ b/App/Services/WidgetBridge.swift @@ -0,0 +1,84 @@ +import UIKit +import WidgetKit + +/// Publishes the now-playing snapshot for the Home/Lock Screen widgets (Android Widgets.updateAll). +@MainActor +enum WidgetBridge { + private static var last = NowSnapshot() + private static var artVersion = 0 + private static var lastArt: UIImage? + private static var lastReload = Date.distantPast + private static var reloadPending = false + + static func publish(song: Song?, playing: Bool, position: Double, duration: Double, art: UIImage?, + palette: Palette, lyrics: Lyrics.Result?, shuffle: Bool, repeatMode: Int) { + var s = NowSnapshot() + if let song { + s.title = song.displayTitle + s.artist = song.displayArtist + s.album = song.album + s.favourite = PlayStats.shared.fav(song) + } + s.playing = playing + s.position = position + s.duration = duration + s.at = Date().timeIntervalSince1970 + s.shuffle = shuffle + s.repeatMode = repeatMode + s.dark = palette.dark + s.widgetFPS = Prefs.shared.widgetAnim + s.palette = [palette.primary, palette.onPrimary, palette.primaryContainer, palette.onPrimaryContainer, + palette.secondaryContainer, palette.onSecondaryContainer, palette.surface, palette.surfaceHigh, + palette.onSurface, palette.onSurfaceVariant] + if let lr = lyrics { + if lr.synced { + s.lyrics = lr.lines.map(\.t) + s.lyricText = lr.lines.map(\.text) + } else { + s.plainLyric = lr.lines.prefix(4).map(\.text).joined(separator: "\n") + } + } + if art !== lastArt { + lastArt = art + artVersion += 1 + if let art, let d = squareThumb(art, 400)?.jpegData(compressionQuality: 0.85) { + try? d.write(to: NowSnapshot.artFile, options: .atomic) + } else { + try? FileManager.default.removeItem(at: NowSnapshot.artFile) + } + } + s.hasArt = art != nil + s.artVersion = artVersion + // Only the position drifting is not worth a reload: the widget extrapolates it. + var cmp = s + cmp.position = last.position; cmp.at = last.at + let drifted = abs(s.position(at: Date()) - last.position(at: Date())) > 2 + guard cmp != last || drifted else { return } + last = s + s.save() + reload() + } + + /// WidgetKit throttles reloads; coalesce bursts (track change + art + lyrics) into one. + private static func reload() { + guard !reloadPending else { return } + let wait = max(0, 0.4 - Date().timeIntervalSince(lastReload)) + reloadPending = true + DispatchQueue.main.asyncAfter(deadline: .now() + wait) { + reloadPending = false + lastReload = Date() + WidgetCenter.shared.reloadAllTimelines() + } + } + + static func squareThumb(_ img: UIImage, _ px: CGFloat) -> UIImage? { + let side = min(img.size.width, img.size.height) + guard side > 0 else { return nil } + let r = UIGraphicsImageRenderer(size: CGSize(width: px, height: px)) + return r.image { _ in + let scale = px / side + let w = img.size.width * scale, h = img.size.height * scale + img.draw(in: CGRect(x: (px - w) / 2, y: (px - h) / 2, width: w, height: h)) + } + } +} diff --git a/App/UI/Components.swift b/App/UI/Components.swift new file mode 100644 index 0000000..30d58d5 --- /dev/null +++ b/App/UI/Components.swift @@ -0,0 +1,235 @@ +import SwiftUI + +/// Rounded cover thumbnail that loads off the main thread (Android Lists.coverView/bindCover). +struct CoverThumb: View { + let song: Song? + var size: CGFloat = 48 + var radius: CGFloat = 8 + var circle = false + @EnvironmentObject var theme: Theme + @State private var img: UIImage? + @State private var loadedFor: String? + + var body: some View { + let shape = RoundedRectangle(cornerRadius: circle ? size / 2 : radius, style: .continuous) + ZStack { + if let img { + Image(uiImage: img).resizable().scaledToFill() + } else { + theme.palette.cSurfaceHighest + Image(systemName: "music.note") + .font(.system(size: size * 0.36, weight: .medium)) + .foregroundColor(theme.palette.cOnSurfaceVar.opacity(0.7)) + } + } + .frame(width: size, height: size) + .clipShape(shape) + .task(id: song?.albumKey ?? song?.path) { await load() } + } + + private func load() async { + guard let s = song else { img = nil; return } + let px = Int(size * UIScreen.main.scale) <= 160 ? 160 : 300 + if let c = Covers.cached(s, px) { img = c; return } + img = nil + let r = await Task.detached(priority: .utility) { Covers.thumb(s, px: px) }.value + if !Task.isCancelled { img = r } + } +} + +struct SongRow: View { + let song: Song + var current = false + var showCover = true + var trailing: String? + var onMenu: (() -> Void)? + @EnvironmentObject var theme: Theme + + var body: some View { + let p = theme.palette + HStack(spacing: 14) { + if showCover { CoverThumb(song: song, size: 48) } + VStack(alignment: .leading, spacing: 2) { + Text(song.displayTitle) + .font(.system(size: 16, weight: current ? .semibold : .regular)) + .foregroundColor(current ? p.cPrimary : p.cOnSurface) + .lineLimit(1) + Text(song.subtitle) + .font(.system(size: 14)) + .foregroundColor(p.cOnSurfaceVar) + .lineLimit(1) + } + Spacer(minLength: 6) + Text(trailing ?? (song.duration > 0 ? TimeFmt.string(song.duration) : "")) + .font(.system(size: 13).monospacedDigit()) + .foregroundColor(p.cOnSurfaceVar) + if let onMenu { + Button(action: onMenu) { + Image(systemName: "ellipsis") + .rotationEffect(.degrees(90)) + .font(.system(size: 17, weight: .semibold)) + .foregroundColor(p.cOnSurfaceVar) + .frame(width: 32, height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .padding(.leading, 16) + .padding(.trailing, onMenu == nil ? 16 : 6) + .padding(.vertical, 6) + .contentShape(Rectangle()) + } +} + +struct GroupRow: View { + let group: Library.Group + var circle = false + var folder = false + @EnvironmentObject var theme: Theme + + var body: some View { + let p = theme.palette + HStack(spacing: 14) { + if folder { + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(p.cSurfaceHighest) + .frame(width: 48, height: 48) + .overlay(Image(systemName: "folder").font(.system(size: 20)).foregroundColor(p.cOnSurfaceVar)) + } else { + CoverThumb(song: group.cover, size: 48, circle: circle) + } + VStack(alignment: .leading, spacing: 2) { + Text(group.title).font(.system(size: 16)).foregroundColor(p.cOnSurface).lineLimit(1) + Text(group.subtitle).font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar).lineLimit(1) + } + Spacer() + } + .padding(.horizontal, 16) + .padding(.vertical, 6) + .contentShape(Rectangle()) + } +} + +/// Filled or tonal pill button (Android Ui.pill). +struct Pill: View { + let icon: String? + let title: String + var filled = false + let action: () -> Void + @EnvironmentObject var theme: Theme + + var body: some View { + let p = theme.palette + Button(action: action) { + HStack(spacing: 8) { + if let icon { Image(systemName: icon).font(.system(size: 15, weight: .semibold)) } + Text(title).font(.system(size: 14, weight: .medium)).lineLimit(1) + } + .padding(.leading, 16) + .padding(.trailing, 20) + .padding(.vertical, 10) + .foregroundColor(filled ? p.cOnPrimary : p.cOnSecondaryC) + .background(Capsule().fill(filled ? p.cPrimary : p.cSecondaryC)) + } + .buttonStyle(PressScale()) + } +} + +/// Filter chip (Songs / Albums / Artists / Folders). +struct Chip: View { + let title: String + let selected: Bool + let action: () -> Void + @EnvironmentObject var theme: Theme + + var body: some View { + let p = theme.palette + Button(action: action) { + Text(title) + .font(.system(size: 15)) + .padding(.horizontal, 18) + .padding(.vertical, 9) + .foregroundColor(selected ? p.cOnSecondaryC : p.cOnSurface) + .background(Capsule().fill(selected ? p.cSecondaryC : Color.clear)) + .overlay(Capsule().stroke(selected ? Color.clear : p.cOutlineVar, lineWidth: 1)) + } + .buttonStyle(PressScale()) + } +} + +struct IconButton: View { + let icon: String + var size: CGFloat = 44 + var tint: Color? + var filled: Color? + let action: () -> Void + @EnvironmentObject var theme: Theme + + var body: some View { + Button(action: action) { + Image(systemName: icon) + .font(.system(size: size * 0.42, weight: .semibold)) + .foregroundColor(tint ?? theme.palette.cOnSurfaceVar) + .frame(width: size, height: size) + .background(Circle().fill(filled ?? .clear)) + .contentShape(Circle()) + } + .buttonStyle(PressScale()) + } +} + +struct PressScale: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .scaleEffect(configuration.isPressed ? 0.94 : 1) + .opacity(configuration.isPressed ? 0.85 : 1) + .animation(.easeOut(duration: 0.12), value: configuration.isPressed) + } +} + +/// Section header like "Smart playlists" / "Appearance". +struct SectionLabel: View { + let text: String + @EnvironmentObject var theme: Theme + var body: some View { + Text(text) + .font(.system(size: 14, weight: .medium)) + .foregroundColor(theme.palette.cPrimary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 20) + .padding(.top, 18) + .padding(.bottom, 8) + } +} + +/// Rounded container card used in Settings. +struct Card: View { + @ViewBuilder let content: Content + @EnvironmentObject var theme: Theme + var body: some View { + VStack(spacing: 0) { content } + .background(RoundedRectangle(cornerRadius: 24, style: .continuous).fill(theme.palette.cSurfaceC)) + .padding(.horizontal, 12) + } +} + +/// Toast banner shown at the bottom. +struct Toast: View { + let text: String + @EnvironmentObject var theme: Theme + var body: some View { + Text(text) + .font(.system(size: 14)) + .foregroundColor(theme.palette.cSurface) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .background(Capsule().fill(theme.palette.cOnSurface)) + .shadow(radius: 6, y: 2) + } +} + +extension View { + /// Applies the palette's surface background. + func surface(_ p: Palette) -> some View { background(p.cSurface.ignoresSafeArea()) } +} diff --git a/App/UI/Editors.swift b/App/UI/Editors.swift new file mode 100644 index 0000000..0bb3963 --- /dev/null +++ b/App/UI/Editors.swift @@ -0,0 +1,349 @@ +import SwiftUI +import PhotosUI + +/// Tag editor for one or many songs (Android TagEditorActivity). Fields that differ across a selection +/// show "Keep" and are left alone unless edited. +struct TagEditorView: View { + let songs: [Song] + @EnvironmentObject var theme: Theme + @EnvironmentObject var ui: UIState + @Environment(\.dismiss) var dismiss + + struct Field: Identifiable { + let id: String + let label: String + var value: String + var mixed: Bool + var touched = false + var multiline = false + } + + @State private var fields: [Field] = [] + @State private var cover: Data?? + @State private var coverPreview: UIImage? + @State private var photo: PhotosPickerItem? + @State private var saving = false + @State private var lookup = false + @State private var error: String? + + var body: some View { + let p = theme.palette + NavigationStack { + Form { + Section { + HStack(spacing: 16) { + Group { + if let coverPreview { Image(uiImage: coverPreview).resizable().scaledToFill() } + else if cover == .some(nil) { p.cSurfaceHighest.overlay(Image(systemName: "photo.badge.minus")) } + else { CoverThumb(song: songs.first, size: 96, radius: 16) } + } + .frame(width: 96, height: 96) + .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) + VStack(alignment: .leading, spacing: 10) { + PhotosPicker(selection: $photo, matching: .images) { Label("Choose image", systemImage: "photo") } + Button { lookup = true } label: { Label("Search online", systemImage: "magnifyingglass") } + Button(role: .destructive) { cover = .some(nil); coverPreview = nil } label: { Label("Remove cover", systemImage: "trash") } + } + .font(.system(size: 15)) + } + .listRowBackground(p.cSurfaceC) + } + Section(songs.count == 1 ? songs[0].fileName : "\(songs.count) songs") { + ForEach($fields) { $f in + VStack(alignment: .leading, spacing: 4) { + Text(f.label).font(.system(size: 12, weight: .medium)).foregroundColor(p.cPrimary) + if f.multiline { + TextEditor(text: Binding(get: { f.value }, set: { f.value = $0; f.touched = true })) + .frame(minHeight: 120) + .scrollContentBackground(.hidden) + } else { + TextField(f.mixed && !f.touched ? "Keep (different values)" : "", text: Binding(get: { f.value }, set: { f.value = $0; f.touched = true })) + .keyboardType(["year", "track", "disc"].contains(f.id) ? .numbersAndPunctuation : .default) + } + } + .listRowBackground(p.cSurfaceC) + } + } + if let error { + Section { Text(error).foregroundColor(Color(rgb: p.error)) }.listRowBackground(p.cSurfaceC) + } + if songs.contains(where: { !TagWriter.canWrite($0.url) }) { + Section { Text("Some of these files are in a format Mulberry can't write tags to yet (WMA, APE, WavPack…). They'll be skipped.").font(.footnote) } + .listRowBackground(p.cSurfaceC) + } + } + .scrollContentBackground(.hidden) + .background(p.cSurfaceLow) + .navigationTitle(songs.count == 1 ? "Edit tags" : "Edit tags (\(songs.count))") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button(saving ? "Saving…" : "Save") { save() }.disabled(saving).fontWeight(.semibold) + } + } + .sheet(isPresented: $lookup) { + if let s = songs.first { + CoverPicker(song: s) { data in cover = .some(data); coverPreview = UIImage(data: data) }.environmentObjects() + } + } + } + .tint(p.cPrimary) + .onAppear(perform: load) + .onChange(of: photo) { item in + Task { + if let d = try? await item?.loadTransferable(type: Data.self), let img = UIImage(data: d) { + let jpeg = WidgetBridge.squareThumb(img, min(1200, max(img.size.width, img.size.height)))?.jpegData(compressionQuality: 0.9) ?? d + cover = .some(jpeg) + coverPreview = img + } + } + } + } + + private func load() { + func common(_ f: (Song) -> String) -> (String, Bool) { + let vals = Set(songs.map(f)) + return vals.count == 1 ? (vals.first!, false) : ("", true) + } + let defs: [(String, String, (Song) -> String)] = [ + ("title", "Title", { $0.title }), ("artist", "Artist", { $0.artist }), ("album", "Album", { $0.album }), + ("albumArtist", "Album artist", { $0.albumArtist }), ("genre", "Genre", { $0.genre }), + ("year", "Year", { $0.year > 0 ? String($0.year) : "" }), ("track", "Track", { $0.track > 0 ? String($0.track) : "" }), + ("disc", "Disc", { $0.disc > 0 ? String($0.disc) : "" }), + ] + fields = defs.compactMap { id, label, f in + if songs.count > 1 && (id == "title" || id == "track") { return nil } + let (v, mixed) = common(f) + return Field(id: id, label: label, value: v, mixed: mixed) + } + if songs.count == 1 { + let lyr = TagReader.read(songs[0].url).lyrics + fields.append(Field(id: "lyrics", label: "Lyrics", value: lyr, mixed: false, multiline: true)) + } + } + + private func save() { + var edit = TagEdit() + for f in fields where f.touched { + let v = f.value.trimmingCharacters(in: .whitespacesAndNewlines) + switch f.id { + case "title": edit.title = v + case "artist": edit.artist = v + case "album": edit.album = v + case "albumArtist": edit.albumArtist = v + case "genre": edit.genre = v + case "year": edit.year = v + case "track": edit.track = v + case "disc": edit.disc = v + case "lyrics": edit.lyrics = f.value + default: break + } + } + edit.cover = cover + guard !edit.isEmpty else { dismiss(); return } + saving = true + let targets = songs.filter { TagWriter.canWrite($0.url) } + Task.detached(priority: .userInitiated) { + var failed: [String] = [] + for s in targets { + do { try TagWriter.write(s.url, edit) } catch { failed.append("\(s.fileName): \(error.localizedDescription)") } + } + await MainActor.run { + for s in targets { Library.shared.updated(s); Covers.forget(s) } + if let cur = Player.shared.current, targets.contains(where: { $0.id == cur.id }) { Player.shared.loadArtAndLyrics(cur) } + saving = false + if failed.isEmpty { + UIState.shared.show("Saved \(targets.count) file\(targets.count == 1 ? "" : "s")") + dismiss() + } else { + error = failed.joined(separator: "\n") + } + } + } + } +} + +struct DetailsSheet: View { + let song: Song + @EnvironmentObject var theme: Theme + @EnvironmentObject var stats: PlayStats + + var body: some View { + let p = theme.palette + let attrs = try? FileManager.default.attributesOfItem(atPath: song.url.path) + let size = (attrs?[.size] as? NSNumber)?.int64Value ?? song.size + NavigationStack { + List { + row("Title", song.displayTitle) + row("Artist", song.displayArtist) + row("Album", song.album) + row("Album artist", song.albumArtist) + row("Genre", song.genre) + row("Year", song.year > 0 ? String(song.year) : "") + row("Track", song.track > 0 ? String(song.track) : "") + row("Length", TimeFmt.string(song.duration)) + row("File type", song.url.pathExtension.uppercased()) + row("Size", ByteCountFormatter.string(fromByteCount: size, countStyle: .file)) + if song.duration > 0 && size > 0 { row("Bitrate", "\(Int(Double(size) * 8 / song.duration / 1000)) kbps") } + row("Location", "Mulberry/" + song.path) + row("Plays", String(stats.count(song))) + HStack { + Text("Rating").foregroundColor(p.cOnSurfaceVar) + Spacer() + ForEach(1...5, id: \.self) { i in + Image(systemName: i <= stats.rating(song) ? "star.fill" : "star") + .foregroundColor(p.cPrimary) + .onTapGesture { stats.setRating(song, stats.rating(song) == i ? 0 : i) } + } + } + .listRowBackground(p.cSurfaceC) + } + .scrollContentBackground(.hidden) + .background(p.cSurfaceLow) + .navigationTitle("Details") + .navigationBarTitleDisplayMode(.inline) + } + .presentationDetents([.medium, .large]) + } + + private func row(_ k: String, _ v: String) -> some View { + HStack(alignment: .top) { + Text(k).foregroundColor(theme.palette.cOnSurfaceVar) + Spacer() + Text(v.isEmpty ? "—" : v).foregroundColor(theme.palette.cOnSurface).multilineTextAlignment(.trailing).textSelection(.enabled) + } + .listRowBackground(theme.palette.cSurfaceC) + } +} + +/// Online cover search (desktop cover manager): pick one to save as override or embed. +struct CoverPicker: View { + let song: Song + var onPick: ((Data) -> Void)? + @EnvironmentObject var theme: Theme + @Environment(\.dismiss) var dismiss + @State private var results: [Covers.Candidate] = [] + @State private var loading = true + @State private var artist = "" + @State private var album = "" + + var body: some View { + let p = theme.palette + NavigationStack { + VStack(spacing: 0) { + HStack { + TextField("Artist", text: $artist).textFieldStyle(.roundedBorder) + TextField("Album", text: $album).textFieldStyle(.roundedBorder) + Button { search() } label: { Image(systemName: "magnifyingglass") } + } + .padding() + if loading { ProgressView().padding() } + ScrollView { + LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 12)], spacing: 12) { + ForEach(results) { c in + Button { pick(c) } label: { + VStack(alignment: .leading, spacing: 4) { + AsyncImage(url: URL(string: c.thumb)) { img in img.resizable().scaledToFill() } placeholder: { p.cSurfaceHighest } + .frame(height: 150).clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) + Text(c.source).font(.caption.weight(.semibold)).foregroundColor(p.cPrimary) + Text(c.label).font(.caption).foregroundColor(p.cOnSurfaceVar).lineLimit(2) + } + } + .buttonStyle(.plain) + } + } + .padding(.horizontal) + } + if !loading && results.isEmpty { Text("No covers found").foregroundColor(p.cOnSurfaceVar).padding() } + } + .background(p.cSurfaceLow) + .navigationTitle("Choose cover") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + if onPick == nil { + ToolbarItem(placement: .destructiveAction) { + Button("Reset") { Covers.setOverride(song, nil); Player.shared.loadArtAndLyrics(song); dismiss() } + } + } + } + } + .onAppear { artist = song.groupArtist; album = song.album; search() } + } + + private func search() { + loading = true + let a = artist, al = album, t = song.displayTitle + Task.detached { + let r = Covers.candidates(artist: a, album: al, title: t) + await MainActor.run { results = r; loading = false } + } + } + + private func pick(_ c: Covers.Candidate) { + loading = true + Task.detached { + let d = try? Net.data(c.url) + await MainActor.run { + loading = false + guard let d, UIImage(data: d) != nil else { UIState.shared.show("Couldn't download that cover"); return } + if let onPick { onPick(d) } else { + Covers.setOverride(song, d) + if Player.shared.current?.albumKey == song.albumKey { Player.shared.loadArtAndLyrics(Player.shared.current!) } + UIState.shared.show("Cover saved") + } + dismiss() + } + } + } +} + +/// Edit / save lyrics as an .lrc next to the song (Android "Edit / save lyrics…"). +struct LyricsEditor: View { + let song: Song + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @Environment(\.dismiss) var dismiss + @State private var text = "" + + var body: some View { + let p = theme.palette + NavigationStack { + VStack(spacing: 8) { + TextEditor(text: $text) + .font(.system(size: 15, design: .monospaced)) + .scrollContentBackground(.hidden) + .padding(8) + .background(RoundedRectangle(cornerRadius: 16).fill(p.cSurfaceC)) + HStack { + Button { + // Insert a timestamp for the current position at the cursor line start (simple LRC syncing). + let t = player.position + text += String(format: "[%02d:%05.2f]", Int(t) / 60, t.truncatingRemainder(dividingBy: 60)) + } label: { Label("Insert time", systemImage: "clock") } + Spacer() + Text("Saved as \(song.url.deletingPathExtension().lastPathComponent).lrc").font(.caption).foregroundColor(p.cOnSurfaceVar) + } + } + .padding() + .background(p.cSurfaceLow) + .navigationTitle("Lyrics") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + let url = song.url.deletingPathExtension().appendingPathExtension("lrc") + try? text.write(to: url, atomically: true, encoding: .utf8) + Lyrics.clearCache(song) + player.reloadLyrics(online: false) + dismiss() + } + } + } + } + .tint(p.cPrimary) + .onAppear { text = player.lyrics?.raw ?? Lyrics.local(song) } + } +} diff --git a/App/UI/LibraryView.swift b/App/UI/LibraryView.swift new file mode 100644 index 0000000..e55717f --- /dev/null +++ b/App/UI/LibraryView.swift @@ -0,0 +1,259 @@ +import SwiftUI +import UniformTypeIdentifiers + +struct LibraryView: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var ui: UIState + @EnvironmentObject var lib: Library + @EnvironmentObject var player: Player + @EnvironmentObject var prefs: Prefs + @State private var query = "" + @State private var importing = false + + private let tabs = ["Songs", "Albums", "Artists", "Folders", "Genres"] + + var body: some View { + let p = theme.palette + NavigationStack(path: $ui.libraryPath) { + VStack(spacing: 0) { + header + searchField + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(tabs.indices, id: \.self) { i in + Chip(title: tabs[i], selected: prefs.libTab == i) { + withAnimation(.easeOut(duration: 0.15)) { prefs.libTab = i } + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + content + } + .surface(p) + .toolbar(.hidden, for: .navigationBar) + .navigationDestination(for: LibraryRoute.self) { r in + switch r { + case .group(let g): GroupDetail(group: g) + case .smart(let k): SmartListView(key: k) + case .playlist(let id): PlaylistDetail(id: id) + } + } + } + .fileImporter(isPresented: $importing, allowedContentTypes: [.audio, .folder, .item], allowsMultipleSelection: true) { r in + if case .success(let urls) = r { importFiles(urls) } + } + } + + private var header: some View { + let p = theme.palette + return HStack(spacing: 6) { + Text("Library") + .font(.system(size: 34, weight: .bold)) + .foregroundColor(p.cOnSurface) + Spacer() + Menu { + Picker("Sort songs by", selection: $prefs.sortKey) { + Text("Title").tag("title") + Text("Artist").tag("artist") + Text("Album").tag("album") + Text("Year").tag("year") + Text("Recently added").tag("added") + Text("Length").tag("duration") + } + Divider() + Button { importing = true } label: { Label("Import from Files…", systemImage: "square.and.arrow.down") } + Button { lib.scan(force: true); ui.show("Rescanning…") } label: { Label("Rescan library", systemImage: "arrow.clockwise") } + } label: { + Image(systemName: "line.3.horizontal.decrease") + .font(.system(size: 20, weight: .medium)) + .foregroundColor(p.cOnSurfaceVar) + .frame(width: 44, height: 44) + } + Pill(icon: "shuffle", title: "Shuffle", filled: true) { + player.playShuffled(query.isEmpty ? lib.songs : lib.search(query)) + } + } + .padding(.leading, 20) + .padding(.trailing, 14) + .padding(.top, 8) + } + + private var searchField: some View { + let p = theme.palette + return HStack(spacing: 12) { + Image(systemName: "magnifyingglass").font(.system(size: 18)).foregroundColor(p.cOnSurfaceVar) + TextField("", text: $query, prompt: Text("Search songs, artists, albums").foregroundColor(p.cOnSurfaceVar.opacity(0.8))) + .foregroundColor(p.cOnSurface) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .submitLabel(.search) + if !query.isEmpty { + Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundColor(p.cOnSurfaceVar) } + } + } + .padding(.horizontal, 18) + .frame(height: 54) + .background(Capsule().fill(p.cSurfaceHigh)) + .padding(.horizontal, 16) + .padding(.top, 8) + } + + @ViewBuilder private var content: some View { + if lib.songs.isEmpty { + EmptyLibrary(importing: $importing) + } else if !query.isEmpty { + songList(lib.search(query)) + } else { + switch prefs.libTab { + case 1: groupList(lib.albums) + case 2: groupList(lib.artists, circle: true) + case 3: groupList(lib.folders, folder: true) + case 4: groupList(lib.genres) + default: songList(lib.sorted(lib.songs, by: prefs.sortKey)) + } + } + } + + private func songList(_ songs: [Song]) -> some View { + ScrollView { + LazyVStack(spacing: 0) { + ForEach(Array(songs.enumerated()), id: \.element.id) { i, s in + SongRow(song: s, current: player.current?.id == s.id) { ui.songMenu(s, in: songs) } + .onTapGesture { player.playList(songs, start: i) } + .onLongPressGesture { ui.songMenu(s, in: songs) } + } + } + .padding(.bottom, 8) + } + .scrollDismissesKeyboard(.immediately) + } + + private func groupList(_ groups: [Library.Group], circle: Bool = false, folder: Bool = false) -> some View { + ScrollView { + LazyVStack(spacing: 0) { + ForEach(groups) { g in + NavigationLink(value: LibraryRoute.group(g)) { + GroupRow(group: g, circle: circle, folder: folder) + } + .buttonStyle(.plain) + .simultaneousGesture(LongPressGesture().onEnded { _ in ui.groupMenu(g) }) + } + } + } + } + + private func importFiles(_ urls: [URL]) { + let dest = Library.root.appendingPathComponent("Music") + var n = 0 + for u in urls { + let ok = u.startAccessingSecurityScopedResource() + defer { if ok { u.stopAccessingSecurityScopedResource() } } + let ext = u.pathExtension.lowercased() + let target = (Library.playlistExts.contains(ext) ? Playlists.folder : dest).appendingPathComponent(u.lastPathComponent) + try? FileManager.default.removeItem(at: target) + if (try? FileManager.default.copyItem(at: u, to: target)) != nil { n += 1 } + } + ui.show("Imported \(n) item\(n == 1 ? "" : "s")") + lib.scan() + } +} + +struct EmptyLibrary: View { + @Binding var importing: Bool + @EnvironmentObject var theme: Theme + @EnvironmentObject var lib: Library + + var body: some View { + let p = theme.palette + VStack(spacing: 16) { + Spacer() + if lib.scanning { + ProgressView().tint(p.cPrimary) + Text("Scanning your music… \(lib.scanned)").foregroundColor(p.cOnSurfaceVar) + } else { + Image(systemName: "music.note.list").font(.system(size: 44)).foregroundColor(p.cPrimary) + Text("No music yet").font(.system(size: 22, weight: .semibold)).foregroundColor(p.cOnSurface) + Text("Open the Files app › On My iPhone › Mulberry › Music and copy your songs there, or import them here. Playlists go in the Playlists folder.") + .multilineTextAlignment(.center) + .foregroundColor(p.cOnSurfaceVar) + .padding(.horizontal, 32) + Pill(icon: "square.and.arrow.down", title: "Import from Files", filled: true) { importing = true } + Pill(icon: "arrow.clockwise", title: "Rescan") { lib.scan(force: true) } + } + Spacer() + Spacer() + } + .frame(maxWidth: .infinity) + } +} + +/// Album / artist / folder / genre page. +struct GroupDetail: View { + let group: Library.Group + @EnvironmentObject var theme: Theme + @EnvironmentObject var ui: UIState + @EnvironmentObject var player: Player + @Environment(\.dismiss) var dismiss + + var body: some View { + let p = theme.palette + ScrollView { + VStack(spacing: 0) { + HStack { + IconButton(icon: "chevron.left", tint: p.cOnSurface) { dismiss() } + Spacer() + IconButton(icon: "ellipsis", tint: p.cOnSurface) { ui.groupMenu(group) } + } + .padding(.horizontal, 8) + CoverThumb(song: group.cover, size: 220, radius: 28, circle: group.id.hasPrefix("artist:")) + .shadow(color: .black.opacity(0.25), radius: 16, y: 8) + .padding(.top, 4) + Text(group.title) + .font(.system(size: 26, weight: .bold)) + .foregroundColor(p.cOnSurface) + .multilineTextAlignment(.center) + .padding(.top, 18) + .padding(.horizontal, 20) + Text(subtitle) + .font(.system(size: 15)) + .foregroundColor(p.cOnSurfaceVar) + .padding(.top, 4) + HStack(spacing: 10) { + Pill(icon: "play.fill", title: "Play", filled: true) { player.playList(group.songs) } + Pill(icon: "shuffle", title: "Shuffle") { player.playShuffled(group.songs) } + } + .padding(.vertical, 16) + LazyVStack(spacing: 0) { + ForEach(Array(group.songs.enumerated()), id: \.element.id) { i, s in + SongRow(song: s, current: player.current?.id == s.id, showCover: !group.id.hasPrefix("album:"), + trailing: nil) { ui.songMenu(s, in: group.songs) } + .overlay(alignment: .leading) { + if group.id.hasPrefix("album:") { + Text(s.track > 0 ? "\(s.track)" : "") + .font(.system(size: 14).monospacedDigit()) + .foregroundColor(p.cOnSurfaceVar) + .frame(width: 28) + .padding(.leading, 4) + } + } + .padding(.leading, group.id.hasPrefix("album:") ? 22 : 0) + .onTapGesture { player.playList(group.songs, start: i) } + } + } + } + } + .surface(p) + .toolbar(.hidden, for: .navigationBar) + } + + private var subtitle: String { + let total = group.songs.reduce(0) { $0 + $1.duration } + let year = group.songs.map(\.year).filter { $0 > 0 }.max() + var parts = [group.subtitle] + if group.id.hasPrefix("album:"), let year { parts.append(String(year)) } + parts.append("\(group.songs.count) songs · \(Int(total / 60)) min") + return parts.filter { !$0.isEmpty }.joined(separator: " · ") + } +} diff --git a/App/UI/NowPlayingView.swift b/App/UI/NowPlayingView.swift new file mode 100644 index 0000000..8b103ad --- /dev/null +++ b/App/UI/NowPlayingView.swift @@ -0,0 +1,422 @@ +import SwiftUI + +struct NowPlayingView: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @EnvironmentObject var ui: UIState + @EnvironmentObject var stats: PlayStats + @EnvironmentObject var prefs: Prefs + @Environment(\.dismiss) var dismiss + @State private var showLyrics = false + @State private var showQueue = false + @State private var showSleep = false + @State private var showEQ = false + @State private var showCovers = false + @State private var showLyricsEditor = false + @State private var dragPos: Double? + @State private var dragY: CGFloat = 0 + + var body: some View { + let p = theme.palette + GeometryReader { geo in + VStack(spacing: 0) { + topBar + ZStack { + if showLyrics { + LyricsPanel() + .transition(.opacity) + } else { + CookieView(image: player.art, playing: player.isPlaying) + .padding(.horizontal, 12) + .gesture(DragGesture(minimumDistance: 30).onEnded { g in + if g.translation.width < -60 { player.next() } else if g.translation.width > 60 { player.prev() } + }) + .onTapGesture(count: 2) { player.toggle() } + .transition(.opacity) + } + } + .frame(maxHeight: .infinity) + info + seek + controls + bottomRow + } + .padding(.bottom, max(8, geo.safeAreaInsets.bottom > 0 ? 0 : 8)) + } + .background(background.ignoresSafeArea()) + .offset(y: dragY) + .gesture(DragGesture().onChanged { g in dragY = max(0, g.translation.height) } + .onEnded { g in + if g.translation.height > 140 { dismiss() } + withAnimation(.spring()) { dragY = 0 } + }) + .sheet(isPresented: $showQueue) { QueueSheet().environmentObjects() } + .sheet(isPresented: $showSleep) { SleepSheet().environmentObjects() } + .sheet(isPresented: $showEQ) { EqualizerSheet().environmentObjects() } + .sheet(isPresented: $showCovers) { if let s = player.current { CoverPicker(song: s).environmentObjects() } } + .sheet(isPresented: $showLyricsEditor) { if let s = player.current { LyricsEditor(song: s).environmentObjects() } } + .sheet(item: $ui.menu) { m in MenuSheetView(menu: m).environmentObjects() } + .sheet(isPresented: Binding(get: { ui.addToPlaylist != nil }, set: { if !$0 { ui.addToPlaylist = nil } })) { + AddToPlaylistSheet(songs: ui.addToPlaylist ?? []).environmentObjects() + } + .sheet(isPresented: Binding(get: { ui.editTags != nil }, set: { if !$0 { ui.editTags = nil } })) { + TagEditorView(songs: ui.editTags ?? []).environmentObjects() + } + .sheet(item: $ui.details) { s in DetailsSheet(song: s).environmentObjects() } + .preferredColorScheme(theme.palette.dark ? .dark : .light) + .onChange(of: player.current == nil) { if $0 { dismiss() } } + } + + private var background: some View { + let p = theme.palette + return LinearGradient(colors: [Color(rgb: Palette.mix(p.primaryContainer, p.surface, 0.25)), + Color(rgb: Palette.mix(p.primaryContainer, p.surface, 0.75)), p.cSurface], + startPoint: .top, endPoint: .bottom) + } + + private var topBar: some View { + let p = theme.palette + return HStack { + IconButton(icon: "chevron.down", tint: p.cOnSurface) { dismiss() } + Spacer() + VStack(spacing: 4) { + Text("NOW PLAYING").font(.system(size: 11, weight: .medium)).tracking(1.2).foregroundColor(p.cOnSurfaceVar) + Text("Mulberry") + .font(.system(size: 11, weight: .medium)) + .padding(.horizontal, 10).padding(.vertical, 3) + .foregroundColor(p.cOnPrimaryC) + .background(Capsule().fill(p.cPrimaryC)) + } + Spacer() + Button { npMenu() } label: { + Image(systemName: "ellipsis").rotationEffect(.degrees(90)) + .font(.system(size: 18, weight: .semibold)).foregroundColor(p.cOnSurface) + .frame(width: 44, height: 44) + } + } + .padding(.horizontal, 8) + } + + private var info: some View { + let p = theme.palette + let s = player.current + return HStack(alignment: .bottom) { + VStack(alignment: .leading, spacing: 3) { + Text(s?.displayTitle ?? "Nothing playing") + .font(.system(size: 28, weight: .bold)) + .foregroundColor(p.cOnSurface) + .lineLimit(2) + .minimumScaleFactor(0.7) + Text(s?.displayArtist ?? "") + .font(.system(size: 17)) + .foregroundColor(p.cOnSurface.opacity(0.9)) + .lineLimit(1) + .onTapGesture { if let s { goArtist(s) } } + if let a = s?.album, !a.isEmpty { + Text(a).font(.system(size: 16)).foregroundColor(p.cPrimary).lineLimit(1) + .onTapGesture { if let s { goAlbum(s) } } + } + } + Spacer() + if let s { + let fav = stats.fav(s) + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + stats.setFav(s, !fav) + } label: { + Image(systemName: fav ? "heart.fill" : "heart") + .font(.system(size: 24)) + .foregroundColor(fav ? p.cPrimary : p.cOnSurface) + .frame(width: 48, height: 48) + .scaleEffect(fav ? 1.08 : 1) + .animation(.spring(response: 0.25, dampingFraction: 0.5), value: fav) + } + } + } + .padding(.horizontal, 20) + } + + private var seek: some View { + let p = theme.palette + return TimelineView(.periodic(from: .now, by: 0.5)) { _ in + VStack(spacing: 0) { + WavySeekBar(position: player.position, duration: player.duration, playing: player.isPlaying, + onDrag: { dragPos = $0 }) { player.seek($0) } + HStack { + Text(TimeFmt.string(dragPos ?? player.position)) + Spacer() + Text(TimeFmt.string(player.duration)) + } + .font(.system(size: 13).monospacedDigit()) + .foregroundColor(p.cOnSurfaceVar) + .padding(.horizontal, 20) + } + .padding(.horizontal, 10) + .padding(.top, 10) + } + } + + private var controls: some View { + let p = theme.palette + return HStack(spacing: 14) { + IconButton(icon: "shuffle", size: 52, tint: prefs.shuffle ? p.cOnPrimaryC : p.cOnSecondaryC, + filled: prefs.shuffle ? p.cPrimaryC : p.cSecondaryC.opacity(0.7)) { player.setShuffle(!prefs.shuffle) } + IconButton(icon: "backward.end.fill", size: 52, tint: p.cOnSecondaryC, filled: p.cSecondaryC.opacity(0.7)) { player.prev() } + PlayButton(playing: player.isPlaying) { player.toggle() } + .frame(width: 96, height: 72) + IconButton(icon: "forward.end.fill", size: 52, tint: p.cOnSecondaryC, filled: p.cSecondaryC.opacity(0.7)) { player.next() } + IconButton(icon: prefs.repeatMode == 2 ? "repeat.1" : "repeat", size: 52, + tint: prefs.repeatMode > 0 ? p.cOnPrimaryC : p.cOnSecondaryC, + filled: prefs.repeatMode > 0 ? p.cPrimaryC : p.cSecondaryC.opacity(0.7)) { player.cycleRepeat() } + } + .padding(.vertical, 14) + } + + private var bottomRow: some View { + let p = theme.palette + return HStack { + IconButton(icon: showLyrics ? "quote.bubble.fill" : "quote.bubble", tint: showLyrics ? p.cPrimary : p.cOnSurfaceVar) { + withAnimation(.easeInOut(duration: 0.25)) { showLyrics.toggle() } + } + Spacer() + IconButton(icon: "list.bullet") { showQueue = true } + Spacer() + IconButton(icon: player.sleepAt != nil || player.sleepAtTrackEnd ? "moon.zzz.fill" : "moon.zzz", + tint: player.sleepAt != nil || player.sleepAtTrackEnd ? p.cPrimary : p.cOnSurfaceVar) { showSleep = true } + Spacer() + IconButton(icon: "pencil") { if let s = player.current, !s.isStream { ui.editTags = [s] } } + } + .padding(.horizontal, 40) + .padding(.bottom, 6) + } + + private func goAlbum(_ s: Song) { + if let g = Library.shared.albums.first(where: { $0.id == "album:" + s.albumKey }) { dismiss(); UIState.shared.go(.group(g)) } + } + + private func goArtist(_ s: Song) { + if let g = Library.shared.artists.first(where: { $0.title == s.groupArtist }) { dismiss(); UIState.shared.go(.group(g)) } + } + + private func npMenu() { + guard let s = player.current else { return } + var items: [MenuSheet.Item] = [ + .init("Add to playlist…", "music.note.list") { ui.addToPlaylist = [s] }, + .init("Go to album", "square.stack") { goAlbum(s) }, + .init("Go to artist", "person") { goArtist(s) }, + .init(player.stopAfterCurrent ? "Keep playing after this song" : "Stop after this song", "stop.circle") { + player.stopAfterCurrent.toggle() + ui.show(player.stopAfterCurrent ? "Stops after this song" : "Keeps playing") + }, + .init("Equalizer", "slider.vertical.3") { showEQ = true }, + .init("Search lyrics again", "arrow.clockwise") { player.reloadLyrics(online: true); showLyrics = true }, + .init("Edit / save lyrics…", "text.quote") { showLyricsEditor = true }, + .init("Choose cover…", "photo") { showCovers = true }, + ] + if !s.isStream { + items.append(.init("Details", "info.circle") { ui.details = s }) + items.append(.init("Share", "square.and.arrow.up") { share([s.url]) }) + } + if Scrobbler.shared.lfmOn { + items.append(.init("Love on Last.fm", "heart.circle") { Scrobbler.shared.love(s, true) }) + } + ui.menu = MenuSheet(title: s.displayTitle, subtitle: s.subtitle, song: s, items: items) + } +} + +/// Synced lyrics, auto-scrolling, tap a line to seek (Android LyricsView). +struct LyricsPanel: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @State private var userScrolled = Date.distantPast + + var body: some View { + let p = theme.palette + Group { + if let lr = player.lyrics, !lr.lines.isEmpty { + TimelineView(.periodic(from: .now, by: 0.2)) { _ in + let cur = lr.synced ? Lyrics.lineAt(lr.lines, player.position) : -1 + ScrollViewReader { proxy in + ScrollView(showsIndicators: false) { + VStack(alignment: .leading, spacing: 18) { + Color.clear.frame(height: 100) + ForEach(Array(lr.lines.enumerated()), id: \.offset) { i, l in + Text(l.text.isEmpty ? "♪" : l.text) + .font(.system(size: lr.synced ? 24 : 19, weight: lr.synced ? .bold : .medium)) + .foregroundColor(i == cur ? p.cOnSurface : p.cOnSurfaceVar.opacity(lr.synced ? (i < cur ? 0.45 : 0.6) : 0.9)) + .scaleEffect(i == cur ? 1.0 : 0.96, anchor: .leading) + .animation(.easeOut(duration: 0.25), value: cur) + .id(i) + .onTapGesture { if l.t >= 0 { player.seek(l.t) } } + } + if !lr.source.isEmpty { + Text("Lyrics from \(lr.source)").font(.system(size: 12)).foregroundColor(p.cOnSurfaceVar.opacity(0.6)) + } + Color.clear.frame(height: 200) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 28) + } + .simultaneousGesture(DragGesture().onChanged { _ in userScrolled = Date() }) + .onChange(of: cur) { c in + guard c >= 0, Date().timeIntervalSince(userScrolled) > 3 else { return } + withAnimation(.easeInOut(duration: 0.4)) { proxy.scrollTo(c, anchor: UnitPoint(x: 0, y: 0.35)) } + } + .onAppear { if cur >= 0 { proxy.scrollTo(cur, anchor: UnitPoint(x: 0, y: 0.35)) } } + } + } + .mask(LinearGradient(stops: [.init(color: .clear, location: 0), .init(color: .black, location: 0.12), + .init(color: .black, location: 0.85), .init(color: .clear, location: 1)], + startPoint: .top, endPoint: .bottom)) + } else { + VStack(spacing: 14) { + Image(systemName: "text.quote").font(.system(size: 36)).foregroundColor(p.cPrimary) + Text(player.lyrics?.message.isEmpty == false ? player.lyrics!.message : (player.lyrics == nil ? "Looking for lyrics…" : "No lyrics")) + .multilineTextAlignment(.center).foregroundColor(p.cOnSurfaceVar) + Pill(icon: "arrow.clockwise", title: "Search again") { player.reloadLyrics(online: true) } + } + .padding(32) + } + } + } +} + +/// Up-next queue with reorder and swipe to remove. +struct QueueSheet: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @EnvironmentObject var ui: UIState + @State private var saveName = "" + @State private var askSave = false + + var body: some View { + let p = theme.palette + NavigationStack { + ScrollViewReader { proxy in + List { + ForEach(Array(player.queue.enumerated()), id: \.offset) { i, s in + SongRow(song: s, current: i == player.index) + .listRowInsets(EdgeInsets()) + .listRowBackground(i == player.index ? p.cSecondaryC.opacity(0.5) : Color.clear) + .onTapGesture { player.jump(i) } + .id(i) + } + .onDelete { idx in idx.sorted(by: >).forEach { player.removeAt($0) } } + .onMove { from, to in if let f = from.first { player.move(f, to) } } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .environment(\.editMode, .constant(.active)) + .onAppear { proxy.scrollTo(max(0, player.index - 2), anchor: .top) } + } + .navigationTitle("Queue · \(player.queue.count)") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Button("Save") { saveName = "Queue \(Date().formatted(date: .abbreviated, time: .omitted))"; askSave = true } + } + ToolbarItem(placement: .topBarTrailing) { + Button("Clear", role: .destructive) { player.clearQueue() } + } + } + .alert("Save queue as playlist", isPresented: $askSave) { + TextField("Name", text: $saveName) + Button("Save") { Playlists.shared.create(saveName, player.queue); ui.show("Saved") } + Button("Cancel", role: .cancel) {} + } + } + .presentationDetents([.large]) + .presentationBackground(p.cSurfaceLow) + } +} + +struct SleepSheet: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @Environment(\.dismiss) var dismiss + + var body: some View { + let p = theme.palette + VStack(alignment: .leading, spacing: 0) { + Text("Sleep timer").font(.system(size: 22, weight: .semibold)).foregroundColor(p.cOnSurface).padding(24) + if let at = player.sleepAt { + Text("Stops at \(at.formatted(date: .omitted, time: .shortened))").foregroundColor(p.cPrimary).padding(.horizontal, 24) + } else if player.sleepAtTrackEnd { + Text("Stops after this song").foregroundColor(p.cPrimary).padding(.horizontal, 24) + } + ForEach([5, 15, 30, 45, 60, 90, 120], id: \.self) { m in + row("\(m) minutes") { player.sleep(minutes: m) } + } + row("End of this song") { player.sleepAtEndOfTrack() } + row("Turn off") { player.cancelSleep() } + } + .frame(maxWidth: .infinity, alignment: .leading) + .presentationDetents([.medium, .large]) + .presentationBackground(p.cSurfaceLow) + } + + private func row(_ t: String, _ a: @escaping () -> Void) -> some View { + Button { a(); dismiss() } label: { + Text(t).font(.system(size: 17)).foregroundColor(theme.palette.cOnSurface) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 24).padding(.vertical, 13) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } +} + +struct EqualizerSheet: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var prefs: Prefs + + static let presets: [(String, [Double])] = [ + ("Flat", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + ("Bass boost", [6, 5, 4, 2, 0, 0, 0, 0, 0, 0]), + ("Treble boost", [0, 0, 0, 0, 0, 1, 2, 4, 5, 6]), + ("Rock", [4, 3, 2, 0, -1, -1, 1, 2, 3, 4]), + ("Pop", [-1, 1, 3, 4, 3, 0, -1, -1, 1, 2]), + ("Vocal", [-2, -2, -1, 1, 3, 4, 3, 1, 0, -1]), + ("Loudness", [5, 4, 1, 0, -1, 0, 0, 1, 4, 5]), + ] + + var body: some View { + let p = theme.palette + VStack(spacing: 18) { + HStack { + Text("Equalizer").font(.system(size: 22, weight: .semibold)).foregroundColor(p.cOnSurface) + Spacer() + Toggle("", isOn: $prefs.eqOn).labelsHidden().tint(p.cPrimary) + } + ScrollView(.horizontal, showsIndicators: false) { + HStack { + ForEach(Self.presets, id: \.0) { pr in + Chip(title: pr.0, selected: prefs.eqBands == pr.1) { prefs.eqBands = pr.1; prefs.eqOn = true; Player.shared.applyEQ() } + } + } + } + HStack(alignment: .bottom, spacing: 0) { + ForEach(0..<10, id: \.self) { i in + VStack(spacing: 6) { + Text(String(format: "%+.0f", prefs.eqBands[i])).font(.system(size: 11).monospacedDigit()).foregroundColor(p.cOnSurfaceVar) + Slider(value: Binding(get: { prefs.eqBands[i] }, set: { prefs.eqBands[i] = $0; Player.shared.applyEQ() }), in: -12...12, step: 1) + .rotationEffect(.degrees(-90)) + .frame(width: 180, height: 30) + .frame(width: 30, height: 180) + let f = Player.eqFreqs[i] + Text(f >= 1000 ? "\(Int(f / 1000))k" : "\(Int(f))").font(.system(size: 11)).foregroundColor(p.cOnSurfaceVar) + } + .frame(maxWidth: .infinity) + } + } + .disabled(!prefs.eqOn) + .opacity(prefs.eqOn ? 1 : 0.5) + Spacer() + } + .padding(24) + .tint(p.cPrimary) + .onChange(of: prefs.eqOn) { _ in Player.shared.applyEQ() } + .presentationDetents([.medium]) + .presentationBackground(p.cSurfaceLow) + } +} diff --git a/App/UI/PlaylistsView.swift b/App/UI/PlaylistsView.swift new file mode 100644 index 0000000..d705816 --- /dev/null +++ b/App/UI/PlaylistsView.swift @@ -0,0 +1,318 @@ +import SwiftUI +import UniformTypeIdentifiers + +struct PlaylistsView: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var ui: UIState + @EnvironmentObject var lib: Library + @EnvironmentObject var lists: Playlists + @EnvironmentObject var stats: PlayStats + @EnvironmentObject var player: Player + @State private var importing = false + @State private var askNew = false + @State private var newName = "" + @State private var exportFormat = false + + static let smart: [(key: String, title: String, icon: String)] = [ + ("fav", "Favourites", "heart.fill"), ("most", "Most played", "chart.line.uptrend.xyaxis"), + ("recent", "Recently played", "clock.arrow.circlepath"), ("added", "Recently added", "plus.square.on.square"), + ("never", "Never played", "eye"), ("rated", "Top rated", "star.fill"), + ] + + static func smartSongs(_ key: String) -> [Song] { + let all = Library.shared.songs, s = PlayStats.shared + switch key { + case "fav": return s.favourites(all) + case "most": return s.mostPlayed(all) + case "recent": return s.recentlyPlayed(all) + case "added": return s.recentlyAdded(all) + case "never": return s.neverPlayed(all) + case "rated": return s.topRated(all) + default: return [] + } + } + + var body: some View { + let p = theme.palette + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + Text("Playlists").font(.system(size: 34, weight: .bold)).foregroundColor(p.cOnSurface) + .padding(.horizontal, 20).padding(.top, 8) + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + Pill(icon: "plus", title: "New", filled: true) { newName = ""; askNew = true } + Pill(icon: "square.and.arrow.down", title: "Import") { importing = true } + Pill(icon: "square.and.arrow.up", title: "Export all") { exportFormat = true } + Pill(icon: "list.bullet.rectangle", title: "Save queue") { + guard !player.queue.isEmpty else { ui.show("The queue is empty"); return } + lists.create("Queue \(Date().formatted(date: .abbreviated, time: .shortened))", player.queue) + ui.show("Saved") + } + } + .padding(.horizontal, 16).padding(.vertical, 12) + } + SectionLabel(text: "Smart playlists") + ForEach(Self.smart, id: \.key) { sm in + NavigationLink(value: LibraryRoute.smart(sm.key)) { + listRow(icon: sm.icon, title: sm.title, sub: "\(Self.smartSongs(sm.key).count) songs", tile: p.cTertiary) + } + .buttonStyle(.plain) + } + SectionLabel(text: lists.all.isEmpty ? "Your playlists — none yet" : "Your playlists") + ForEach(lists.all) { pl in + NavigationLink(value: LibraryRoute.playlist(pl.id)) { + listRow(icon: "music.note.list", title: pl.name, sub: "\(pl.paths.count) songs", tile: p.cSecondaryC) + } + .buttonStyle(.plain) + .contextMenu { playlistMenu(pl) } + } + if lists.all.isEmpty { + Text("Tap New, import an .m3u/.pls/.xspf file, or drop playlists into Files › On My iPhone › Mulberry › Playlists.") + .font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar) + .padding(.horizontal, 20).padding(.top, 4) + } + } + .padding(.bottom, 20) + } + .surface(p) + .toolbar(.hidden, for: .navigationBar) + .navigationDestination(for: LibraryRoute.self) { r in + switch r { + case .group(let g): GroupDetail(group: g) + case .smart(let k): SmartListView(key: k) + case .playlist(let id): PlaylistDetail(id: id) + } + } + } + .fileImporter(isPresented: $importing, allowedContentTypes: Self.playlistTypes, allowsMultipleSelection: true) { r in + guard case .success(let urls) = r else { return } + var msgs: [String] = [] + for u in urls { + let ok = u.startAccessingSecurityScopedResource() + defer { if ok { u.stopAccessingSecurityScopedResource() } } + do { + let (pl, found, total) = try lists.importFile(u) + msgs.append("\(pl.name): \(found)/\(total)") + } catch { msgs.append("Import failed: \(error.localizedDescription)") } + } + ui.show(msgs.joined(separator: " · ")) + } + .alert("New playlist", isPresented: $askNew) { + TextField("Name", text: $newName) + Button("Create") { lists.create(newName, []) } + Button("Cancel", role: .cancel) {} + } + .confirmationDialog("Export all playlists", isPresented: $exportFormat) { + ForEach(["m3u8", "m3u", "pls", "xspf", "wpl"], id: \.self) { f in + Button(f.uppercased()) { + let n = lists.exportAll(format: f) + ui.show(n == 0 ? "No playlists to export" : "Exported \(n) to Files › Mulberry › Playlists") + } + } + } + } + + static var playlistTypes: [UTType] { + ["m3u", "m3u8", "pls", "xspf", "wpl", "asx"].compactMap { UTType(filenameExtension: $0) } + [.m3uPlaylist, .plainText, .xml, .item] + } + + private func listRow(icon: String, title: String, sub: String, tile: Color) -> some View { + let p = theme.palette + return HStack(spacing: 14) { + RoundedRectangle(cornerRadius: 12, style: .continuous).fill(tile.opacity(0.35)) + .frame(width: 48, height: 48) + .overlay(Image(systemName: icon).font(.system(size: 19, weight: .semibold)).foregroundColor(p.cOnSurface)) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.system(size: 16)).foregroundColor(p.cOnSurface) + Text(sub).font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar) + } + Spacer() + } + .padding(.horizontal, 16).padding(.vertical, 6) + .contentShape(Rectangle()) + } + + @ViewBuilder private func playlistMenu(_ pl: Playlists.PL) -> some View { + Button { player.playList(lists.songs(pl)) } label: { Label("Play", systemImage: "play") } + Button { player.playShuffled(lists.songs(pl)) } label: { Label("Shuffle", systemImage: "shuffle") } + Button { if let u = try? lists.export(pl, format: "m3u8") { share([u]) } } label: { Label("Share", systemImage: "square.and.arrow.up") } + Button(role: .destructive) { lists.delete(pl) } label: { Label("Delete playlist", systemImage: "trash") } + } +} + +struct SmartListView: View { + let key: String + @EnvironmentObject var stats: PlayStats + @EnvironmentObject var lib: Library + + var body: some View { + let title = PlaylistsView.smart.first { $0.key == key }?.title ?? "" + SongListPage(title: title, songs: PlaylistsView.smartSongs(key)) + } +} + +struct PlaylistDetail: View { + let id: UUID + @EnvironmentObject var lists: Playlists + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @EnvironmentObject var ui: UIState + @Environment(\.dismiss) var dismiss + @State private var renaming = false + @State private var name = "" + @State private var exporting = false + @State private var editing = false + + var body: some View { + if let pl = lists.all.first(where: { $0.id == id }) { + let p = theme.palette + let songs = lists.songs(pl) + VStack(spacing: 0) { + HStack { + IconButton(icon: "chevron.left", tint: p.cOnSurface) { dismiss() } + Spacer() + Button(editing ? "Done" : "Edit") { withAnimation { editing.toggle() } }.foregroundColor(p.cPrimary) + Menu { + Button { name = pl.name; renaming = true } label: { Label("Rename", systemImage: "pencil") } + Button { exporting = true } label: { Label("Export…", systemImage: "square.and.arrow.up") } + Button { lists.removeDuplicates(pl) } label: { Label("Remove duplicates", systemImage: "square.on.square") } + Button { lists.removeMissing(pl) } label: { Label("Remove missing files", systemImage: "questionmark.square.dashed") } + Button(role: .destructive) { lists.delete(pl); dismiss() } label: { Label("Delete playlist", systemImage: "trash") } + } label: { + Image(systemName: "ellipsis").rotationEffect(.degrees(90)).foregroundColor(p.cOnSurface).frame(width: 44, height: 44) + } + } + .padding(.horizontal, 8) + Text(pl.name).font(.system(size: 28, weight: .bold)).foregroundColor(p.cOnSurface) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 20) + Text("\(songs.count) songs" + (pl.missing.isEmpty ? "" : " · \(pl.missing.count) not found")) + .font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 20) + HStack(spacing: 10) { + Pill(icon: "play.fill", title: "Play", filled: true) { player.playList(songs) } + Pill(icon: "shuffle", title: "Shuffle") { player.playShuffled(songs) } + Spacer() + } + .padding(.horizontal, 16).padding(.vertical, 12) + List { + ForEach(Array(songs.enumerated()), id: \.offset) { i, s in + SongRow(song: s, current: player.current?.id == s.id) { ui.songMenu(s, in: songs, playlist: pl, index: i) } + .listRowInsets(EdgeInsets()) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + .onTapGesture { player.playList(songs, start: i) } + } + .onDelete { lists.removeAt(pl, $0) } + .onMove { lists.move(pl, $0, $1) } + if !pl.missing.isEmpty { + Section("Not found in your library") { + ForEach(pl.missing, id: \.self) { m in + Text(m).font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar.opacity(0.6)) + .listRowBackground(Color.clear) + } + } + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .environment(\.editMode, .constant(editing ? .active : .inactive)) + } + .surface(p) + .toolbar(.hidden, for: .navigationBar) + .alert("Rename playlist", isPresented: $renaming) { + TextField("Name", text: $name) + Button("Rename") { lists.rename(pl, name) } + Button("Cancel", role: .cancel) {} + } + .confirmationDialog("Export", isPresented: $exporting) { + ForEach(["m3u8", "m3u", "pls", "xspf", "wpl"], id: \.self) { f in + Button(f.uppercased()) { if let u = try? lists.export(pl, format: f) { share([u]) } } + } + } + } + } +} + +/// Plain titled song list page (smart lists). +struct SongListPage: View { + let title: String + let songs: [Song] + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @EnvironmentObject var ui: UIState + @Environment(\.dismiss) var dismiss + + var body: some View { + let p = theme.palette + VStack(spacing: 0) { + HStack { + IconButton(icon: "chevron.left", tint: p.cOnSurface) { dismiss() } + Spacer() + } + .padding(.horizontal, 8) + Text(title).font(.system(size: 28, weight: .bold)).foregroundColor(p.cOnSurface) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 20) + HStack(spacing: 10) { + Pill(icon: "play.fill", title: "Play", filled: true) { player.playList(songs) } + Pill(icon: "shuffle", title: "Shuffle") { player.playShuffled(songs) } + Spacer() + } + .padding(.horizontal, 16).padding(.vertical, 12) + ScrollView { + LazyVStack(spacing: 0) { + ForEach(Array(songs.enumerated()), id: \.element.id) { i, s in + SongRow(song: s, current: player.current?.id == s.id) { ui.songMenu(s, in: songs) } + .onTapGesture { player.playList(songs, start: i) } + } + } + } + } + .surface(p) + .toolbar(.hidden, for: .navigationBar) + } +} + +struct AddToPlaylistSheet: View { + let songs: [Song] + @EnvironmentObject var theme: Theme + @EnvironmentObject var lists: Playlists + @EnvironmentObject var ui: UIState + @Environment(\.dismiss) var dismiss + @State private var newName = "" + + var body: some View { + let p = theme.palette + NavigationStack { + List { + Section { + HStack { + TextField("New playlist…", text: $newName) + Button("Create") { + lists.create(newName, songs) + ui.show("Added to \(newName.isEmpty ? "New playlist" : newName)") + dismiss() + } + .disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty) + } + } + Section("Your playlists") { + ForEach(lists.all) { pl in + Button { + lists.add(pl, songs) + ui.show("Added to \(pl.name)") + dismiss() + } label: { + HStack { Text(pl.name).foregroundColor(p.cOnSurface); Spacer(); Text("\(pl.paths.count)").foregroundColor(p.cOnSurfaceVar) } + } + } + } + } + .scrollContentBackground(.hidden) + .navigationTitle("Add \(songs.count) song\(songs.count == 1 ? "" : "s") to playlist") + .navigationBarTitleDisplayMode(.inline) + } + .presentationDetents([.medium, .large]) + .presentationBackground(p.cSurfaceLow) + } +} diff --git a/App/UI/RootView.swift b/App/UI/RootView.swift new file mode 100644 index 0000000..4fb3c9b --- /dev/null +++ b/App/UI/RootView.swift @@ -0,0 +1,341 @@ +import SwiftUI + +/// App-wide UI state: tabs, the now-playing sheet, menus and toasts. +@MainActor +final class UIState: ObservableObject { + static let shared = UIState() + @Published var tab = 0 + @Published var nowPlaying = false + @Published var menu: MenuSheet? + @Published var toast: String? + @Published var libraryPath: [LibraryRoute] = [] + @Published var addToPlaylist: [Song]? + @Published var editTags: [Song]? + @Published var details: Song? + private var toastTask: Task? + + func show(_ text: String) { + toastTask?.cancel() + withAnimation(.spring(response: 0.3)) { toast = text } + toastTask = Task { + try? await Task.sleep(nanoseconds: 2_400_000_000) + if !Task.isCancelled { withAnimation(.easeOut) { toast = nil } } + } + } + + /// Standard per-song menu (Android MainActivity song sheet). + func songMenu(_ s: Song, in list: [Song]? = nil, playlist: Playlists.PL? = nil, index: Int? = nil) { + let player = Player.shared, stats = PlayStats.shared + var items: [MenuSheet.Item] = [ + .init("Play next", "text.insert") { player.playNext([s]); self.show("Plays next") }, + .init("Add to queue", "text.append") { player.enqueue([s]); self.show("Added to queue") }, + .init("Add to playlist…", "music.note.list") { self.addToPlaylist = [s] }, + .init(stats.fav(s) ? "Remove from favourites" : "Add to favourites", stats.fav(s) ? "heart.slash" : "heart") { + stats.setFav(s, !stats.fav(s)) + }, + ] + if !s.album.isEmpty { + items.append(.init("Go to album", "square.stack") { + if let g = Library.shared.albums.first(where: { $0.id == "album:" + s.albumKey }) { self.go(.group(g)) } + }) + } + items.append(.init("Go to artist", "person") { + if let g = Library.shared.artists.first(where: { $0.title == s.groupArtist }) { self.go(.group(g)) } + }) + if !s.isStream { + items.append(.init("Edit tags…", "pencil") { self.editTags = [s] }) + items.append(.init("Details", "info.circle") { self.details = s }) + items.append(.init("Share", "square.and.arrow.up") { share([s.url]) }) + } + if let pl = playlist, let index { + items.append(.init("Remove from playlist", "minus.circle") { Playlists.shared.removeAt(pl, IndexSet(integer: index)) }) + } + if !s.isStream { + items.append(.init("Delete file", "trash", destructive: true) { + self.menu = MenuSheet(title: "Delete \(s.displayTitle)?", subtitle: "The file is removed from your iPhone.", + items: [.init("Delete", "trash", destructive: true) { Library.shared.delete(s) }]) + }) + } + menu = MenuSheet(title: s.displayTitle, subtitle: s.subtitle, song: s, items: items) + } + + func groupMenu(_ g: Library.Group) { + let player = Player.shared + menu = MenuSheet(title: g.title, subtitle: g.subtitle, song: g.cover, items: [ + .init("Play", "play.fill") { player.playList(g.songs) }, + .init("Shuffle", "shuffle") { player.playShuffled(g.songs) }, + .init("Play next", "text.insert") { player.playNext(g.songs); self.show("Plays next") }, + .init("Add to queue", "text.append") { player.enqueue(g.songs); self.show("Added to queue") }, + .init("Add to playlist…", "music.note.list") { self.addToPlaylist = g.songs }, + .init("Edit tags of all songs…", "pencil") { self.editTags = g.songs }, + ]) + } + + func go(_ r: LibraryRoute) { + nowPlaying = false + tab = 0 + libraryPath.append(r) + } +} + +struct MenuSheet: Identifiable { + struct Item: Identifiable { + let id = UUID() + let title: String + let icon: String + var destructive = false + let action: () -> Void + init(_ t: String, _ i: String, destructive: Bool = false, _ a: @escaping () -> Void) { + title = t; icon = i; self.destructive = destructive; action = a + } + } + let id = UUID() + var title: String + var subtitle = "" + var song: Song? + var items: [Item] +} + +enum LibraryRoute: Hashable { + case group(Library.Group) + case smart(String) + case playlist(UUID) +} + +func share(_ urls: [URL]) { + let vc = UIActivityViewController(activityItems: urls, applicationActivities: nil) + guard let root = UIApplication.shared.connectedScenes.compactMap({ ($0 as? UIWindowScene)?.keyWindow }).first?.rootViewController else { return } + var top = root + while let p = top.presentedViewController { top = p } + vc.popoverPresentationController?.sourceView = top.view + top.present(vc, animated: true) +} + +struct RootView: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var ui: UIState + @EnvironmentObject var player: Player + @EnvironmentObject var prefs: Prefs + @EnvironmentObject var scrobbler: Scrobbler + @Environment(\.colorScheme) var scheme + + var body: some View { + let p = theme.palette + ZStack(alignment: .bottom) { + Group { + switch ui.tab { + case 1: PlaylistsView() + case 2: SettingsView() + default: LibraryView() + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .safeAreaInset(edge: .bottom) { Color.clear.frame(height: player.current == nil ? 80 : 168) } + + VStack(spacing: 0) { + if player.current != nil { + MiniPlayer() + .padding(.horizontal, 12) + .padding(.bottom, 8) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } + NavBar() + } + + if prefs.bassShape && !prefs.lowPower && player.current != nil && !ui.nowPlaying { + BassShapeView(playing: player.isPlaying) + .frame(width: 56, height: 56) + .allowsHitTesting(false) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) + .padding(.leading, 6) + .padding(.bottom, 170) + } + + if let t = ui.toast ?? scrobbler.toast { + Toast(text: t) + .padding(.bottom, player.current == nil ? 96 : 184) + .transition(.move(edge: .bottom).combined(with: .opacity)) + .onAppear { + if scrobbler.toast != nil { + DispatchQueue.main.asyncAfter(deadline: .now() + 2.4) { scrobbler.toast = nil } + } + } + } + } + .surface(p) + .preferredColorScheme(prefs.themeMode == "system" ? nil : (prefs.themeMode == "dark" ? .dark : .light)) + .tint(p.cPrimary) + .fullScreenCover(isPresented: $ui.nowPlaying) { NowPlayingView().environmentObjects() } + .sheet(item: $ui.menu) { m in MenuSheetView(menu: m).environmentObjects() } + .sheet(isPresented: Binding(get: { ui.addToPlaylist != nil }, set: { if !$0 { ui.addToPlaylist = nil } })) { + AddToPlaylistSheet(songs: ui.addToPlaylist ?? []).environmentObjects() + } + .sheet(isPresented: Binding(get: { ui.editTags != nil }, set: { if !$0 { ui.editTags = nil } })) { + TagEditorView(songs: ui.editTags ?? []).environmentObjects() + } + .sheet(item: $ui.details) { s in DetailsSheet(song: s).environmentObjects() } + .onAppear { theme.systemDark = scheme == .dark } + .onChange(of: scheme) { theme.systemDark = $0 == .dark } + .onChange(of: prefs.themeMode) { _ in theme.update() } + .onChange(of: prefs.colorSource) { _ in theme.update() } + .onChange(of: prefs.customColor) { _ in theme.update() } + } +} + +extension View { + /// Sheets and covers don't inherit environment objects reliably across presentations. + func environmentObjects() -> some View { + environmentObject(Theme.shared) + .environmentObject(UIState.shared) + .environmentObject(Player.shared) + .environmentObject(Prefs.shared) + .environmentObject(Library.shared) + .environmentObject(Playlists.shared) + .environmentObject(PlayStats.shared) + .environmentObject(Scrobbler.shared) + } +} + +/// Material 3 navigation bar with a pill indicator. +struct NavBar: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var ui: UIState + + var body: some View { + let p = theme.palette + HStack { + item(0, "Library", "music.note.house") + item(1, "Playlists", "music.note.list") + item(2, "Settings", "gearshape") + } + .padding(.top, 10) + .padding(.bottom, 4) + .background(p.cSurfaceC.ignoresSafeArea(edges: .bottom)) + } + + private func item(_ i: Int, _ title: String, _ icon: String) -> some View { + let p = theme.palette + let sel = ui.tab == i + return Button { + if ui.tab == i && i == 0 { ui.libraryPath = [] } + withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) { ui.tab = i } + } label: { + VStack(spacing: 4) { + Image(systemName: icon) + .font(.system(size: 20, weight: sel ? .semibold : .regular)) + .foregroundColor(sel ? p.cOnSecondaryC : p.cOnSurfaceVar) + .frame(width: 64, height: 32) + .background(Capsule().fill(sel ? p.cSecondaryC : .clear)) + Text(title) + .font(.system(size: 12, weight: sel ? .semibold : .medium)) + .foregroundColor(sel ? p.cOnSurface : p.cOnSurfaceVar) + } + .frame(maxWidth: .infinity) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } +} + +/// Floating mini player card above the nav bar (cover cookie, title, play, next, wavy progress). +struct MiniPlayer: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var player: Player + @EnvironmentObject var ui: UIState + + var body: some View { + let p = theme.palette + TimelineView(.periodic(from: .now, by: 0.5)) { _ in + VStack(spacing: 2) { + HStack(spacing: 12) { + CookieView(image: player.art, playing: player.isPlaying, small: true) + .frame(width: 64, height: 64) + VStack(alignment: .leading, spacing: 2) { + Text(player.current?.displayTitle ?? "") + .font(.system(size: 17, weight: .bold)) + .foregroundColor(p.cOnPrimaryC) + .lineLimit(1) + Text(player.current?.displayArtist ?? "") + .font(.system(size: 15)) + .foregroundColor(p.cPrimary) + .lineLimit(1) + } + Spacer(minLength: 4) + PlayButton(playing: player.isPlaying) { player.toggle() } + .frame(width: 64, height: 48) + IconButton(icon: "forward.end.fill", size: 40, tint: p.cOnPrimaryC) { player.next() } + } + WavySeekBar(position: player.position, duration: player.duration, playing: player.isPlaying, height: 22) { + player.seek($0) + } + } + .padding(.leading, 10) + .padding(.trailing, 8) + .padding(.top, 8) + .padding(.bottom, 4) + .background( + RoundedRectangle(cornerRadius: 28, style: .continuous) + .fill(LinearGradient(colors: [Color(rgb: Palette.mix(p.primaryContainer, p.surfaceHigh, 0.35)), + Color(rgb: Palette.mix(p.primaryContainer, p.surfaceHigh, 0.6))], + startPoint: .topLeading, endPoint: .bottomTrailing)) + ) + .contentShape(Rectangle()) + .onTapGesture { ui.nowPlaying = true } + .gesture(DragGesture(minimumDistance: 20).onEnded { g in + if g.translation.height < -40 { ui.nowPlaying = true } + else if g.translation.width < -60 { player.next() } + else if g.translation.width > 60 { player.prev() } + }) + } + } +} + +/// Bottom sheet with a header and a list of actions. +struct MenuSheetView: View { + let menu: MenuSheet + @EnvironmentObject var theme: Theme + @Environment(\.dismiss) var dismiss + + var body: some View { + let p = theme.palette + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 14) { + if let s = menu.song { CoverThumb(song: s, size: 52, radius: 12) } + VStack(alignment: .leading, spacing: 2) { + Text(menu.title).font(.system(size: 18, weight: .semibold)).foregroundColor(p.cOnSurface).lineLimit(2) + if !menu.subtitle.isEmpty { + Text(menu.subtitle).font(.system(size: 14)).foregroundColor(p.cOnSurfaceVar).lineLimit(2) + } + } + } + .padding(.horizontal, 24) + .padding(.top, 24) + .padding(.bottom, 12) + ScrollView { + VStack(spacing: 0) { + ForEach(menu.items) { it in + Button { + dismiss() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { it.action() } + } label: { + HStack(spacing: 18) { + Image(systemName: it.icon).frame(width: 24) + Text(it.title).font(.system(size: 16)) + Spacer() + } + .foregroundColor(it.destructive ? Color(rgb: p.error) : p.cOnSurface) + .padding(.horizontal, 24) + .padding(.vertical, 14) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + } + } + .presentationDetents([.medium, .large]) + .presentationDragIndicator(.visible) + .presentationBackground(p.cSurfaceLow) + .presentationCornerRadius(28) + } +} diff --git a/App/UI/SettingsView.swift b/App/UI/SettingsView.swift new file mode 100644 index 0000000..e683fbe --- /dev/null +++ b/App/UI/SettingsView.swift @@ -0,0 +1,240 @@ +import SwiftUI + +struct SettingsView: View { + @EnvironmentObject var theme: Theme + @EnvironmentObject var prefs: Prefs + @EnvironmentObject var lib: Library + @EnvironmentObject var ui: UIState + @EnvironmentObject var scrobbler: Scrobbler + @State private var cacheSize: Int64 = 0 + @State private var showEQ = false + @State private var lbToken = "" + @State private var askLB = false + @State private var fetching = false + + var body: some View { + let p = theme.palette + ScrollView { + VStack(alignment: .leading, spacing: 0) { + Text("Settings").font(.system(size: 34, weight: .bold)).foregroundColor(p.cOnSurface) + .padding(.horizontal, 20).padding(.top, 8) + + SectionLabel(text: "Appearance") + Card { + MenuRow(icon: "paintpalette", title: "Colours", value: colourLabel, options: [ + ("From album art", "album"), ("Custom colour", "custom"), ("Mulberry purple", "system")], selection: $prefs.colorSource) + if prefs.colorSource == "custom" { + ColorPicker(selection: Binding(get: { Color(rgb: UInt32(truncatingIfNeeded: prefs.customColor)) }, + set: { prefs.customColor = Int($0.rgb) }), supportsOpacity: false) { + RowLabel(icon: "eyedropper", title: "Pick colour", sub: nil) + } + .padding(.trailing, 16) + } + MenuRow(icon: "circle.lefthalf.filled", title: "Theme", value: ["system": "Follow system", "dark": "Dark", "light": "Light"][prefs.themeMode] ?? "", + options: [("Follow system", "system"), ("Dark", "dark"), ("Light", "light")], selection: $prefs.themeMode) + ToggleRow(icon: "waveform", title: "Visualizer", sub: "Spectrum bars around the cover (from the audio itself, no microphone needed)", on: $prefs.visualizer) + ToggleRow(icon: "sparkle", title: "Floating bass shape", sub: "A shape at the bottom-left that morphs, spins and pulses with the beat", on: $prefs.bassShape) + MenuRow(icon: "rectangle.3.group", title: "Widget animation", value: widgetLabel, + options: [("Off", "0"), ("Battery saver — 5 fps", "5"), ("Balanced — 15 fps", "15"), ("Smooth — 30 fps", "30")], + selection: Binding(get: { String(prefs.widgetAnim) }, set: { prefs.widgetAnim = Int($0) ?? 15; Player.shared.publishWidget() })) + ToggleRow(icon: "leaf", title: "Low-power mode", sub: "Fewer animations, no visualizer, 30 fps", on: $prefs.lowPower) + } + + SectionLabel(text: "Playback") + Card { + MenuRow(icon: "slider.horizontal.below.rectangle", title: "Crossfade", value: prefs.crossfade == 0 ? "Off" : "\(prefs.crossfade) seconds — songs blend into each other", + options: [("Off", "0"), ("2 seconds", "2"), ("3 seconds", "3"), ("5 seconds", "5"), ("8 seconds", "8"), ("12 seconds", "12")], + selection: Binding(get: { String(prefs.crossfade) }, set: { prefs.crossfade = Int($0) ?? 0 })) + ToggleRow(icon: "waveform.path", title: "Fade on play / pause", sub: "A short, smooth volume fade instead of a hard stop", on: $prefs.fadePause) + ToggleRow(icon: "arrow.right.to.line", title: "Gapless playback", + sub: prefs.crossfade > 0 ? "Crossfade is on, so it takes over between songs" : "No silence between tracks of an album", on: $prefs.gapless) + ToggleRow(icon: "clock.arrow.circlepath", title: "Remember position", sub: "Resume the last song where you left off", on: $prefs.resume) + ToggleRow(icon: "headphones", title: "Pause when headphones disconnect", sub: nil, on: $prefs.pauseOnDetach) + ToggleRow(icon: "speaker.wave.2", title: "ReplayGain", sub: "Even out loudness using the tags in your files", on: $prefs.replayGain) + MenuRow(icon: "music.note", title: "Hide short clips", value: prefs.minDuration == 0 ? "Off" : "Shorter than \(prefs.minDuration) s", + options: [("Off", "0"), ("10 s", "10"), ("20 s", "20"), ("30 s", "30"), ("60 s", "60")], + selection: Binding(get: { String(prefs.minDuration) }, set: { prefs.minDuration = Int($0) ?? 0; lib.scan() })) + ButtonRow(icon: "slider.vertical.3", title: "Equalizer", sub: prefs.eqOn ? "On" : "Off") { showEQ = true } + } + + SectionLabel(text: "Lyrics & covers") + Card { + MenuRow(icon: "text.quote", title: "Lyrics source", value: lyricsLabel, + options: [("Auto — synced first, local last", "auto"), ("Local .lrc / embedded", "local"), ("LRCLIB", "lrclib"), + ("NetEase", "netease"), ("Off", "off")], selection: $prefs.lyricsSource) + ToggleRow(icon: "text.alignleft", title: "Plain lyrics", sub: "Show lyrics as text without timing", on: $prefs.lyricsPlain) + ToggleRow(icon: "icloud.and.arrow.down", title: "Fetch lyrics online", sub: "LRCLIB and NetEase", on: $prefs.onlineLyrics) + ToggleRow(icon: "photo", title: "Fetch missing covers", sub: "iTunes, Deezer and Last.fm", on: $prefs.onlineCovers) + ButtonRow(icon: "photo.stack", title: "Fetch covers for the whole library", sub: fetching ? "Working…" : "Saves them in the cover cache") { fetchAllCovers() } + ButtonRow(icon: "trash", title: "Clear lyrics & cover cache", sub: ByteCountFormatter.string(fromByteCount: cacheSize, countStyle: .file)) { + Covers.clearCache(); Lyrics.clearAllCache(); cacheSize = Covers.cacheSize(); ui.show("Cache cleared") + } + } + + SectionLabel(text: "Library") + Card { + RowLabel(icon: "folder", title: "Music folder", sub: "Files › On My iPhone › Mulberry — put music in Music, playlists in Playlists, .lrc files next to songs or in Lyrics") + ButtonRow(icon: "arrow.clockwise", title: "Rescan library", sub: lib.scanning ? "Scanning… \(lib.scanned)" : "\(lib.songs.count) songs") { + lib.scan(force: true); ui.show("Rescanning…") + } + ButtonRow(icon: "folder.badge.gearshape", title: "Open in Files", sub: nil) { + if let u = URL(string: "shareddocuments://" + Library.root.path) { UIApplication.shared.open(u) } + } + } + + SectionLabel(text: "Last.fm") + Card { + RowLabel(icon: "person.icloud", title: scrobbler.lfmOn ? "Signed in as \(prefs.lfmUser)" : "Not signed in", + sub: scrobbler.lfmOn ? (scrobbler.pending.isEmpty ? "Scrobbling directly from Mulberry" : "\(scrobbler.pending.count) scrobbles waiting to be sent") : "Sign in to scrobble directly from Mulberry") + if scrobbler.lfmOn { + ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Scrobble", sub: nil, on: $prefs.lfmEnabled) + ButtonRow(icon: "rectangle.portrait.and.arrow.right", title: "Sign out", sub: nil) { scrobbler.logout() } + } else { + ButtonRow(icon: "person.badge.key", title: "Sign in to Last.fm", sub: nil) { scrobbler.login() } + } + } + + SectionLabel(text: "ListenBrainz") + Card { + ButtonRow(icon: "key", title: prefs.lbToken.isEmpty ? "Add user token" : "Token saved", + sub: "Find it at listenbrainz.org › Settings") { lbToken = prefs.lbToken; askLB = true } + } + + SectionLabel(text: "About") + Card { + RowLabel(icon: "info.circle", title: "Mulberry for iOS \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")", + sub: "Coded by Claude (Anthropic) · MIT licence") + ButtonRow(icon: "desktopcomputer", title: "Mulberry for desktop", sub: "archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry") { + if let u = URL(string: "https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry") { UIApplication.shared.open(u) } + } + } + } + .padding(.bottom, 24) + } + .surface(p) + .tint(p.cPrimary) + .onAppear { cacheSize = Covers.cacheSize() } + .sheet(isPresented: $showEQ) { EqualizerSheet().environmentObjects() } + .alert("ListenBrainz token", isPresented: $askLB) { + TextField("User token", text: $lbToken) + Button("Save") { prefs.lbToken = lbToken.trimmingCharacters(in: .whitespaces) } + Button("Remove", role: .destructive) { prefs.lbToken = "" } + Button("Cancel", role: .cancel) {} + } + .onChange(of: prefs.visualizer) { _ in } + } + + private var colourLabel: String { + ["album": "From album art", "custom": "Custom colour", "system": "Mulberry purple"][prefs.colorSource] ?? "" + } + + private var widgetLabel: String { + switch prefs.widgetAnim { + case 0: return "Off" + case 5: return "Battery saver — 5 fps" + case 30: return "Smooth — 30 fps" + default: return "Balanced — 15 fps" + } + } + + private var lyricsLabel: String { + ["auto": "Auto — synced first, local last", "local": "Local .lrc / embedded", "lrclib": "LRCLIB", + "netease": "NetEase", "off": "Off"][prefs.lyricsSource] ?? "" + } + + private func fetchAllCovers() { + guard !fetching else { return } + fetching = true + let albums = lib.albums.compactMap { $0.songs.first } + Task.detached(priority: .utility) { + var n = 0 + for s in albums where Covers.localData(s) == nil { + if let d = Covers.best(artist: s.groupArtist, album: s.album, title: s.displayTitle) { + try? d.write(to: Covers.onlineFile(s)); Covers.forget(s); n += 1 + } + } + let found = n + await MainActor.run { fetching = false; UIState.shared.show("Found \(found) covers") } + } + } +} + +struct RowLabel: View { + let icon: String + let title: String + let sub: String? + @EnvironmentObject var theme: Theme + + var body: some View { + let p = theme.palette + HStack(alignment: .center, spacing: 18) { + Image(systemName: icon).font(.system(size: 18)).foregroundColor(p.cOnSurfaceVar).frame(width: 26) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.system(size: 16)).foregroundColor(p.cOnSurface) + if let sub, !sub.isEmpty { Text(sub).font(.system(size: 13)).foregroundColor(p.cOnSurfaceVar) } + } + Spacer(minLength: 0) + } + .padding(.horizontal, 18) + .padding(.vertical, 13) + .contentShape(Rectangle()) + } +} + +struct ToggleRow: View { + let icon: String + let title: String + let sub: String? + @Binding var on: Bool + @EnvironmentObject var theme: Theme + + var body: some View { + HStack { + RowLabel(icon: icon, title: title, sub: sub) + Toggle("", isOn: $on).labelsHidden().tint(theme.palette.cPrimary).padding(.trailing, 18) + } + .onTapGesture { on.toggle() } + } +} + +struct ButtonRow: View { + let icon: String + let title: String + let sub: String? + let action: () -> Void + + var body: some View { + Button(action: action) { RowLabel(icon: icon, title: title, sub: sub) }.buttonStyle(.plain) + } +} + +struct MenuRow: View { + let icon: String + let title: String + let value: String + let options: [(String, String)] + @Binding var selection: String + + var body: some View { + Menu { + ForEach(options, id: \.1) { o in + Button { selection = o.1 } label: { + if selection == o.1 { Label(o.0, systemImage: "checkmark") } else { Text(o.0) } + } + } + } label: { + RowLabel(icon: icon, title: title, sub: value) + } + .buttonStyle(.plain) + } +} + +extension Color { + /// 0xRRGGBB of a SwiftUI colour. + var rgb: UInt32 { + var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 + UIColor(self).getRed(&r, green: &g, blue: &b, alpha: &a) + func c(_ v: CGFloat) -> UInt32 { UInt32(max(0, min(255, (v * 255).rounded()))) } + return c(r) << 16 | c(g) << 8 | c(b) + } +} diff --git a/App/UI/Visuals.swift b/App/UI/Visuals.swift new file mode 100644 index 0000000..9c3e0ef --- /dev/null +++ b/App/UI/Visuals.swift @@ -0,0 +1,248 @@ +import SwiftUI + +/// Per-frame clock shared by the animated views (Android Ticker). Returns dt in seconds, clamped. +final class FrameClock { + private var last: Date? + func step(_ now: Date) -> Float { + defer { last = now } + guard let last else { return 1 / 60 } + return Float(min(0.1, max(0, now.timeIntervalSince(last)))) + } +} + +var animFPS: Double { Prefs.shared.lowPower ? 30 : 60 } + +// MARK: Cookie cover with spectrum bars (CookieView.java) + +final class CookieModel { + var spin: Float = 0, rot: Float = 0, appear: Float = 1, pulse: Float = 0, bass: Float = 0 + var lv = [Float](repeating: 0, count: 48) + var target = [Float](repeating: 0, count: 48) + var coverID: ObjectIdentifier? + let clock = FrameClock() + + func frame(_ now: Date, playing: Bool, bars: Bool, spectrum: Spectrum?) { + let f = clock.step(now) + spin += ((playing && !Prefs.shared.lowPower ? 1 : 0) - spin) * min(1, 2.5 * f) + rot += spin * f * 0.22 + if appear < 1 { appear = min(1, appear + 2.8 * f) } + let have = bars && playing && (spectrum?.levels(&target) ?? false) + var b: Float = 0 + for i in lv.indices { + let t = have ? target[i] : 0 + let k: Float = t > lv[i] ? 0.55 : 0.16 + lv[i] += (t - lv[i]) * min(1, k * f * 60) + if i < 4 { b += lv[i] } + } + bass = b / 4 + pulse += ((have ? 1.8 * max(0, bass - 0.45) : 0) - pulse) * min(1, 14 * f) + } + + var busy: Bool { spin > 0.01 || appear < 1 || pulse > 0.01 } +} + +struct CookieView: View { + var image: UIImage? + var playing: Bool + var small = false + @EnvironmentObject var theme: Theme + @EnvironmentObject var prefs: Prefs + @State private var model = CookieModel() + + var body: some View { + let bars = prefs.visualizer && !prefs.lowPower + TimelineView(.animation(minimumInterval: 1 / animFPS, paused: !(playing || model.busy))) { tl in + Canvas { ctx, size in + model.frame(tl.date, playing: playing, bars: bars, spectrum: Player.shared.spectrum) + draw(&ctx, size, bars: bars) + } + } + .aspectRatio(1, contentMode: .fit) + .onChange(of: image.map(ObjectIdentifier.init)) { _ in model.appear = 0 } + } + + private func draw(_ ctx: inout GraphicsContext, _ size: CGSize, bars: Bool) { + let p = theme.palette + let m = min(size.width, size.height) + let c = CGPoint(x: size.width / 2, y: size.height / 2) + let full = m / 2 - 2 + let base = (bars ? 0.72 : 0.97) * full + let depth: CGFloat = bars ? 0.06 : 0.045 + let a = CGFloat(model.appear) + let r = (0.9 + 0.1 * (1 - (1 - a) * (1 - a))) * (1 + 0.045 * CGFloat(model.pulse)) * base + if bars { + Shapes.drawBars(&ctx, center: c, radius: r, depth: depth, rotation: Double(model.rot), + length: full - base * 1.06 - full * 0.04, levels: model.lv, count: small ? 44 : 72, + color: p.primary, width: small ? max(1.6, m / 50) : max(2.6, m / 85)) + } + let path = Shapes.cookie(center: c, radius: r, depth: depth, rotation: Double(model.rot)) + if let image { + var clipped = ctx + clipped.clip(to: path) + let iw = image.size.width, ih = image.size.height + let s = 2 * r / min(iw, ih) + clipped.draw(Image(uiImage: image), in: CGRect(x: c.x - iw * s / 2, y: c.y - ih * s / 2, width: iw * s, height: ih * s)) + } else { + ctx.fill(path, with: .color(p.cPrimaryC)) + let icon = ctx.resolve(Image(systemName: "opticaldisc.fill")) + ctx.draw(icon.shading(.color(p.cOnPrimaryC)) as GraphicsContext.ResolvedImage, + in: CGRect(x: c.x - r * 0.4, y: c.y - r * 0.4, width: r * 0.8, height: r * 0.8)) + } + } +} + +extension GraphicsContext.ResolvedImage { + func shading(_ s: GraphicsContext.Shading) -> GraphicsContext.ResolvedImage { + var copy = self + copy.shading = s + return copy + } +} + +// MARK: Wavy seek bar (WavySeekBar.java) + +final class WavyModel { + var amp: Float = 0, phase: Float = 0 + var value: Double = 0 + var target: Double = -1 + let clock = FrameClock() +} + +struct WavySeekBar: View { + var position: Double + var duration: Double + var playing: Bool + var height: CGFloat = 40 + var onDrag: (Double?) -> Void = { _ in } + var onSeek: (Double) -> Void + @EnvironmentObject var theme: Theme + @State private var model = WavyModel() + @State private var drag: Double? + + var body: some View { + GeometryReader { geo in + TimelineView(.animation(minimumInterval: 1 / animFPS, paused: !(playing || model.amp > 0.01))) { tl in + Canvas { ctx, size in + step(tl.date) + let p = theme.palette + let pad: CGFloat = 10 + Shapes.drawWavy(&ctx, x0: pad, x1: size.width - pad, y: size.height / 2, + frac: CGFloat(drag ?? model.value), amp: CGFloat(model.amp), phase: CGFloat(model.phase), + stroke: 4.5, wavelength: 36, height: 3.6, active: p.cPrimary, + inactive: p.cSecondaryC, thumb: true, + thumbHeight: min(size.height - 2, drag != nil ? 26 : 20)) + } + } + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { g in + let f = frac(g.location.x, geo.size.width) + drag = f + onDrag(f * duration) + } + .onEnded { g in + let f = frac(g.location.x, geo.size.width) + drag = nil + model.value = f + model.target = -1 + onDrag(nil) + onSeek(f * duration) + }) + } + .frame(height: height) + .onChange(of: position) { _ in sync() } + .onAppear { model.value = duration > 0 ? position / duration : 0 } + } + + private func frac(_ x: CGFloat, _ w: CGFloat) -> Double { + Double(max(0, min(1, (x - 10) / max(1, w - 20)))) + } + + private func sync() { + guard drag == nil else { return } + let f = duration > 0 ? max(0, min(1, position / duration)) : 0 + if playing && abs(f - model.value) * max(1, duration) <= 0.9 { model.target = f } else { model.value = f; model.target = -1 } + } + + private func step(_ now: Date) { + let f = model.clock.step(now) + model.amp += ((playing ? 1 : 0) - model.amp) * min(1, 7 * f) + model.phase = (model.phase + 6.6 * f).truncatingRemainder(dividingBy: 2 * .pi) + if playing && duration > 0 && drag == nil { + model.value = min(1, model.value + Double(f) / duration) + if model.target >= 0 { + model.value += Double(min(1, 3 * f)) * (model.target - model.value) + if abs(model.target - model.value) < 1e-5 { model.target = -1 } + } + } + } +} + +// MARK: Morphing play button (PlayButton.java) + +struct PlayButton: View { + var playing: Bool + var tonal = false + var action: () -> Void + @EnvironmentObject var theme: Theme + @State private var pressed = false + + var body: some View { + let p = theme.palette + GeometryReader { g in + let w = g.size.width, h = g.size.height + let press: CGFloat = pressed ? 1 : 0 + let morph: CGFloat = playing ? 1 : 0 + let sc = 1 - 0.08 * press + let bw = w * sc * (1 - 0.12 * morph), bh = h * sc + let radius = bh / 2 + (bh * 0.3 - bh / 2) * morph + ZStack { + RoundedRectangle(cornerRadius: radius, style: .continuous) + .fill(tonal ? p.cSecondaryC : p.cPrimary) + .frame(width: bw, height: bh) + Image(systemName: "play.fill") + .resizable().scaledToFit() + .frame(width: bh * 0.4, height: bh * 0.4) + .scaleEffect(0.7 + 0.3 * (1 - morph)) + .opacity(1 - morph) + Image(systemName: "pause.fill") + .resizable().scaledToFit() + .frame(width: bh * 0.4, height: bh * 0.4) + .scaleEffect(0.7 + 0.3 * morph) + .opacity(morph) + } + .foregroundColor(tonal ? p.cOnSecondaryC : p.cOnPrimary) + .frame(width: w, height: h) + .animation(.spring(response: 0.32, dampingFraction: 0.72), value: playing) + .animation(.easeOut(duration: 0.12), value: pressed) + } + .contentShape(Rectangle()) + .simultaneousGesture(DragGesture(minimumDistance: 0).onChanged { _ in pressed = true }.onEnded { _ in pressed = false }) + .onTapGesture { UIImpactFeedbackGenerator(style: .light).impactOccurred(); action() } + .accessibilityLabel(playing ? "Pause" : "Play") + .accessibilityAddTraits(.isButton) + } +} + +// MARK: Floating bass shape (BassShapeView.java) + +struct BassShapeView: View { + var playing: Bool + @EnvironmentObject var theme: Theme + @State private var anim = Shapes.Animator() + @State private var clock = FrameClock() + + var body: some View { + TimelineView(.animation(minimumInterval: 1 / animFPS, paused: !(playing || !anim.settled))) { tl in + Canvas { ctx, size in + anim.playing = playing + let dt = clock.step(tl.date) + anim.step(dt, bass: playing ? Player.shared.spectrum.bass() : -1) + let p = theme.palette + let c = CGPoint(x: size.width / 2, y: size.height / 2) + anim.draw(&ctx, center: c, radius: min(c.x, c.y) * 0.86, fill: Color(rgb: p.primaryContainer, alpha: 0.94), + innerFill: p.cPrimary, stroke: p.primary) + } + } + } +} diff --git a/Resources/AppIcon60x60@2x.png b/Resources/AppIcon60x60@2x.png new file mode 100644 index 0000000..c858bcf Binary files /dev/null and b/Resources/AppIcon60x60@2x.png differ diff --git a/Resources/AppIcon60x60@3x.png b/Resources/AppIcon60x60@3x.png new file mode 100644 index 0000000..0a024bd Binary files /dev/null and b/Resources/AppIcon60x60@3x.png differ diff --git a/Resources/AppIcon76x76@2x~ipad.png b/Resources/AppIcon76x76@2x~ipad.png new file mode 100644 index 0000000..74cc022 Binary files /dev/null and b/Resources/AppIcon76x76@2x~ipad.png differ diff --git a/Resources/Info.plist b/Resources/Info.plist new file mode 100644 index 0000000..db9ee08 --- /dev/null +++ b/Resources/Info.plist @@ -0,0 +1,74 @@ + + + + + CFBundleDevelopmentRegionen + CFBundleDisplayNameMulberry + CFBundleExecutableMulberry + CFBundleIdentifiercom.mulberry.player + CFBundleInfoDictionaryVersion6.0 + CFBundleNameMulberry + CFBundlePackageTypeAPPL + CFBundleShortVersionString@VERSION@ + CFBundleVersion@BUILD@ + CFBundleSupportedPlatformsiPhoneOS + DTPlatformNameiphoneos + DTPlatformVersion18.6 + DTSDKNameiphoneos18.6 + MinimumOSVersion17.0 + LSRequiresIPhoneOS + UIDeviceFamily12 + UIRequiredDeviceCapabilitiesarm64 + UIBackgroundModesaudio + UIFileSharingEnabled + LSSupportsOpeningDocumentsInPlace + UILaunchScreenUIColorName + UIStatusBarStyleUIStatusBarStyleDefault + UISupportedInterfaceOrientationsUIInterfaceOrientationPortrait + UISupportedInterfaceOrientations~ipad + UIInterfaceOrientationPortraitUIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeftUIInterfaceOrientationLandscapeRight + + UIApplicationSceneManifestUIApplicationSupportsMultipleScenes + CFBundleIcons + CFBundlePrimaryIcon + CFBundleIconFilesAppIcon60x60 + CFBundleIconNameAppIcon + + + CFBundleIcons~ipad + CFBundlePrimaryIcon + CFBundleIconFilesAppIcon60x60AppIcon76x76 + + + CFBundleURLTypes + CFBundleURLNamecom.mulberry.player + CFBundleURLSchemesmulberry + + CFBundleDocumentTypes + + CFBundleTypeNameAudio + CFBundleTypeRoleViewer + LSHandlerRankAlternate + LSItemContentTypespublic.audio + + + CFBundleTypeNamePlaylist + CFBundleTypeRoleViewer + LSHandlerRankAlternate + LSItemContentTypespublic.m3u-playlistcom.mulberry.playlist + + + UTImportedTypeDeclarations + UTTypeIdentifiercom.mulberry.playlist + UTTypeDescriptionPlaylist + UTTypeConformsTopublic.data + UTTypeTagSpecification + public.filename-extension + plsxspfwplasxm3u8 + + + + NSAppTransportSecurityNSAllowsArbitraryLoads + + diff --git a/Resources/Widget-Info.plist b/Resources/Widget-Info.plist new file mode 100644 index 0000000..f5e9bc6 --- /dev/null +++ b/Resources/Widget-Info.plist @@ -0,0 +1,23 @@ + + + + + CFBundleDevelopmentRegionen + CFBundleDisplayNameMulberry + CFBundleExecutableMulberryWidgets + CFBundleIdentifiercom.mulberry.player.widgets + CFBundleInfoDictionaryVersion6.0 + CFBundleNameMulberryWidgets + CFBundlePackageTypeXPC! + CFBundleShortVersionString@VERSION@ + CFBundleVersion@BUILD@ + CFBundleSupportedPlatformsiPhoneOS + DTPlatformNameiphoneos + DTSDKNameiphoneos18.6 + MinimumOSVersion17.0 + UIDeviceFamily12 + NSExtension + NSExtensionPointIdentifiercom.apple.widgetkit-extension + + + diff --git a/Resources/icon-1024.png b/Resources/icon-1024.png new file mode 100644 index 0000000..98662fd Binary files /dev/null and b/Resources/icon-1024.png differ diff --git a/Shared/Palette.swift b/Shared/Palette.swift new file mode 100644 index 0000000..19dd54a --- /dev/null +++ b/Shared/Palette.swift @@ -0,0 +1,189 @@ +import SwiftUI + +/// Material You palette built in OKLCH, ported 1:1 from the Android app's Palette.java. +struct Palette: Equatable { + var dark = true + var seed: UInt32 = 0 + var primary: UInt32 = 0 + var onPrimary: UInt32 = 0 + var primaryContainer: UInt32 = 0 + var onPrimaryContainer: UInt32 = 0 + var secondary: UInt32 = 0 + var secondaryContainer: UInt32 = 0 + var onSecondaryContainer: UInt32 = 0 + var tertiary: UInt32 = 0 + var tertiaryContainer: UInt32 = 0 + var surface: UInt32 = 0 + var surfaceLow: UInt32 = 0 + var surfaceContainer: UInt32 = 0 + var surfaceHigh: UInt32 = 0 + var surfaceHighest: UInt32 = 0 + var onSurface: UInt32 = 0 + var onSurfaceVariant: UInt32 = 0 + var outline: UInt32 = 0 + var outlineVariant: UInt32 = 0 + var error: UInt32 = 0 + + /// Android's default seed (-6651951 as ARGB). + static let defaultSeed: UInt32 = 0x9A7FD1 + + static func fromSeed(_ rgb: UInt32, dark: Bool) -> Palette { + let lch = rgbToOklch(rgb) + let h = lch.2 + let t1 = Tonal(h: h, c: min(max(lch.1, 0.085), 0.15)) + let t2 = Tonal(h: h, c: 0.04) + let t3 = Tonal(h: (60 + h).truncatingRemainder(dividingBy: 360), c: 0.075) + let t4 = Tonal(h: h, c: 0.014) + let t5 = Tonal(h: h, c: 0.025) + var p = Palette() + p.dark = dark + p.seed = rgb + if dark { + p.primary = t1.t(80); p.onPrimary = t1.t(20) + p.primaryContainer = t1.t(30); p.onPrimaryContainer = t1.t(90) + p.secondary = t2.t(80); p.secondaryContainer = t2.t(30); p.onSecondaryContainer = t2.t(90) + p.tertiary = t3.t(80); p.tertiaryContainer = t3.t(30) + p.surface = t4.t(6); p.surfaceLow = t4.t(10); p.surfaceContainer = t4.t(12) + p.surfaceHigh = t4.t(17); p.surfaceHighest = t4.t(22) + p.onSurface = t4.t(90); p.onSurfaceVariant = t5.t(80) + p.outline = t5.t(60); p.outlineVariant = t5.t(30) + p.error = 0xF2B8B5 + } else { + p.primary = t1.t(40); p.onPrimary = t1.t(100) + p.primaryContainer = t1.t(90); p.onPrimaryContainer = t1.t(10) + p.secondary = t2.t(40); p.secondaryContainer = t2.t(90); p.onSecondaryContainer = t2.t(10) + p.tertiary = t3.t(40); p.tertiaryContainer = t3.t(90) + p.surface = t4.t(98); p.surfaceLow = t4.t(96); p.surfaceContainer = t4.t(94) + p.surfaceHigh = t4.t(92); p.surfaceHighest = t4.t(90) + p.onSurface = t4.t(10); p.onSurfaceVariant = t5.t(30) + p.outline = t5.t(50); p.outlineVariant = t5.t(80) + p.error = 0xB3261E + } + return p + } + + struct Tonal { + let h: Double + let c: Double + func t(_ tone: Double) -> UInt32 { oklchToRgb(toneToL(tone), c, h) } + } + + static func toneToL(_ d: Double) -> Double { + d <= 8 ? cbrt(d / 903.2963) : (16 + d) / 116 + } + + static func lin(_ d: Double) -> Double { d <= 0.04045 ? d / 12.92 : pow((0.055 + d) / 1.055, 2.4) } + static func delin(_ d: Double) -> Double { d <= 0.0031308 ? 12.92 * d : 1.055 * pow(d, 1 / 2.4) - 0.055 } + + static func rgbToOklch(_ rgb: UInt32) -> (Double, Double, Double) { + let r = lin(Double((rgb >> 16) & 0xFF) / 255) + let g = lin(Double((rgb >> 8) & 0xFF) / 255) + let b = lin(Double(rgb & 0xFF) / 255) + let l = cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b) + let m = cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b) + let s = cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b) + let L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s + let A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s + let B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s + let h = (atan2(B, A) * 180 / .pi + 360).truncatingRemainder(dividingBy: 360) + return (L, hypot(A, B), h) + } + + static func toLin(_ L: Double, _ C: Double, _ H: Double) -> (Double, Double, Double) { + let a = cos(H * .pi / 180) * C + let b = sin(H * .pi / 180) * C + let l = pow(L + 0.3963377774 * a + 0.2158037573 * b, 3) + let m = pow(L - 0.1055613458 * a - 0.0638541728 * b, 3) + let s = pow(L - 0.0894841775 * a - 1.291485548 * b, 3) + return (4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, + -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, + -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s) + } + + static func inGamut(_ v: (Double, Double, Double)) -> Bool { + let lo = -1e-4, hi = 1.0001 + return v.0 >= lo && v.0 <= hi && v.1 >= lo && v.1 <= hi && v.2 >= lo && v.2 <= hi + } + + static func oklchToRgb(_ L: Double, _ C: Double, _ H: Double) -> UInt32 { + var v = toLin(L, C, H) + if !inGamut(v) { + var lo = 0.0, hi = C + for _ in 0..<18 { + let mid = (lo + hi) / 2 + if inGamut(toLin(L, mid, H)) { lo = mid } else { hi = mid } + } + v = toLin(L, lo, H) + } + func ch(_ x: Double) -> UInt32 { + UInt32(max(0, min(255, (delin(max(0, min(1, x))) * 255).rounded()))) + } + return (ch(v.0) << 16) | (ch(v.1) << 8) | ch(v.2) + } + + static func mix(_ a: UInt32, _ b: UInt32, _ f: Double) -> UInt32 { + func c(_ x: UInt32, _ s: UInt32) -> Double { Double((x >> s) & 0xFF) } + func m(_ s: UInt32) -> UInt32 { UInt32((c(a, s) + (c(b, s) - c(a, s)) * f).rounded()) << s } + return m(16) | m(8) | m(0) + } + + /// Dominant colour of an image (32x32 OKLCH hue histogram), as in Palette.dominant(). + static func dominant(_ image: CGImage?) -> UInt32? { + guard let image else { return nil } + let n = 32 + var px = [UInt8](repeating: 0, count: n * n * 4) + guard let ctx = CGContext(data: &px, width: n, height: n, bitsPerComponent: 8, bytesPerRow: n * 4, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } + ctx.interpolationQuality = .medium + ctx.draw(image, in: CGRect(x: 0, y: 0, width: n, height: n)) + var w = [Double](repeating: 0, count: 24), cx = w, sx = w, cc = w + for i in 0..<(n * n) { + let rgb = (UInt32(px[i * 4]) << 16) | (UInt32(px[i * 4 + 1]) << 8) | UInt32(px[i * 4 + 2]) + let (L, C, H) = rgbToOklch(rgb) + guard C >= 0.03, L >= 0.2, L <= 0.95 else { continue } + let bin = Int(H / 15) % 24 + let wt = C * C + w[bin] += wt + cx[bin] += cos(H * .pi / 180) * wt + sx[bin] += sin(H * .pi / 180) * wt + cc[bin] += wt * C + } + var best = -1 + for i in 0..<24 where w[i] > 0 && (best < 0 || w[i] > w[best]) { best = i } + guard best >= 0 else { return nil } + let hue = (atan2(sx[best], cx[best]) * 180 / .pi + 360).truncatingRemainder(dividingBy: 360) + return oklchToRgb(0.65, max(cc[best] / w[best], 0.1), hue) + } +} + +extension Color { + init(rgb: UInt32, alpha: Double = 1) { + self.init(.sRGB, + red: Double((rgb >> 16) & 0xFF) / 255, + green: Double((rgb >> 8) & 0xFF) / 255, + blue: Double(rgb & 0xFF) / 255, + opacity: alpha) + } +} + +/// SwiftUI-friendly accessors. +extension Palette { + var cPrimary: Color { Color(rgb: primary) } + var cOnPrimary: Color { Color(rgb: onPrimary) } + var cPrimaryC: Color { Color(rgb: primaryContainer) } + var cOnPrimaryC: Color { Color(rgb: onPrimaryContainer) } + var cSecondary: Color { Color(rgb: secondary) } + var cSecondaryC: Color { Color(rgb: secondaryContainer) } + var cOnSecondaryC: Color { Color(rgb: onSecondaryContainer) } + var cTertiary: Color { Color(rgb: tertiary) } + var cSurface: Color { Color(rgb: surface) } + var cSurfaceLow: Color { Color(rgb: surfaceLow) } + var cSurfaceC: Color { Color(rgb: surfaceContainer) } + var cSurfaceHigh: Color { Color(rgb: surfaceHigh) } + var cSurfaceHighest: Color { Color(rgb: surfaceHighest) } + var cOnSurface: Color { Color(rgb: onSurface) } + var cOnSurfaceVar: Color { Color(rgb: onSurfaceVariant) } + var cOutline: Color { Color(rgb: outline) } + var cOutlineVar: Color { Color(rgb: outlineVariant) } +} diff --git a/Shared/Shapes.swift b/Shared/Shapes.swift new file mode 100644 index 0000000..44132e9 --- /dev/null +++ b/Shared/Shapes.swift @@ -0,0 +1,270 @@ +import SwiftUI + +/// Morphing shapes and the cookie/bars/wavy drawing helpers, ported from Shapes.java and Draw.java. +enum Shapes { + static let n = 120 + static let names = ["circle", "cookie4", "cookie6", "cookie7", "cookie9", "cookie12", "clover4", "clover8", + "sunny", "burst", "softburst", "star5", "star4", "triangle", "square", "pentagon", + "hexagon", "gem", "pill", "flower", "puffy", "bean", "arch"] + + static let all: [[Float]] = names.map { name in + var r = (0.. Double { + var x = (d / (2 * .pi)).truncatingRemainder(dividingBy: 1) + if x < 0 { x += 1 } + return 1 - abs(x * 2 - 1) + } + + static func poly(_ k: Int, _ d: Double, _ round: Double) -> Double { + let seg = 2 * .pi / Double(k) + let m = ((d.truncatingRemainder(dividingBy: seg)) + seg).truncatingRemainder(dividingBy: seg) + return cos(.pi / Double(k)) / cos(m - seg / 2) * (1 - round) + cos(.pi / Double(k)) * round * 1.04 + } + + static func radius(_ name: String, _ d: Double) -> Double { + switch name { + case "cookie4": return 0.9 + cos(4 * d) * 0.1 + case "cookie6": return 0.92 + 0.08 * cos(6 * d) + case "cookie7": return 0.925 + 0.075 * cos(7 * d) + case "cookie9": return 0.94 + 0.06 * cos(9 * d) + case "cookie12": return 0.955 + 0.045 * cos(12 * d) + case "clover4": return 0.58 + 0.42 * pow(abs(cos(2 * d)), 0.55) + case "clover8": return 0.7 + 0.3 * pow(abs(cos(4 * d)), 0.6) + case "sunny": return 0.84 + 0.16 * cos(8 * d) + case "burst": return 0.72 + 0.28 * tri(12 * d) + case "softburst": return 0.8 + 0.2 * pow(tri(10 * d), 1.6) + case "star5": return pow((1 + cos(5 * d)) / 2, 1.8) * 0.5 + 0.5 + case "star4": return pow((1 + cos(4 * (.pi / 4 + d))) / 2, 2.2) * 0.48 + 0.52 + case "triangle": return poly(3, d - .pi / 2, 0.18) + case "square": return poly(4, d + .pi / 4, 0.16) + case "pentagon": return poly(5, d - .pi / 2, 0.14) + case "hexagon": return poly(6, d, 0.1) + case "gem": return poly(4, d, 0.1) + case "pill": return 1 / sqrt(pow(sin(d) / 0.6, 2) + pow(cos(d), 2)) + case "flower": return 0.55 + 0.45 * abs(cos(3 * d)) + case "puffy": return poly(4, d + .pi / 4, 0.3) * (0.965 + 0.035 * cos(16 * d)) + case "bean": return (1 + sin(d)) * 0.38 / 2 + 0.62 + 0.05 * cos(2 * d) + case "arch": return sin(d) > 0 ? poly(4, d + .pi / 4, 0.25) : 0.92 + default: return 1 + } + } + + static func smooth(_ a: [Float], _ passes: Int) -> [Float] { + var cur = a + for _ in 0.. Path { + var p = Path() + for i in 0...n { + let k = i % n + let a = 2 * .pi * Double(k) / Double(n) + rot + let pt = CGPoint(x: c.x + CGFloat(r[k]) * rad * CGFloat(cos(a)), + y: c.y + CGFloat(r[k]) * rad * CGFloat(sin(a))) + if i == 0 { p.move(to: pt) } else { p.addLine(to: pt) } + } + p.closeSubpath() + return p + } + + /// Nine-lobed "cookie" outline used for covers (Draw.cookie). + static func cookie(center c: CGPoint, radius r: CGFloat, depth: CGFloat, rotation rot: Double) -> Path { + var p = Path() + for i in 0.. x0 { + let a = height * amp + let end = x - gap + let taper = wavelength * 0.42 + var p = Path() + p.move(to: CGPoint(x: x0, y: y)) + let step = max(1, stroke / 2.5) + var cx = x0 + while cx < end { + let nx = min(cx + step, end) + var k = min(1, min((nx - x0) / taper, (end - nx) / taper)) + if k < 0 { k = 0 } + let s = (3 - k * 2) * k * k + let yy = y + s * a * CGFloat(sin(Double((nx - x0) / wavelength * 2) * .pi - Double(phase))) + p.addLine(to: CGPoint(x: nx, y: yy)) + cx = nx + } + ctx.stroke(p, with: .color(active), style: style) + } + if thumb { + let w = 1.25 * stroke + ctx.fill(Path(roundedRect: CGRect(x: x - w / 2, y: y - thumbHeight / 2, width: w, height: thumbHeight), + cornerRadius: w / 2), with: .color(active)) + } + } + + /// Bass-reactive morphing shape (Shapes.Animator). + final class Animator { + var playing = false + private var from = 0, to = 6, innerFrom = 3, innerTo = 11 + private var t: Float = 1, tInner: Float = 1, morphSpeed: Float = 6 + private var rotVel: Float = 0.35, rot: Float = 0, innerRot: Float = 0 + private var energy: Float = 0, avg: Float = 0.2, prev: Float = 0, kick: Float = 0, pulse: Float = 0 + private var sinceBeat: Float = 10, sinceMorph: Float = 0, clock: Float = 0 + private var beatsSinceMorph = 0 + private var histV = [Float](repeating: 0, count: 24), histT = [Float](repeating: 0, count: 24) + private var histPos = 0 + private(set) var cur = [Float](repeating: 1, count: Shapes.n) + private(set) var inner = [Float](repeating: 1, count: Shapes.n) + + private func pick(_ a: Int, _ b: Int) -> Int { + while true { + let i = Int.random(in: 0..= 0 { + energy += (bass - energy) * min(1, 20 * dt) + avg += (bass - avg) * min(1, 0.7 * dt) + let rise = bass - prev + prev = bass + clock += dt + var floor = bass + for i in 0..<24 where clock - histT[i] < 0.2 && histV[i] < floor { floor = histV[i] } + histV[histPos] = bass + histT[histPos] = clock + histPos = (histPos + 1) % 24 + let jumpBy = bass - floor + if bass > 0.3 && jumpBy > 0.05 && rise > 0.025 && sinceBeat > 0.28 { + sinceBeat = 0 + kick = min(1, 2.5 * jumpBy + 0.5) + beatsSinceMorph += 1 + if sinceMorph > 0.8 && (jumpBy > 0.2 || beatsSinceMorph >= 2) { + beatsSinceMorph = 0 + jump(true) + } + } + } else if sinceBeat > 1.8 { + kick = 0.5 + sinceBeat = 0 + jump(true) + } + if sinceMorph > 6 { jump(false) } + } else { + energy += (0 - energy) * min(1, 4 * dt) + if sinceMorph > 8 { jump(false) } + } + kick = max(0, kick - 3.4 * dt) + let target: Float = playing ? 0.15 + energy * 0.45 + kick * 0.55 : 0 + pulse += (target - pulse) * min(1, 16 * dt) + t = min(1, t + morphSpeed * dt) + tInner = min(1, tInner + morphSpeed * dt * 0.8) + rotVel += ((playing ? 0.4 : 0.12) - rotVel) * min(1, 2.5 * dt) + rot += rotVel * dt + innerRot -= (0.6 + kick * 3) * dt + let e1 = Animator.ease(t), e2 = Animator.ease(tInner) + let a = Shapes.all[from], b = Shapes.all[to], c = Shapes.all[innerFrom], d = Shapes.all[innerTo] + for i in 0.. Float { + let x = f - 1 + return 1.7 * x * x + 2.7 * x * x * x + 1 + } + + var settled: Bool { !playing && pulse < 0.01 && t >= 1 && tInner >= 1 && kick <= 0 } + + func draw(_ ctx: inout GraphicsContext, center c: CGPoint, radius r: CGFloat, + fill: Color, innerFill: Color, stroke: UInt32) { + let rr = r * CGFloat(0.74 + 0.26 * pulse) + let outer = Shapes.path(cur, center: c, radius: rr, rotation: Double(rot)) + ctx.fill(outer, with: .color(fill)) + ctx.stroke(outer, with: .color(Color(rgb: stroke, alpha: Double(0.35 + 0.65 * kick))), + lineWidth: max(2, 0.035 * r)) + let ir = rr * CGFloat(0.36 + 0.12 * kick + 0.06 * energy) + ctx.fill(Shapes.path(inner, center: c, radius: ir, rotation: Double(innerRot)), with: .color(innerFill)) + } + } +} + +enum TimeFmt { + static func string(_ seconds: Double) -> String { + let s = max(0, Int(seconds)) + let h = s / 3600, m = (s / 60) % 60, sec = s % 60 + return h > 0 ? String(format: "%d:%02d:%02d", h, m, sec) : String(format: "%d:%02d", m, sec) + } +} diff --git a/Shared/WidgetShared.swift b/Shared/WidgetShared.swift new file mode 100644 index 0000000..f591b8b --- /dev/null +++ b/Shared/WidgetShared.swift @@ -0,0 +1,96 @@ +import Foundation +import AppIntents + +/// What the widget shows; written by the app into the shared app-group container. +struct NowSnapshot: Codable, Equatable { + var title = "" + var artist = "" + var album = "" + var playing = false + var position: Double = 0 + var duration: Double = 0 + var at: Double = 0 // when `position` was sampled (epoch seconds) + var hasArt = false + var artVersion = 0 + var favourite = false + var shuffle = false + var repeatMode = 0 + var palette: [UInt32] = [] // primary, onPrimary, primaryC, onPrimaryC, secondaryC, onSecondaryC, surface, surfaceHigh, onSurface, onSurfaceVar + var dark = true + var lyrics: [Double] = [] // line start times (synced only) + var lyricText: [String] = [] + var plainLyric = "" // first unsynced lines when lyrics aren't timed + var widgetFPS = 15 + + static let group = "group.com.mulberry.player" + static let kind = "MulberryPlayer" + static let lyricsKind = "MulberryLyrics" + static let shapeKind = "MulberryShape" + + static var container: URL { + if let u = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) { return u } + // Jailbreak installs without a group container: fall back to a shared world-readable folder. + let u = URL(fileURLWithPath: "/var/mobile/Library/Mulberry", isDirectory: true) + try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true) + return u + } + + static var file: URL { container.appendingPathComponent("now.json") } + static var artFile: URL { container.appendingPathComponent("art.jpg") } + + static func load() -> NowSnapshot { + guard let d = try? Data(contentsOf: file), let s = try? JSONDecoder().decode(NowSnapshot.self, from: d) else { return NowSnapshot() } + return s + } + + func save() { + if let d = try? JSONEncoder().encode(self) { try? d.write(to: NowSnapshot.file, options: .atomic) } + } + + /// Position at a given time, extrapolated while playing. + func position(at date: Date) -> Double { + guard playing else { return position } + return min(duration > 0 ? duration : .infinity, position + date.timeIntervalSince1970 - at) + } + + func lyricIndex(at date: Date) -> Int { + let t = position(at: date) + var ans = -1 + for (i, s) in lyrics.enumerated() where s <= t + 0.15 { ans = i } + return ans + } +} + +// MARK: Widget buttons (iOS 17 interactive widgets). AudioPlaybackIntent runs in the app's process. + +enum MulberryCommand: String, AppEnum { + case toggle, next, previous, shuffle, repeatMode, favourite + + static var typeDisplayRepresentation: TypeDisplayRepresentation { "Mulberry command" } + static var caseDisplayRepresentations: [MulberryCommand: DisplayRepresentation] { + [.toggle: "Play/Pause", .next: "Next", .previous: "Previous", .shuffle: "Shuffle", .repeatMode: "Repeat", + .favourite: "Favourite"] + } +} + +@available(iOS 17.0, *) +struct MulberryControlIntent: AudioPlaybackIntent { + static var title: LocalizedStringResource = "Control Mulberry" + static var isDiscoverable = false + + @Parameter(title: "Command") var command: MulberryCommand + + init() { command = .toggle } + init(_ c: MulberryCommand) { command = c } + + func perform() async throws -> some IntentResult { + let c = command + await MainActor.run { IntentRouter.handler?(c) } + return .result() + } +} + +/// The app installs a handler at launch; inside the widget extension it stays nil. +enum IntentRouter { + @MainActor static var handler: ((MulberryCommand) -> Void)? +} diff --git a/Widget/MulberryWidgets.swift b/Widget/MulberryWidgets.swift new file mode 100644 index 0000000..417f098 --- /dev/null +++ b/Widget/MulberryWidgets.swift @@ -0,0 +1,357 @@ +import WidgetKit +import SwiftUI +import AppIntents + +struct NowEntry: TimelineEntry { + let date: Date + let snap: NowSnapshot + let art: UIImage? +} + +struct NowProvider: TimelineProvider { + func placeholder(in context: Context) -> NowEntry { + var s = NowSnapshot() + s.title = "Drive"; s.artist = "Incubus"; s.album = "Make Yourself"; s.duration = 232; s.position = 60 + s.palette = Palette.fromSeed(0xE07A5F, dark: true).widgetColors + return NowEntry(date: Date(), snap: s, art: nil) + } + + func getSnapshot(in context: Context, completion: @escaping (NowEntry) -> Void) { + let s = NowSnapshot.load() + completion(s.title.isEmpty ? placeholder(in: context) : NowEntry(date: Date(), snap: s, art: loadArt())) + } + + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + let s = NowSnapshot.load() + let art = loadArt() + let now = Date() + var entries = [NowEntry(date: now, snap: s, art: art)] + if s.playing && s.duration > 0 { + // One entry per upcoming synced lyric line (up to 60), so the lyrics card follows the song. + let pos = s.position(at: now) + let end = now.addingTimeInterval(max(0, s.duration - pos)) + for t in s.lyrics where t > pos && entries.count < 60 { + let d = now.addingTimeInterval(t - pos) + if d < end { entries.append(NowEntry(date: d, snap: s, art: art)) } + } + var done = s + done.playing = false + done.position = s.duration + entries.append(NowEntry(date: end.addingTimeInterval(1), snap: done, art: art)) + completion(Timeline(entries: entries, policy: .after(end.addingTimeInterval(2)))) + } else { + completion(Timeline(entries: entries, policy: .never)) + } + } + + private func loadArt() -> UIImage? { + guard let d = try? Data(contentsOf: NowSnapshot.artFile) else { return nil } + return UIImage(data: d) + } +} + +extension Palette { + var widgetColors: [UInt32] { + [primary, onPrimary, primaryContainer, onPrimaryContainer, secondaryContainer, onSecondaryContainer, surface, + surfaceHigh, onSurface, onSurfaceVariant] + } +} + +/// Colour lookup from the snapshot (falls back to the default palette). +struct WColors { + let c: [Color] + init(_ s: NowSnapshot) { + let raw = s.palette.count == 10 ? s.palette : Palette.fromSeed(Palette.defaultSeed, dark: s.dark).widgetColors + c = raw.map { Color(rgb: $0) } + } + var primary: Color { c[0] } + var onPrimary: Color { c[1] } + var primaryC: Color { c[2] } + var onPrimaryC: Color { c[3] } + var secondaryC: Color { c[4] } + var onSecondaryC: Color { c[5] } + var surface: Color { c[6] } + var surfaceHigh: Color { c[7] } + var onSurface: Color { c[8] } + var onSurfaceVar: Color { c[9] } +} + +struct CookieShape: Shape { + var depth: CGFloat = 0.045 + func path(in rect: CGRect) -> Path { + Shapes.cookie(center: CGPoint(x: rect.midX, y: rect.midY), radius: min(rect.width, rect.height) / 2, depth: depth, rotation: 0) + } +} + +struct CoverCookie: View { + let art: UIImage? + let colors: WColors + var body: some View { + ZStack { + if let art { Image(uiImage: art).resizable().scaledToFill() } + else { colors.primaryC.overlay(Image(systemName: "music.note").font(.title2).foregroundColor(colors.onPrimaryC)) } + } + .clipShape(CookieShape()) + } +} + +struct CtlButton: View { + let cmd: MulberryCommand + let icon: String + let size: CGFloat + let fg: Color + let bg: Color + var wide = false + var body: some View { + Button(intent: MulberryControlIntent(cmd)) { + Image(systemName: icon) + .font(.system(size: size * 0.4, weight: .bold)) + .foregroundColor(fg) + .frame(width: wide ? size * 1.5 : size, height: size) + .background(Capsule().fill(bg)) + } + .buttonStyle(.plain) + } +} + +struct Controls: View { + let s: NowSnapshot + let col: WColors + var size: CGFloat = 34 + var body: some View { + HStack(spacing: 8) { + CtlButton(cmd: .shuffle, icon: "shuffle", size: size, fg: s.shuffle ? col.onPrimaryC : col.onSurfaceVar, + bg: s.shuffle ? col.primaryC : col.surfaceHigh) + CtlButton(cmd: .previous, icon: "backward.end.fill", size: size, fg: col.onSecondaryC, bg: col.secondaryC) + CtlButton(cmd: .toggle, icon: s.playing ? "pause.fill" : "play.fill", size: size, fg: col.onPrimary, bg: col.primary, wide: true) + CtlButton(cmd: .next, icon: "forward.end.fill", size: size, fg: col.onSecondaryC, bg: col.secondaryC) + CtlButton(cmd: .repeatMode, icon: s.repeatMode == 2 ? "repeat.1" : "repeat", size: size, + fg: s.repeatMode > 0 ? col.onPrimaryC : col.onSurfaceVar, bg: s.repeatMode > 0 ? col.primaryC : col.surfaceHigh) + } + } +} + +/// Progress that advances by itself while playing. +struct LiveProgress: View { + let s: NowSnapshot + let col: WColors + let date: Date + var showTimes = true + var body: some View { + let pos = s.position(at: date) + let start = date.addingTimeInterval(-pos) + let end = start.addingTimeInterval(max(1, s.duration)) + VStack(spacing: 2) { + if s.playing && s.duration > 0 { + ProgressView(timerInterval: start...end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() } + .tint(col.primary) + } else { + ProgressView(value: s.duration > 0 ? min(1, pos / s.duration) : 0).tint(col.primary) + } + if showTimes { + HStack { + if s.playing { Text(start, style: .timer).monospacedDigit() } else { Text(TimeFmt.string(pos)) } + Spacer() + Text(TimeFmt.string(s.duration)) + } + .font(.system(size: 10).monospacedDigit()) + .foregroundColor(col.onSurfaceVar) + } + } + } +} + +struct PlayerWidgetView: View { + let e: NowEntry + @Environment(\.widgetFamily) var family + + var body: some View { + let s = e.snap, col = WColors(s) + Group { + if s.title.isEmpty { + VStack(spacing: 8) { + Image(systemName: "music.note").font(.title).foregroundColor(col.primary) + Text("Nothing playing").font(.headline).foregroundColor(col.onSurface) + Text("Tap to open Mulberry").font(.caption).foregroundColor(col.onSurfaceVar) + } + } else { + switch family { + case .systemSmall: small(s, col) + case .systemLarge: large(s, col) + default: medium(s, col) + } + } + } + .widgetURL(URL(string: "mulberry://nowplaying")) + .containerBackground(for: .widget) { + LinearGradient(colors: [Color(rgb: Palette.mix(s.palette.count == 10 ? s.palette[2] : 0x553355, s.palette.count == 10 ? s.palette[7] : 0x222222, 0.35)), + col.surfaceHigh], startPoint: .topLeading, endPoint: .bottomTrailing) + } + } + + private func titles(_ s: NowSnapshot, _ col: WColors, big: Bool = false) -> some View { + VStack(alignment: .leading, spacing: 1) { + Text(s.title).font(.system(size: big ? 19 : 16, weight: .bold)).foregroundColor(col.onSurface).lineLimit(1) + Text(s.artist).font(.system(size: big ? 15 : 13)).foregroundColor(col.onSurface.opacity(0.85)).lineLimit(1) + if !s.album.isEmpty { Text(s.album).font(.system(size: big ? 14 : 12, weight: .semibold)).foregroundColor(col.primary).lineLimit(1) } + } + } + + private func small(_ s: NowSnapshot, _ col: WColors) -> some View { + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .top) { + CoverCookie(art: e.art, colors: col).frame(width: 64, height: 64) + Spacer() + CtlButton(cmd: .toggle, icon: s.playing ? "pause.fill" : "play.fill", size: 40, fg: col.onPrimary, bg: col.primary) + } + Spacer(minLength: 0) + titles(s, col) + LiveProgress(s: s, col: col, date: e.date, showTimes: false) + } + } + + private func medium(_ s: NowSnapshot, _ col: WColors) -> some View { + VStack(spacing: 6) { + HStack(spacing: 12) { + CoverCookie(art: e.art, colors: col).frame(width: 62, height: 62) + titles(s, col) + Spacer(minLength: 0) + } + LiveProgress(s: s, col: col, date: e.date) + Controls(s: s, col: col, size: 34) + } + } + + private func large(_ s: NowSnapshot, _ col: WColors) -> some View { + VStack(spacing: 10) { + HStack(spacing: 14) { + CoverCookie(art: e.art, colors: col).frame(width: 84, height: 84) + titles(s, col, big: true) + Spacer(minLength: 0) + } + LiveProgress(s: s, col: col, date: e.date) + Controls(s: s, col: col, size: 40) + LyricsCard(e: e, col: col, lines: 3) + } + } +} + +/// The lyrics card (Android widget's lower panel): the current synced line, with the next ones dimmed. +struct LyricsCard: View { + let e: NowEntry + let col: WColors + var lines = 2 + + var body: some View { + let s = e.snap + let i = s.lyricIndex(at: e.date) + VStack(alignment: .leading, spacing: 6) { + Image(systemName: "music.note").font(.caption).foregroundColor(col.primary) + if !s.lyrics.isEmpty { + let cur = i >= 0 ? s.lyricText[i] : (s.lyricText.first ?? "") + Text(cur.isEmpty ? "♪" : cur).font(.system(size: 17, weight: .bold)).foregroundColor(col.onSurface).lineLimit(2) + ForEach(Array(s.lyricText.dropFirst(i + 1).prefix(lines - 1).enumerated()), id: \.offset) { _, l in + Text(l.isEmpty ? "♪" : l).font(.system(size: 13)).foregroundColor(col.onSurfaceVar).lineLimit(1) + } + } else if !s.plainLyric.isEmpty { + Text(s.plainLyric).font(.system(size: 13)).foregroundColor(col.onSurfaceVar).lineLimit(lines + 1) + } else { + Text(s.title.isEmpty ? "Nothing playing" : s.title).font(.system(size: 16, weight: .bold)).foregroundColor(col.onSurface) + Text("No lyrics").font(.system(size: 13)).foregroundColor(col.onSurfaceVar) + } + Spacer(minLength: 0) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(12) + .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(col.surface.opacity(0.55))) + } +} + +struct LyricsWidgetView: View { + let e: NowEntry + var body: some View { + let col = WColors(e.snap) + LyricsCard(e: e, col: col, lines: 3) + .padding(-12) + .widgetURL(URL(string: "mulberry://nowplaying")) + .containerBackground(for: .widget) { col.surfaceHigh } + } +} + +struct LockWidgetView: View { + let e: NowEntry + @Environment(\.widgetFamily) var family + + var body: some View { + let s = e.snap + Group { + switch family { + case .accessoryCircular: + ZStack { + AccessoryWidgetBackground() + if s.playing && s.duration > 0 { + let start = e.date.addingTimeInterval(-s.position(at: e.date)) + ProgressView(timerInterval: start...start.addingTimeInterval(s.duration), countsDown: false) { EmptyView() } currentValueLabel: { + Image(systemName: "pause.fill") + } + .progressViewStyle(.circular) + } else { + Image(systemName: "play.fill") + } + } + .widgetLabel(s.title) + case .accessoryInline: + Text(s.title.isEmpty ? "Mulberry" : "♪ \(s.title) · \(s.artist)") + default: + VStack(alignment: .leading, spacing: 1) { + if !s.lyrics.isEmpty, s.playing, case let i = s.lyricIndex(at: e.date), i >= 0 { + Text(s.lyricText[i].isEmpty ? "♪" : s.lyricText[i]).font(.headline).lineLimit(2) + Text("\(s.title) · \(s.artist)").font(.caption2).lineLimit(1).opacity(0.8) + } else { + Text(s.title.isEmpty ? "Nothing playing" : s.title).font(.headline).lineLimit(1) + Text(s.artist).font(.caption).lineLimit(1) + LiveProgress(s: s, col: WColors(s), date: e.date, showTimes: false) + } + } + } + } + .widgetURL(URL(string: "mulberry://nowplaying")) + .containerBackground(for: .widget) { Color.clear } + } +} + +struct PlayerWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: NowSnapshot.kind, provider: NowProvider()) { PlayerWidgetView(e: $0) } + .configurationDisplayName("Mulberry") + .description("What's playing, with controls.") + .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) + } +} + +struct LyricsWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: NowSnapshot.lyricsKind, provider: NowProvider()) { LyricsWidgetView(e: $0) } + .configurationDisplayName("Mulberry lyrics") + .description("The current line of synced lyrics.") + .supportedFamilies([.systemMedium, .systemSmall]) + } +} + +struct LockWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: NowSnapshot.shapeKind, provider: NowProvider()) { LockWidgetView(e: $0) } + .configurationDisplayName("Mulberry") + .description("Now playing on the Lock Screen.") + .supportedFamilies([.accessoryRectangular, .accessoryCircular, .accessoryInline]) + } +} + +@main +struct MulberryWidgets: WidgetBundle { + var body: some Widget { + PlayerWidget() + LyricsWidget() + LockWidget() + } +} diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..d5369cd --- /dev/null +++ b/build.sh @@ -0,0 +1,77 @@ +#!/bin/bash +# Builds Mulberry for iOS on Linux: swift.org toolchain + iPhoneOS SDK, no Xcode. +# Outputs build/Mulberry--iOS.ipa (TrollStore) and build/Mulberry--iOS-rootless.deb. +# Signing uses a local ldid if present, otherwise ldid on the iPhone over SSH ($IPHONE). +set -euo pipefail +cd "$(dirname "$0")" + +VERSION=${VERSION:-1.0.0} +BUILD=${BUILD:-$(date +%Y%m%d%H%M)} +SWIFT=${SWIFT:-$HOME/.local/opt/swift/usr/bin} +SDK=${SDK:-$HOME/.local/opt/dl/sdk18/iPhoneOS18.6.sdk} +TARGET=arm64-apple-ios17.0 +IPHONE=${IPHONE:-mobile@192.168.1.94} +IPHONE_KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key} +CONFIG=${CONFIG:-release} + +OUT=build +APP=$OUT/Payload/Mulberry.app +APPEX=$APP/PlugIns/MulberryWidgets.appex +rm -rf "$OUT/Payload" "$OUT/deb" +mkdir -p "$APPEX" "$OUT/obj" + +OPT=(-O -wmo) +[ "$CONFIG" = debug ] && OPT=(-Onone -g) + +common=(-target "$TARGET" -sdk "$SDK" -swift-version 5 "${OPT[@]}" + -use-ld=lld -Xlinker -dead_strip + -Xcc -Wno-unused-command-line-argument) + +echo "== app" +"$SWIFT/swiftc" "${common[@]}" -module-name Mulberry \ + $(find App Shared -name '*.swift' | sort) \ + -o "$APP/Mulberry" + +echo "== widget extension" +"$SWIFT/swiftc" "${common[@]}" -module-name MulberryWidgets -application-extension \ + $(find Widget Shared -name '*.swift' | sort) \ + -o "$APPEX/MulberryWidgets" + +echo "== bundle" +sed -e "s/@VERSION@/$VERSION/" -e "s/@BUILD@/$BUILD/" Resources/Info.plist > "$APP/Info.plist" +sed -e "s/@VERSION@/$VERSION/" -e "s/@BUILD@/$BUILD/" Resources/Widget-Info.plist > "$APPEX/Info.plist" +cp Resources/AppIcon*.png "$APP/" +printf 'APPL????' > "$APP/PkgInfo" + +echo "== sign" +if command -v ldid >/dev/null; then + ldid -Spackaging/widget.entitlements "$APPEX/MulberryWidgets" + ldid -Spackaging/app.entitlements "$APP/Mulberry" +else + ssh_=(ssh -i "$IPHONE_KEY" -o BatchMode=yes -o ConnectTimeout=10 "$IPHONE") + remote=/var/mobile/Documents/mulberry-sign + "${ssh_[@]}" "rm -rf $remote && mkdir -p $remote" + scp -i "$IPHONE_KEY" -q "$APP/Mulberry" "$APPEX/MulberryWidgets" packaging/app.entitlements packaging/widget.entitlements "$IPHONE:$remote/" + "${ssh_[@]}" "cd $remote && ldid -Swidget.entitlements MulberryWidgets && ldid -Sapp.entitlements Mulberry" + scp -i "$IPHONE_KEY" -q "$IPHONE:$remote/Mulberry" "$APP/Mulberry" + scp -i "$IPHONE_KEY" -q "$IPHONE:$remote/MulberryWidgets" "$APPEX/MulberryWidgets" + "${ssh_[@]}" "rm -rf $remote" +fi + +echo "== ipa" +rm -f "$OUT/Mulberry-$VERSION-iOS.ipa" +(cd "$OUT" && zip -qry "Mulberry-$VERSION-iOS.ipa" Payload) + +echo "== deb (rootless)" +D=$OUT/deb +mkdir -p "$D/data/var/jb/Applications" "$D/control" +cp -a "$APP" "$D/data/var/jb/Applications/" +sed "s/@VERSION@/$VERSION/" packaging/control > "$D/control/control" +cp packaging/postinst packaging/prerm "$D/control/" +(cd "$D/control" && tar --owner=0 --group=0 -czf ../control.tar.gz .) +(cd "$D/data" && tar --owner=0 --group=0 -cJf ../data.tar.xz .) +echo "2.0" > "$D/debian-binary" +rm -f "$OUT/Mulberry-$VERSION-iOS-rootless.deb" +(cd "$D" && ar rc "../Mulberry-$VERSION-iOS-rootless.deb" debian-binary control.tar.gz data.tar.xz) + +ls -la "$OUT"/*.ipa "$OUT"/*.deb diff --git a/packaging/app.entitlements b/packaging/app.entitlements new file mode 100644 index 0000000..a89f9a0 --- /dev/null +++ b/packaging/app.entitlements @@ -0,0 +1,10 @@ + + + + + application-identifierMULBERRY00.com.mulberry.player + com.apple.developer.team-identifierMULBERRY00 + com.apple.security.application-groupsgroup.com.mulberry.player + get-task-allow + + diff --git a/packaging/control b/packaging/control new file mode 100644 index 0000000..d2c664e --- /dev/null +++ b/packaging/control @@ -0,0 +1,10 @@ +Package: com.mulberry.player +Name: Mulberry +Version: @VERSION@ +Architecture: iphoneos-arm64 +Description: Material You music player: library, playlists, synced lyrics, widgets. No tweak injection needed. +Maintainer: astar76 +Author: astar76 +Section: Multimedia +Depends: firmware (>= 17.0) +Icon: file:///var/jb/Applications/Mulberry.app/AppIcon60x60@2x.png diff --git a/packaging/postinst b/packaging/postinst new file mode 100755 index 0000000..738772f --- /dev/null +++ b/packaging/postinst @@ -0,0 +1,3 @@ +#!/bin/sh +uicache -p /var/jb/Applications/Mulberry.app 2>/dev/null || uicache -a +exit 0 diff --git a/packaging/prerm b/packaging/prerm new file mode 100755 index 0000000..bef8649 --- /dev/null +++ b/packaging/prerm @@ -0,0 +1,3 @@ +#!/bin/sh +uicache -u /var/jb/Applications/Mulberry.app 2>/dev/null || true +exit 0 diff --git a/packaging/widget.entitlements b/packaging/widget.entitlements new file mode 100644 index 0000000..e7ff59a --- /dev/null +++ b/packaging/widget.entitlements @@ -0,0 +1,9 @@ + + + + + application-identifierMULBERRY00.com.mulberry.player.widgets + com.apple.developer.team-identifierMULBERRY00 + com.apple.security.application-groupsgroup.com.mulberry.player + +