Compare commits

...
11 changed files with 179 additions and 42 deletions

No files matched your search

+24 -6
View File
@@ -219,11 +219,19 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
@ObservationIgnored private var stationGen = 0
@ObservationIgnored private var stationBusy = false
private static let radioAlbumsAhead = 8
private static let radioAlbumsLow = 3
/// Each new song adds an album, up to this many ahead (keeps the queue from growing without end).
private static let radioAlbumsMax = 40
/// Album radio: the song the last top-up saw, and songs started since that haven't added their album yet.
@ObservationIgnored private var radioSeenUid: Int64?
@ObservationIgnored private var radioOwed = 0
private static let radioSongsBatch = 100
private static let radioSongsLow = 25
private func setStation(_ s: Station?) { station = s; stationGen += 1; stationBusy = false }
private func setStation(_ s: Station?) {
station = s; stationGen += 1; stationBusy = false
radioSeenUid = queue.indices.contains(index) ? queue[index].uid : nil
radioOwed = 0
}
private func albumDeck() async throws -> [String] {
var deck = (try? await plex.albums().map(\.ratingKey)) ?? []
@@ -268,18 +276,28 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
let gen = stationGen
switch st {
case .albums(let saved):
// Every song that starts (the next track, a skip, a jump to another album) owes one more album,
// so the queue always runs on past what's playing.
let uid = queue[index].uid
if uid != radioSeenUid { radioSeenUid = uid; radioOwed += 1 }
let ahead = Set(queue[index...].map { $0.track.albumKey ?? $0.track.album }).count
guard ahead <= Self.radioAlbumsLow else { return }
let want = min(max(Self.radioAlbumsAhead + 1 - ahead, radioOwed), Self.radioAlbumsMax - ahead)
guard want > 0 else { radioOwed = 0; return }
stationBusy = true
let owed = radioOwed
Task { @MainActor in
defer { if gen == stationGen { stationBusy = false } }
var got = false
// Checks again once the albums are in, unless nothing came back (server down: don't spin).
defer { if gen == stationGen { stationBusy = false; if got { topUpStation() } } }
var deck = saved
if deck.isEmpty { deck = (try? await albumDeck()) ?? [] }
let take = Array(deck.prefix(Self.radioAlbumsAhead + 1 - ahead))
if deck.count < want { deck += (try? await albumDeck()) ?? [] }
let take = Array(deck.prefix(want))
deck.removeFirst(take.count)
let tracks = await albumTracks(take)
guard gen == stationGen else { return }
station = .albums(deck)
radioOwed = max(radioOwed - owed, 0)
got = !tracks.isEmpty
addToQueue(tracks)
}
case .songs:
+8 -3
View File
@@ -88,15 +88,20 @@ final class StemPlaylists {
/// Saves [data] (any image format Photos hands over) as the list's cover, scaled to 1200 px.
/// Each pick gets a new file name so cached art doesn't show the old one.
@discardableResult
func setPhotoArt(_ id: String, _ data: Data) -> Bool {
guard let img = UIImage(data: data) else { return false }
/// A picked photo as a JPEG no bigger than 1200 px a side.
static func coverJpeg(_ data: Data) -> Data? {
guard let img = UIImage(data: data) else { return nil }
let side: CGFloat = 1200
let scale = min(1, side / max(img.size.width, img.size.height, 1))
let size = CGSize(width: (img.size.width * scale).rounded(), height: (img.size.height * scale).rounded())
let fmt = UIGraphicsImageRendererFormat.default(); fmt.scale = 1
let jpeg = UIGraphicsImageRenderer(size: size, format: fmt).jpegData(withCompressionQuality: 0.85) { _ in
return UIGraphicsImageRenderer(size: size, format: fmt).jpegData(withCompressionQuality: 0.85) { _ in
img.draw(in: CGRect(origin: .zero, size: size))
}
}
func setPhotoArt(_ id: String, _ data: Data) -> Bool {
guard let jpeg = Self.coverJpeg(data) else { return false }
let name = "\(id)-\(UUID().uuidString.prefix(8).lowercased()).jpg"
do {
try FileManager.default.createDirectory(at: Self.artDir, withIntermediateDirectories: true)
+14 -3
View File
@@ -80,7 +80,8 @@ struct JItem: Decodable {
func toArtist() -> Artist { Artist(ratingKey: id, title: name, sortTitle: sortName ?? name, thumb: thumb) }
func toPlaylist() -> Playlist {
Playlist(ratingKey: id, title: name, thumb: thumb, trackCount: childCount ?? 0, durationMs: durationMs)
// "id|tag": a new cover changes the tag, so the art cache doesn't keep the old one.
Playlist(ratingKey: id, title: name, thumb: primaryTag.map { "\(id)|\($0)" } ?? thumb, trackCount: childCount ?? 0, durationMs: durationMs)
}
}
@@ -414,6 +415,15 @@ final class JellyfinClient: MediaSource, @unchecked Sendable {
try await send("DELETE", "/Items/\(key)")
}
/// Jellyfin wants the image base64 encoded in the body.
func setPlaylistArt(_ key: String, jpeg: Data) async throws {
guard server.signedIn else { throw NotSignedIn() }
var req = request(try url("/Items/\(key)/Images/Primary"), method: "POST")
req.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
req.httpBody = jpeg.base64EncodedData()
_ = try await http.data(req)
}
// ---- playback reporting ----------------------------------------------------------------
func scrobble(_ trackKey: String) async {
@@ -431,8 +441,9 @@ final class JellyfinClient: MediaSource, @unchecked Sendable {
// ---- URLs ---------------------------------------------------------------------------
func artUrl(_ thumb: String?, px: Int) -> URL? {
guard let thumb, !thumb.isEmpty, server.signedIn, let u = URL(string: base + "/Items/\(thumb)/Images/Primary") else { return nil }
return u.with([("fillWidth", px), ("fillHeight", px), ("quality", 90), ("api_key", server.token)])
let parts = thumb?.split(separator: "|", maxSplits: 1).map(String.init) ?? []
guard let id = parts.first, !id.isEmpty, server.signedIn, let u = URL(string: base + "/Items/\(id)/Images/Primary") else { return nil }
return u.with([("fillWidth", px), ("fillHeight", px), ("quality", 90), ("tag", parts.count > 1 ? parts[1] : nil), ("api_key", server.token)])
}
/// The original file, untouched, like Plex's part URL.
+2
View File
@@ -55,6 +55,8 @@ protocol MediaSource: AnyObject, Sendable {
func removeFromPlaylist(_ key: String, playlistItemId: Int64) async throws
func movePlaylistItem(_ key: String, playlistItemId: Int64, afterItemId: Int64?) async throws
func renamePlaylist(_ key: String, title: String) async throws
/// Uploads [jpeg] as the playlist's cover.
func setPlaylistArt(_ key: String, jpeg: Data) async throws
func deletePlaylist(_ key: String) async throws
func scrobble(_ trackKey: String) async
func timeline(_ track: Track, state: String, positionMs: Int64) async
+7
View File
@@ -235,6 +235,13 @@ final class PlexClient: @unchecked Sendable {
try await s.deletePlaylist(k)
}
/// Uploads the cover, then returns the playlist's new thumb.
func setPlaylistArt(_ key: String, jpeg: Data) async throws -> String? {
let (s, k) = try routed(key)
try await s.setPlaylistArt(k, jpeg: jpeg)
return try await s.playlists(sort: "titleSort").first { $0.ratingKey == k }?.thumb.tagged(s.server.id)
}
// ---- playback reporting ---------------------------------------------------------
func scrobble(_ trackKey: String) async {
+9
View File
@@ -293,6 +293,15 @@ final class PlexServer: MediaSource, @unchecked Sendable {
try await send("DELETE", "/playlists/\(key)")
}
/// Plex takes the image as the raw body and selects it as the poster.
func setPlaylistArt(_ key: String, jpeg: Data) async throws {
guard signedIn else { throw NotSignedIn() }
var req = request(try url("/library/metadata/\(key)/posters"), method: "POST")
req.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
req.httpBody = jpeg
_ = try await http.data(req)
}
// ---- playback reporting ---------------------------------------------------------
func scrobble(_ trackKey: String) async {
+38 -2
View File
@@ -54,14 +54,50 @@ struct MediaMenu {
playlistKey: nil, extra: [], confirmDownload: true, stemmed: stemmed(cov))
}
func playlist(_ pl: Playlist, extra: [SheetAction] = []) -> [SheetAction] {
/// [changed] hears the playlist after a rename or a new cover, so an open page can follow.
func playlist(_ pl: Playlist, extra: [SheetAction] = [], changed: ((Playlist) -> Void)? = nil) -> [SheetAction] {
let plex = g.plex
let copy = SheetAction("Copy to Stem Playlist…", icon: "doc.on.doc") { copyToStems(pl) }
let gr = DownloadGroup(kind: .playlist, key: pl.ratingKey, title: pl.title, subtitle: "Playlist", thumb: pl.thumb)
return collection(pl.title, gr, { try await plex.playlistTracks(pl.ratingKey) }, playlistKey: pl.ratingKey, extra: [copy] + extra,
return collection(pl.title, gr, { try await plex.playlistTracks(pl.ratingKey) }, playlistKey: pl.ratingKey,
extra: [copy] + (pl.smart ? [] : playlistEdits(pl, changed)) + extra,
confirmDownload: pl.trackCount > 50)
}
/// Rename and Change Cover, saved on the playlist's own server (Plex or Jellyfin).
private func playlistEdits(_ pl: Playlist, _ changed: ((Playlist) -> Void)?) -> [SheetAction] {
let plex = g.plex
let overlays = overlays
let ui = ui
let rename = SheetAction("Rename…", icon: "pencil") {
overlays.prompt("Rename Playlist", nil, initial: pl.title, "Save") { name in
Task {
do {
try await plex.renamePlaylist(pl.ratingKey, title: name)
var p = pl; p.title = name
ui.playlistEdits += 1
changed?(p)
} catch { overlays.hud("Couldn't rename: \(error.localizedDescription)", "exclamationmark.triangle") }
}
}
}
let cover = SheetAction("Change Cover…", icon: "photo") {
overlays.pickPhoto { data in
guard let jpeg = StemPlaylists.coverJpeg(data) else { overlays.hud("Couldn't use that photo", "exclamationmark.triangle"); return }
Task {
do {
let thumb = try await plex.setPlaylistArt(pl.ratingKey, jpeg: jpeg)
var p = pl; p.thumb = thumb ?? pl.thumb
ui.playlistEdits += 1
changed?(p)
overlays.hud("Cover updated")
} catch { overlays.hud("Couldn't upload: \(error.localizedDescription)", "exclamationmark.triangle") }
}
}
}
return [rename, cover]
}
func stemPlaylist(_ pl: StemPlaylist, extra: [SheetAction] = [], onPage: Bool = false) -> [SheetAction] {
var a = [
SheetAction("Play Next", icon: "text.line.first.and.arrowtriangle.forward") {
+11 -9
View File
@@ -74,6 +74,8 @@ final class Ui {
/// Split only: which of the deck's pages is showing.
var deckPage: DeckPage = .Stems
let overlays: Overlays
/// Bumped when a playlist is renamed or gets a new cover, so the lists reload.
var playlistEdits = 0
init(overlays: Overlays) { self.overlays = overlays }
@@ -149,20 +151,20 @@ final class Ui {
}
/// Leaves the lock as it is: freeing it let iOS turn the window while audio kept the app alive.
/// Folded with something playing, Now Playing goes up now so the app (and the snapshot iOS
/// shows on return) comes back on it instead of the library.
func backgrounded() {
away = true
showPlayingFolded()
}
func backgrounded() { away = true }
private var away = false
/// Folded with something playing, the app comes back on Now Playing.
private func showPlayingFolded() {
guard folded, !nowPlayingOpen, AppGraph.shared.playback.current != nil else { return }
var t = Transaction()
t.disablesAnimations = true
withTransaction(t) { nowPlayingOpen = true }
// Back from the background folded with something playing: Now Playing slides up as if
// swiped open, once the app's own opening animation has landed.
Task { @MainActor in
try? await Task.sleep(for: .milliseconds(180))
guard self.folded, !self.nowPlayingOpen, AppGraph.shared.playback.current != nil else { return }
self.nowPlayingOpen = true
}
}
private func lockOrientation() {
+59 -8
View File
@@ -3,6 +3,44 @@ import UIKit
enum NpPanel { case Art, Mixer, Queue, Lyrics }
/// The close drag's offset. Only DropOffset reads it, so dragging re-renders just the offset.
@Observable final class DropState { var y: CGFloat = 0 }
/// ProMotion only runs as fast as someone asks. A plain drag asks nothing, and the 30 fps meters and
/// bars then set the pace, so the close drag crawled. This display link asks for 120 Hz while held.
@MainActor final class FrameBoost: NSObject {
static let shared = FrameBoost()
private var link: CADisplayLink?
private var stopGen = 0
func start() {
stopGen += 1
guard link == nil else { return }
let l = CADisplayLink(target: self, selector: #selector(tick))
l.preferredFrameRateRange = CAFrameRateRange(minimum: 80, maximum: 120, preferred: 120)
l.add(to: .main, forMode: .common)
link = l
}
/// Keeps the boost through the spring back or the cover's slide down.
func stop(after: Double = 0.6) {
stopGen += 1
let gen = stopGen
DispatchQueue.main.asyncAfter(deadline: .now() + after) { [weak self] in
guard let self, gen == self.stopGen else { return }
self.link?.invalidate()
self.link = nil
}
}
@objc private func tick() {}
}
private struct DropOffset: ViewModifier {
let state: DropState
func body(content: Content) -> some View { content.offset(y: state.y) }
}
func deviceIcon(_ d: OutputDevice) -> (String, UInt32) {
switch d.kind {
case .Speaker: ("iphone", 0x8E8E93)
@@ -62,8 +100,9 @@ struct NowPlayingScreen: View {
@Environment(\.palette) private var base
@Environment(\.dismiss) private var dismiss
@State private var panel = NpPanel.Art
/// How far the screen is being dragged down to close it.
@State private var drop: CGFloat = 0
/// How far the screen is being dragged down to close it. Kept out of the view's own state so a
/// drag only moves the screen (DropOffset) instead of rebuilding all of Now Playing each frame.
@State private var drop = DropState()
/// Docked beside the hinge the pane is narrow, so the controls pack tighter. Full screen
/// (folded or any other iPhone) uses the roomy layout across the whole window.
private var tight: Bool { docked }
@@ -75,6 +114,8 @@ struct NowPlayingScreen: View {
@State private var ctlH: CGFloat = 0
/// The screen's height, for the strip at the top that a drag down closes from.
@State private var screenH: CGFloat = 0
/// Where the art sits on screen: folded, a drag down that starts on it closes Now Playing.
@State private var artFrame: CGRect = .zero
@Environment(\.verticalSizeClass) private var vSize
/// Folded iPhone Duo: the outer display keeps a status column down the right edge.
@State private var folded = false
@@ -151,7 +192,7 @@ struct NowPlayingScreen: View {
.gesture(screenDrag(header: true)) }
}
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { screenH = $0 }
.offset(y: drop)
.modifier(DropOffset(state: drop))
// Drag down from the top strip (or the song header) to close, so it never fights the
// stem faders. Swipe up anywhere on the art for the queue.
.simultaneousGesture(screenDrag(), including: panel == .Art ? .all : .subviews)
@@ -167,6 +208,7 @@ struct NowPlayingScreen: View {
switch panel {
case .Art: ArtPanel(thumb: track.thumb, playing: g.playback.playWhenReady, inset: header ? artInset : 12,
leading: folded && !docked && !ui.split && g.settings.foldedArtLeft, edge: hPad).contentShape(Rectangle())
.onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { if drop.y == 0 { artFrame = $0 } }
case .Mixer: VStack(spacing: 0) { if header { mini(track) }; MixerPanel(spread: folded) }
case .Queue: VStack(spacing: 0) { if header { mini(track) }; QueuePanel(close: { show(.Queue) }) }
case .Lyrics: VStack(spacing: 0) { if header { mini(track) }; LyricsPanel(track: track) }
@@ -287,19 +329,28 @@ struct NowPlayingScreen: View {
}
/// Drag down to close: from the grabber or song header, or anywhere in the top tenth of the screen.
/// Folded, also from the art (only while it shows, so never over the stem dials).
private func fromTop(_ v: DragGesture.Value, header: Bool) -> Bool {
header || v.startLocation.y < max(screenH * 0.1, 56)
|| (folded && !docked && panel == .Art && artFrame.contains(v.startLocation))
}
private func screenDrag(header: Bool = false) -> some Gesture {
DragGesture(minimumDistance: 20)
DragGesture(minimumDistance: 20, coordinateSpace: .global)
.onChanged { v in
let dy = v.translation.height
let top = header || v.startLocation.y < max(screenH * 0.1, 56)
drop = !docked && top && dy > 0 && dy > abs(v.translation.width) ? dy : 0
let top = fromTop(v, header: header)
let y = !docked && top && dy > 0 && dy > abs(v.translation.width) ? dy : 0
if y > 0 { FrameBoost.shared.start() }
if y != drop.y { drop.y = y }
}
.onEnded { v in
FrameBoost.shared.stop()
let dy = v.translation.height
let vertical = abs(dy) > abs(v.translation.width)
let top = header || v.startLocation.y < max(screenH * 0.1, 56)
let top = fromTop(v, header: header)
if !docked && top && vertical && (dy > 120 || v.predictedEndTranslation.height > 300) { dismiss(); return }
withAnimation(.spring(duration: 0.3, bounce: 0.1)) { drop = 0 }
withAnimation(.spring(duration: 0.3, bounce: 0.1)) { drop.y = 0 }
// Never from the stems: a slightly upward fader drag or scroll there kept opening the queue.
if !docked && vertical && dy < -50 && panel != .Mixer && g.settings.swipeUpQueue {
withAnimation(.spring(duration: 0.38, bounce: 0.12)) { panel = .Queue }
+6 -10
View File
@@ -47,7 +47,7 @@ struct PlaylistsScreen: View {
Button { kind == .Plex ? newPlaylist() : newStemPlaylist() } label: { Image(systemName: "plus") }
}
}
.task(id: "\(g.settings.libraryKey)|\(sort.token)|\(reload)") {
.task(id: "\(g.settings.libraryKey)|\(sort.token)|\(reload)|\(ui.playlistEdits)") {
// /playlists may not take sort=random, so Random shuffles here.
let random = sort.option.random
await LoadState.load($lists) { try await random ? g.plex.playlists().shuffled() : g.plex.playlists(sort: sort.param) }
@@ -221,6 +221,7 @@ struct PlaylistScreen: View {
@State private var tracks: LoadState<[Track]> = .loading
@State private var reload = 0
@State private var title: String
@State private var thumb: String?
@State private var editing = false
@State private var items: [Track] = []
@State private var removed: [Track] = []
@@ -230,6 +231,7 @@ struct PlaylistScreen: View {
init(playlist: Playlist) {
self.playlist = playlist
_title = State(initialValue: playlist.title)
_thumb = State(initialValue: playlist.thumb)
}
var body: some View {
@@ -284,7 +286,7 @@ struct PlaylistScreen: View {
private func header(_ list: [Track]) -> some View {
VStack(spacing: 0) {
Artwork(thumb: playlist.thumb, size: 230, corner: 10, placeholder: "music.note.list")
Artwork(thumb: thumb, size: 230, corner: 10, placeholder: "music.note.list")
Text(title).font(.title2.bold()).foregroundStyle(p.label).multilineTextAlignment(.center).lineLimit(2)
.padding(.horizontal, 32).padding(.top, 14)
if !list.isEmpty {
@@ -312,13 +314,6 @@ struct PlaylistScreen: View {
var extra: [SheetAction] = []
let plex = g.plex
let key = playlist.ratingKey
if !playlist.smart {
extra.append(SheetAction("Rename…", icon: "pencil") {
ui.overlays.prompt("Rename Playlist", nil, initial: title, "Save") { name in
Task { if (try? await plex.renamePlaylist(key, title: name)) != nil { title = name } }
}
})
}
extra.append(SheetAction("Delete Playlist", icon: "trash", destructive: true) {
ui.overlays.confirm("Delete “\(title)”?", "This removes it from Plex for every app.", "Delete") {
Task { if (try? await plex.deletePlaylist(key)) != nil { ui.pop() } }
@@ -326,8 +321,9 @@ struct PlaylistScreen: View {
})
var pl = playlist
pl.title = title
pl.thumb = thumb
pl.trackCount = list.count
return ui.menu.playlist(pl, extra: extra)
return ui.menu.playlist(pl, extra: extra) { title = $0.title; thumb = $0.thumb }
}
/// Sends removals, then replays the new order as "move after" calls against a simulated server list.
+1 -1
View File
@@ -9,7 +9,7 @@ settings:
# iOS needs a plain number for the bundle version; the label is what the app and releases show.
MARKETING_VERSION: "0.10.1"
VERSION_LABEL: "0.10.1"
CURRENT_PROJECT_VERSION: "55"
CURRENT_PROJECT_VERSION: "61"
# Dev builds override these (build-ipa.sh dev) so they install next to the release app.
APP_ID: org.cdnutter.stemify
APP_NAME: Stemify