diff --git a/README.md b/README.md index 54b82a3..dded722 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,9 @@ -### ⚠️ THIS PROJECT WAS ENTIRELY VIBECODED AND IS SLOP. DO NOT PROCEED IF YOU DO NOT ALIGN WITH THESE VALUES. DO NOT COMPLAIN ABOUT IT IN PULL RELEASES, ISSUES, ETC. UNLESS THERE ARE SEVERE SECURITY RISKS. THEY WILL BE REMOVED. PROCEED AT YOUR OWN RISK! ⚠️ +> [!CAUTION] +> This project heavily used agentic coding practices. It is not recommended to use this for production and should be heavily monitored prior to any implementation. If you do not align with agentic-coding values, do not use this application. + +> The model(s) used: **Claude Opus 5.5, Claude Sonnet 5.5** + +> AI contribution: **99%**, Human contribution: **1%** # Stemify diff --git a/ios/Stemify/App/AppGraph.swift b/ios/Stemify/App/AppGraph.swift index 96c40ad..90d05a0 100644 --- a/ios/Stemify/App/AppGraph.swift +++ b/ios/Stemify/App/AppGraph.swift @@ -45,6 +45,14 @@ final class AppGraph { mediaSession = URLSession(configuration: m) plex = PlexClient(http: apiHttp, settings: settings) + let plex = plex + // Left home or joined Wi-Fi: the saved Plex address may be dead now. Give the new link a moment first. + net.onChange { + Task.detached { + try? await Task.sleep(nanoseconds: 1_500_000_000) + await plex.reroute("network changed") + } + } reach = HomeReach(settings: settings, net: net) let reach = reach carHttp.forceCache = { !reach.lastKnown } diff --git a/ios/Stemify/App/StemifyApp.swift b/ios/Stemify/App/StemifyApp.swift index c6eeeb2..aa7fc74 100644 --- a/ios/Stemify/App/StemifyApp.swift +++ b/ios/Stemify/App/StemifyApp.swift @@ -34,13 +34,13 @@ final class AppDelegate: NSObject, UIApplicationDelegate { enum Orientation { nonisolated(unsafe) static var mask: UIInterfaceOrientationMask = .allButUpsideDown - @MainActor static func lock(_ upright: Bool) { - let m: UIInterfaceOrientationMask = upright ? .portrait : .allButUpsideDown + /// Folded Duo: portrait only. Unfolded Duo: landscape only. Anything else turns freely. + @MainActor static func lock(_ m: UIInterfaceOrientationMask) { guard m != mask else { return } mask = m for case let scene as UIWindowScene in UIApplication.shared.connectedScenes { scene.keyWindow?.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations() - if upright { scene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) { _ in } } + if m != .allButUpsideDown { scene.requestGeometryUpdate(.iOS(interfaceOrientations: m)) { _ in } } } } } @@ -58,6 +58,7 @@ struct StemifyApp: App { AppActivity.setPhone(p != .background) guard p == .active else { return } AppGraph.shared.eq.refreshRoute() + Task.detached { await AppGraph.shared.plex.reroute("foreground") } // Keep downloaded playlists in step with the server, like Plexamp. Task { await AppGraph.shared.downloads.refresh() } } diff --git a/ios/Stemify/Playback/PlaybackManager.swift b/ios/Stemify/Playback/PlaybackManager.swift index a74121a..c868a5d 100644 --- a/ios/Stemify/Playback/PlaybackManager.swift +++ b/ios/Stemify/Playback/PlaybackManager.swift @@ -639,7 +639,7 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable { /// True when [track] would play without the home network: its stems (or, lacking stems, its file) are fully cached. func playableOffline(_ track: Track) -> Bool { if let entry = stems.find(track) { - return StemQuality.allCases.contains { q in entry.stems.allSatisfy { cache.isComplete(Self.stemKey(entry, $0.file, $0.size, q)) } } + return stemsCached(entry) } return track.partKey != nil && cache.isComplete(Self.plexKey(track)) } @@ -721,19 +721,57 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable { } private func openDetached(_ track: Track, _ startMs: Int64) async throws -> (TrackSession, StemEntry?) { - // Plain Plex files need a playback session first, or a Remote Access upload limit fails them. - var stream: URL? - if stems.find(track) == nil, !cache.isComplete(Self.plexKey(track)) { stream = await plex.streamUrl(track) } - return try await withCheckedThrowingContinuation { [stream] cont in + // Stems when the stem server can serve them (or they're downloaded); Plex's own file otherwise. + // Stemify works as a plain Plex player: a stem server that's off or out of reach only costs the stems. + if let entry = await stemsToPlay(track) { + do { + return try await openOn(track, startMs, entry, nil) + } catch { + if Task.isCancelled { throw error } + Log.shared.error("play", "stems for \(track.title) failed (\(error.localizedDescription)), playing from Plex") + Task.detached { [stems] in await stems.refresh() } + } + } + let plain = !cache.isComplete(Self.plexKey(track)) + let stream = plain ? await plex.streamUrl(track) : nil + do { + return try await openOn(track, startMs, nil, stream) + } catch { + // A dead saved address (left home, network changed): pick a working one and try once more. + guard plain, !Task.isCancelled, await plex.reroute("stream failed") else { throw error } + return try await openOn(track, startMs, nil, await plex.streamUrl(track)) + } + } + + /// The stem entry to play, or nil to play Plex's file: skips stems the stem server can't + /// serve right now unless they're fully downloaded. + private func stemsToPlay(_ track: Track) async -> StemEntry? { + guard let entry = stems.find(track) else { return nil } + if stemsCached(entry) { return entry } + // Right after launch the first check may still be running: give it a few seconds + // rather than sit through a long timeout on a server that isn't there. + var waited = 0 + while case .unknown = stems.status, waited < 30, !Task.isCancelled { + try? await Task.sleep(nanoseconds: 100_000_000); waited += 1 + } + if case .online = stems.status { return entry } + return nil + } + + private func stemsCached(_ entry: StemEntry) -> Bool { + StemQuality.allCases.contains { q in entry.stems.allSatisfy { cache.isComplete(Self.stemKey(entry, $0.file, $0.size, q)) } } + } + + private func openOn(_ track: Track, _ startMs: Int64, _ entry: StemEntry?, _ stream: URL?) async throws -> (TrackSession, StemEntry?) { + try await withCheckedThrowingContinuation { cont in DispatchQueue.global(qos: .userInitiated).async { [self] in - cont.resume(with: Result { try open(track, startMs, stream: stream) }) + cont.resume(with: Result { try open(track, startMs, entry: entry, stream: stream) }) } } } /// Opens every stem (or the original file) and waits for the decoders to know their format. - private func open(_ track: Track, _ startMs: Int64, stream: URL? = nil) throws -> (TrackSession, StemEntry?) { - let entry = stems.find(track) + private func open(_ track: Track, _ startMs: Int64, entry: StemEntry?, stream: URL? = nil) throws -> (TrackSession, StemEntry?) { var sources: [(name: String, key: String, url: URL?, hint: String)] = [] if let entry { let q = qualityFor(entry) diff --git a/ios/Stemify/Plex/MediaServer.swift b/ios/Stemify/Plex/MediaServer.swift index c7b697c..a8317d4 100644 --- a/ios/Stemify/Plex/MediaServer.swift +++ b/ios/Stemify/Plex/MediaServer.swift @@ -17,6 +17,9 @@ struct MediaServer: Codable, Hashable, Identifiable { var machineId = "" var sections: [String] = [] var sectionTitles = "" + /// Every address plex.tv lists for this server, best first (local, remote, relay). + /// Optional so servers saved before it still decode. + var connections: [String]? = nil var signedIn: Bool { !token.isEmpty } var ready: Bool { signedIn && !sections.isEmpty } diff --git a/ios/Stemify/Plex/PlexClient.swift b/ios/Stemify/Plex/PlexClient.swift index fba7aad..7e70eed 100644 --- a/ios/Stemify/Plex/PlexClient.swift +++ b/ios/Stemify/Plex/PlexClient.swift @@ -21,6 +21,7 @@ final class PlexClient: @unchecked Sendable { private let lock = NSLock() private var builtFrom = "\u{0}" private var built: [MediaSource] = [] + private var rerouting = false init(http: Http, settings: Settings) { self.http = http @@ -285,6 +286,45 @@ final class PlexClient: @unchecked Sendable { return box.url } + // ---- address re-picking ------------------------------------------------------------ + + /// Re-picks each Plex server's address. Sign-in picks one (a LAN address at home) and it + /// used to stick forever, so away from home every stream hit a dead LAN address (TLS error) + /// or a relay (503). Probes every known address and keeps the best one that answers; + /// when none answer, asks plex.tv for the current list. Returns true if any address changed. + @discardableResult + func reroute(_ why: String) async -> Bool { + lock.lock() + if rerouting { lock.unlock(); return false } + rerouting = true + lock.unlock() + defer { lock.lock(); rerouting = false; lock.unlock() } + + let tv = plexTv() + var changed = false + for srv in settings.servers where srv.kind == .plex && srv.signedIn { + var uris = srv.connections ?? [] + if !uris.contains(srv.base) { uris.append(srv.base) } + var best = await tv.firstAlive(uris, machineId: srv.machineId, token: srv.token) + var fresh: [String]? + if best == nil || srv.connections == nil, !srv.machineId.isEmpty, + let r = (try? await tv.resources(token: srv.token))?.first(where: { $0.clientIdentifier == srv.machineId }) { + fresh = PlexServer.ranked(r) + if best == nil, let f = fresh { best = await tv.firstAlive(f, machineId: srv.machineId, token: srv.token) } + } + var s = srv + if let fresh { s.connections = fresh } + if let best { s.url = best } + guard s != srv else { continue } + if s.url != srv.url { + changed = true + Log.shared.info("plex", "\(srv.label) (\(why)): \(srv.base) -> \(s.base)") + } + settings.save(s) + } + return changed + } + // ---- sign-in helpers -------------------------------------------------------------- /// A Plex client for plex.tv calls and for a server that isn't saved yet. @@ -323,6 +363,7 @@ final class PlexClient: @unchecked Sendable { ?? settings.servers.first { $0.kind == .plex && $0.machineId.isEmpty && $0.base == h.url.trimmingCharacters(in: CharacterSet(charactersIn: "/")) } var srv = known ?? MediaServer(id: settings.nextServerId(), kind: .plex) srv.url = h.url + srv.connections = PlexServer.ranked(h.res) srv.token = h.res.accessToken.isEmpty ? token : h.res.accessToken srv.machineId = h.res.clientIdentifier srv.user = user diff --git a/ios/Stemify/Plex/PlexServer.swift b/ios/Stemify/Plex/PlexServer.swift index 09ad764..0759549 100644 --- a/ios/Stemify/Plex/PlexServer.swift +++ b/ios/Stemify/Plex/PlexServer.swift @@ -375,21 +375,41 @@ final class PlexServer: MediaSource, @unchecked Sendable { /// The first address that answers /identity as the expected server, local ones first, relay last. func reach(_ r: PlexResource, userToken: String) async -> String? { let tok = r.accessToken.isEmpty ? userToken : r.accessToken - let ordered = r.connections.filter { !$0.uri.isEmpty }.sorted { rank($0) < rank($1) } - for c in ordered { - let base = c.uri.trimmingCharacters(in: CharacterSet(charactersIn: "/")) - guard let u = URL(string: base + "/identity") else { continue } - var req = request(u, withToken: false) - req.setValue(tok, forHTTPHeaderField: "X-Plex-Token") - req.timeoutInterval = 3.5 - guard let body = try? await http.data(req), - let id = try? decode(body).machineIdentifier, id == r.clientIdentifier || r.clientIdentifier.isEmpty else { continue } - return base - } - return nil + return await firstAlive(Self.ranked(r), machineId: r.clientIdentifier, token: tok) } - private func rank(_ c: PlexResource.Connection) -> Int { c.relay ? 2 : (c.local ? 0 : 1) } + /// A resource's addresses, local first, then remote, relay last. + static func ranked(_ r: PlexResource) -> [String] { + r.connections.filter { !$0.uri.isEmpty } + .sorted { ($0.relay ? 2 : ($0.local ? 0 : 1)) < ($1.relay ? 2 : ($1.local ? 0 : 1)) } + .map { $0.uri.trimmingCharacters(in: CharacterSet(charactersIn: "/")) } + } + + /// Probes every address's /identity at once, straight to the network (the offline cache + /// would make a dead LAN address look alive), and returns the earliest one in [uris] that + /// answers as [machineId]. + func firstAlive(_ uris: [String], machineId: String, token: String, timeout: TimeInterval = 4) async -> String? { + let bases = uris.map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "/")) } + let alive: [Int] = await withTaskGroup(of: Int?.self) { group in + for (i, b) in bases.enumerated() { + group.addTask { [self] in + guard let u = URL(string: b + "/identity") else { return nil } + var req = request(u, withToken: false) + req.setValue(token, forHTTPHeaderField: "X-Plex-Token") + req.timeoutInterval = timeout + guard let (body, resp) = try? await http.session.data(for: req), + (resp as? HTTPURLResponse)?.statusCode == 200, + let id = try? decode(body).machineIdentifier, + machineId.isEmpty || id == machineId else { return nil } + return i + } + } + var out: [Int] = [] + for await i in group { if let i { out.append(i) } } + return out + } + return alive.min().map { bases[$0] } + } func checkPin(_ id: Int64) async throws -> PlexPin { let req = request(URL(string: "https://plex.tv/api/v2/pins/\(id)")!, withToken: false) diff --git a/ios/Stemify/Resources/Assets.xcassets/AppIcon.appiconset/icon.png b/ios/Stemify/Resources/Assets.xcassets/AppIcon.appiconset/icon.png index 1e4ce50..168a535 100644 Binary files a/ios/Stemify/Resources/Assets.xcassets/AppIcon.appiconset/icon.png and b/ios/Stemify/Resources/Assets.xcassets/AppIcon.appiconset/icon.png differ diff --git a/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-dark.png b/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-dark.png index 4b05ee9..1e5e25e 100644 Binary files a/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-dark.png and b/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-dark.png differ diff --git a/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-tinted.png b/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-tinted.png index c97eaef..771b5ea 100644 Binary files a/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-tinted.png and b/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon-tinted.png differ diff --git a/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon.png b/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon.png index 4b05ee9..1e5e25e 100644 Binary files a/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon.png and b/ios/Stemify/Resources/Assets.xcassets/AppIconDev.appiconset/icon.png differ diff --git a/ios/Stemify/UI/Nav.swift b/ios/Stemify/UI/Nav.swift index ed401a1..80a14f9 100644 --- a/ios/Stemify/UI/Nav.swift +++ b/ios/Stemify/UI/Nav.swift @@ -131,13 +131,24 @@ final class Ui { duo = true UserDefaults.standard.set(true, forKey: "duoSeen") } - Orientation.lock(folded) + lockOrientation() + } + + /// Split (unfolded) goes landscape at once. Portrait waits a moment and checks again, so a + /// frame without a hinge reading mid-rotation can't throw an unfolded phone back upright. + private func lockOrientation() { + if split { Orientation.lock(.landscape); return } + guard folded else { Orientation.lock(.allButUpsideDown); return } + Task { @MainActor in + try? await Task.sleep(for: .milliseconds(400)) + if self.folded { Orientation.lock(.portrait) } + } } func setSplit(_ on: Bool) { guard on != split else { return } split = on - Orientation.lock(folded) + lockOrientation() if on { nowPlayingOpen = false } diff --git a/ios/Stemify/UI/RootView.swift b/ios/Stemify/UI/RootView.swift index 66ac978..44f652b 100644 --- a/ios/Stemify/UI/RootView.swift +++ b/ios/Stemify/UI/RootView.swift @@ -44,32 +44,32 @@ struct RootView: View { set: { if case .tab(let t) = $0 { ui.selectTab(t) } else { ui.showDeck() } }) } - /// Unfolded with something playing, Now Playing leads the bar: the deck (stems, lyrics, queue, - /// EQ) on this side of the hinge, the player docked on the other. On iOS 18 every item stays in - /// the bar and only hides, so folding and unfolding can't shuffle the order. - @ViewBuilder private var bar: some View { - if #available(iOS 18, *) { - let shown = ui.tabs - TabView(selection: selection) { - SwiftUI.Tab("Now Playing", systemImage: "waveform", value: BarItem.deck) { DuoPane { NowPlayingDeck() } } - .hidden(!ui.hasDeckTab) - ForEach(Tab.layout(g.settings.tabLayout), id: \.self) { t in - SwiftUI.Tab(t.rawValue, systemImage: t.icon, value: BarItem.tab(t)) { page(t) } - .hidden(!shown.contains(t)) - } - } - } else { - TabView(selection: selection) { - if ui.hasDeckTab { + /// The bar always holds the same slots. Unfolded with something playing, Now Playing takes + /// the place of the last tab before Settings (iOS folds a sixth item into "More"), so folding + /// and unfolding swaps one item in place and nothing else moves. + private var slots: [BarItem] { + let all = Tab.layout(g.settings.tabLayout) + var items = all.map { BarItem.tab($0) } + guard ui.hasDeckTab else { return items } + if all.count >= Tab.maxVisible, let i = all.lastIndex(where: { $0 != .Settings }) { items[i] = .deck } + else { items.insert(.deck, at: all.lastIndex(of: .Settings) ?? items.count) } + return items + } + + private var bar: some View { + TabView(selection: selection) { + ForEach(Array(slots.enumerated()), id: \.offset) { _, item in + switch item { + case .deck: DuoPane { NowPlayingDeck() } .tabItem { Label("Now Playing", systemImage: "waveform") } - .tag(BarItem.deck) - } - ForEach(ui.tabs, id: \.self) { t in - page(t).tabItem { Label(t.rawValue, systemImage: t.icon) }.tag(BarItem.tab(t)) + .tag(item) + case .tab(let t): + page(t).tabItem { Label(t.rawValue, systemImage: t.icon) }.tag(item) } } } + .transaction { $0.animation = nil } } private func page(_ t: Tab) -> some View { diff --git a/ios/Stemify/UI/Screens/NowPlayingScreen.swift b/ios/Stemify/UI/Screens/NowPlayingScreen.swift index 97e47fa..0d3ce79 100644 --- a/ios/Stemify/UI/Screens/NowPlayingScreen.swift +++ b/ios/Stemify/UI/Screens/NowPlayingScreen.swift @@ -118,7 +118,7 @@ struct NowPlayingScreen: View { @Environment(\.verticalSizeClass) private var vSize /// Folded iPhone Duo: the outer display keeps a status column down the right edge. @State private var folded = false - private var artInset: CGFloat { tight ? 18 : 28 } + private var artInset: CGFloat { tight ? 18 : folded ? 12 : 28 } private var hPad: CGFloat { tight ? 20 : 28 } private var g: AppGraph { .shared } @@ -167,11 +167,12 @@ struct NowPlayingScreen: View { // Folded, the iPhone Duo keeps a status column down the right edge. Run the player under it // (it only overlaps the sliding preset chips) instead of leaving a quarter of the screen empty. // Upright iPhones have no side insets, so this only changes the Duo. - .ignoresSafeArea(.container, edges: !docked && vSize == .regular ? .trailing : []) + // Folded, the bottom inset is empty space too: run the controls down into it, and the art grows into the room. + .ignoresSafeArea(.container, edges: !docked && vSize == .regular ? (folded ? [.trailing, .bottom] : .trailing) : []) // Measured outside the line above, so it still sees the status column. .onGeometryChange(for: Bool.self) { $0.safeAreaInsets.trailing > 20 } action: { folded = $0 && vSize == .regular } .padding(.top, docked ? 4 : tight ? 14 : 20) - .padding(.bottom, tight ? 4 : 8) + .padding(.bottom, tight ? 4 : folded ? 2 : 8) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(c.bg.ignoresSafeArea()) .overlay(alignment: .top) { @@ -202,7 +203,7 @@ struct NowPlayingScreen: View { private func panelView(_ track: Track, header: Bool) -> some View { switch panel { case .Art: ArtPanel(thumb: track.thumb, playing: g.playback.playWhenReady, inset: header || !tight ? artInset : 12, - leading: folded && g.settings.foldedArtLeft).contentShape(Rectangle()) + leading: folded && !docked && !ui.split && g.settings.foldedArtLeft).contentShape(Rectangle()) 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) } @@ -215,8 +216,8 @@ struct NowPlayingScreen: View { } private func controls(_ track: Track, wide: Bool, width: CGFloat) -> some View { - // Folded with a panel open, the controls give the panel some of their spacing. - let snug = folded && panel != .Art + // Folded, the controls keep the tight stems-panel spacing on every panel, so the art gets the room. + let snug = folded let pm = g.playback let c = tint.map { base.tinted($0) } ?? base let pad: CGFloat = wide && tight ? 14 : hPad @@ -235,7 +236,7 @@ struct NowPlayingScreen: View { Spacer(minLength: 8) EllipsisButton(items: ui.menu.track(track)) } - .padding(.top, tight ? 8 : 14) + .padding(.top, tight || snug ? 8 : 14) .transition(.opacity.combined(with: .move(edge: .top))) } ProgressVolumeBar(played: c.label, unplayed: c.label3, centerLabel: badge(track)) @@ -742,7 +743,8 @@ private struct MixerPanel: View { // Spread spare height across the stem rows instead of leaving it all at the bottom. let count = CGFloat(max(names.count, 1)) // Rows shrink to fit every stem before anything has to scroll (the folded outer display is short). - let rowH = roomy ? min(80, max(Self.roomyMin, (geo.size.height - Self.roomyChrome) / count)) + // Roomy (the unfolded deck), the rows share every point under the chips down to the bottom. + let rowH = roomy ? max(Self.roomyMin, (geo.size.height - chipsH - 8) / count) : min(62, max(spread ? Self.foldedMin : Self.compactMin, (geo.size.height - chipsH - 8) / count)) // Gap above the rows that centres them on the whole panel, not just the space under the chips. let lead = max(0, (geo.size.height - rowH * count) / 2 - chipsH) @@ -760,7 +762,7 @@ private struct MixerPanel: View { HStack(spacing: 8) { saveChips(pm); presetChips(pm, names) }.padding(.horizontal, 24) } .scrollIndicators(.hidden) - .padding(.horizontal, -24) + .padding(.leading, -24).padding(.trailing, roomy ? -6 : -24) .padding(.vertical, 8) .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { chipsH = $0 } } @@ -774,13 +776,11 @@ private struct MixerPanel: View { StemFader(name: name, setting: pm.mix[name] ?? StemSetting(), level: i < levels.count ? levels[i] : 0, enabled: stems, height: rowH, roomy: roomy) } } - // Wide panes keep the faders a sensible length, centred across the panel. - .frame(maxWidth: roomy ? 560 : .infinity) - .frame(maxWidth: .infinity) } Spacer(minLength: 8) } - .padding(.horizontal, 24) + // Roomy, the faders run right up to the hinge. + .padding(.leading, 24).padding(.trailing, roomy ? 6 : 24) .frame(minHeight: geo.size.height) } .scrollIndicators(.hidden) @@ -845,7 +845,7 @@ extension MixerPanel { static let roomyRow: CGFloat = 66 /// Shortest stacked row: name line, fader and the gap under it. - static let roomyMin: CGFloat = 60 + static let roomyMin: CGFloat = 68 /// Shortest side-by-side row, the fader's own height. static let compactMin: CGFloat = 30 static let foldedMin: CGFloat = 40 @@ -921,7 +921,7 @@ struct FaderRow: View { var body: some View { if stacked { // Bottom-aligned with a gap under, so each name sits clear of the meter above it. - VStack(alignment: .leading, spacing: 2) { + VStack(alignment: .leading, spacing: 6) { HStack(spacing: 6) { if let dot { Circle().fill(dot).frame(width: 8, height: 8) } Text(label).font(.subheadline.weight(.semibold)).foregroundStyle(dim ? p.label2 : p.label).lineLimit(1) @@ -931,8 +931,8 @@ struct FaderRow: View { .frame(height: 18) HStack(spacing: 8) { fader; trailing } } - .padding(.bottom, 4) - .frame(height: height, alignment: .bottom) + // Centred in its slot, so tall rows keep even gaps above and below. + .frame(height: height) } else { row } diff --git a/ios/project.yml b/ios/project.yml index 3c75926..066d5eb 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -7,9 +7,9 @@ settings: base: SWIFT_VERSION: "5.0" # iOS needs a plain number for the bundle version; the label is what the app and releases show. - MARKETING_VERSION: "0.9.0" - VERSION_LABEL: "0.9.0" - CURRENT_PROJECT_VERSION: "31" + MARKETING_VERSION: "0.10.0" + VERSION_LABEL: "0.10.0" + CURRENT_PROJECT_VERSION: "40" # Dev builds override these (build-ipa.sh dev) so they install next to the release app. APP_ID: org.cdnutter.stemify APP_NAME: Stemify diff --git a/ios/scripts/make-icon.py b/ios/scripts/make-icon.py new file mode 100644 index 0000000..24032ef --- /dev/null +++ b/ios/scripts/make-icon.py @@ -0,0 +1,101 @@ +"""Run from a venv with resvg-py and pillow: python make-icon.py OUTDIR +Stemify app icon: six stem-colored capsules (the app's stem palette) glowing on a deep night background. +Usage: make.py OUTDIR -> icon.png, icon-dev.png, icon-dev-dark.png, icon-dev-tinted.png""" +import io, sys +import resvg_py +from PIL import Image + +S = 1024 +# vocals, drums, bass, guitar, piano, other (PlaybackManager stem colors) +STEMS = [0xFF7AB6, 0xFFB547, 0x7C8CFF, 0xFF8A5C, 0xB48CFF, 0x4CD07D] +HEIGHTS = [300, 510, 390, 620, 455, 330] +W, GAP = 78, 30 + + +def hx(c): return f"#{c:06X}" +def mix(c, t, k): + a = [(c >> s) & 255 for s in (16, 8, 0)]; b = [(t >> s) & 255 for s in (16, 8, 0)] + return "#" + "".join(f"{round(x + (y - x) * k):02X}" for x, y in zip(a, b)) + + +def svg(mode="color", sash=False): + tint = mode == "tinted" + total = len(STEMS) * W + (len(STEMS) - 1) * GAP + x0 = (S - total) / 2 + cy = S / 2 + 6 + defs, glow, bars, shine = [], [], [], [] + for i, (c, h) in enumerate(zip(STEMS, HEIGHTS)): + if tint: c = 0xFFFFFF + x, y = x0 + i * (W + GAP), cy - h / 2 + defs.append(f'' + f'' + f'' + f'') + r = W / 2 + glow.append(f'') + bars.append(f'') + # glassy highlight down the left edge + shine.append(f'') + + if tint: + bg = '' + aura = "" + else: + bg = ('' + '' + '' + '') + # soft colored light pooling behind the bars + aura = ('' + f'' + f'' + f'' + f'' + f'' + '') + + vignette = ('' + '' + '') if not tint else "" + + sash_svg = "" + if sash: + sash_svg = ('' + '' + '' + '' + '' + '' + 'dev' + 'dev' + '') + + return f''' +{"".join(defs)} + + + + +{bg}{aura} +{"".join(glow)} +{"".join(g.replace('fill="#', 'fill="#000" data-c="') for g in glow)} +{"".join(bars)} +{"".join(shine)} +{vignette}{sash_svg} +''' + + +def png(s, path, gray=False): + im = Image.open(io.BytesIO(bytes(resvg_py.svg_to_bytes(svg_string=s)))).convert("RGB") + (im.convert("L") if gray else im).save(path, optimize=True) + + +out = sys.argv[1] +png(svg(), f"{out}/icon.png") +png(svg(sash=True), f"{out}/icon-dev.png") +png(svg(sash=True), f"{out}/icon-dev-dark.png") +png(svg("tinted", sash=True), f"{out}/icon-dev-tinted.png", gray=True) +open(f"{out}/icon.svg", "w").write(svg()) diff --git a/server/stemserve.py b/server/stemserve.py index 4ec6e35..b926cce 100644 --- a/server/stemserve.py +++ b/server/stemserve.py @@ -30,6 +30,7 @@ import glob import hashlib import json import operator +import re import os import shutil import signal @@ -63,6 +64,35 @@ PEAK_RATE = 2000 # Hz the envelope is computed at; plenty for a few hundred bar CHUNK = 1 << 20 # The web player. Served without the token; it asks for one in its settings when TOKEN is set. WEB_DIR = os.path.realpath(os.environ.get("WEB_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "web"))) + + +# Web player build stamp: changes whenever any file in web/ does. +_web_cache = {} + + +def web_version(): + try: + sig = sorted((e.name, e.stat().st_mtime_ns, e.stat().st_size) for e in os.scandir(WEB_DIR) if e.is_file()) + except OSError: + return "0" + return hashlib.sha1(repr(sig).encode()).hexdigest()[:10] + + +def web_file(full, ver): + """File body with local asset URLs stamped with ?v=ver (html and js), and its ETag.""" + hit = _web_cache.get(full) + if hit and hit[0] == ver: + return hit[1], hit[2] + with open(full, "rb") as f: + body = f.read() + ext = os.path.splitext(full)[1] + if ext == ".html": + body = re.sub(rb'((?:src|href)="(?:\./)?[\w-]+\.(?:js|css))"', rb'\1?v=' + ver.encode() + rb'"', body) + elif ext == ".js": + body = re.sub(rb'((?:from |import\()"\./[\w-]+\.js)"', rb'\1?v=' + ver.encode() + rb'"', body) + etag = '"%s-%s"' % (ver, hashlib.sha1(body).hexdigest()[:8]) + _web_cache[full] = (ver, body, etag) + return body, etag WEB_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".json": "application/json"} @@ -315,7 +345,9 @@ class Handler(BaseHTTPRequestHandler): def _error(self, status, msg): self._send(status, json.dumps({"error": msg}).encode()) - def _web(self, path): + def _web(self, path, query=""): + """The web player. index.html and the modules point at ?v= URLs, so a new + build is picked up on a plain reload and the versioned files cache for good.""" if not SERVE_WEB: return self._error(404, "not found") if path == "/": @@ -323,10 +355,16 @@ class Handler(BaseHTTPRequestHandler): full = os.path.realpath(os.path.join(WEB_DIR, path.lstrip("/"))) if not full.startswith(WEB_DIR + os.sep) or not os.path.isfile(full): return self._error(404, "not found") - with open(full, "rb") as f: - body = f.read() + ver = web_version() + body, etag = web_file(full, ver) ctype = WEB_TYPES.get(os.path.splitext(full)[1], "application/octet-stream") - self._send(200, body, ctype, {"Cache-Control": "no-cache"}) + if "v=" + ver in query.split("&"): + cache = "public, max-age=31536000, immutable" + else: + cache = "no-cache" + if self.headers.get("If-None-Match") == etag: + return self._send(304, b"", ctype, {"Cache-Control": cache, "ETag": etag}) + self._send(200, body, ctype, {"Cache-Control": cache, "ETag": etag}) def do_HEAD(self): self.do_GET() @@ -341,7 +379,7 @@ class Handler(BaseHTTPRequestHandler): if path.startswith("/plex/") and PLEX_URL: return self._plex_proxy(path[len("/plex"):], url.query, query) if not path.startswith(("/api/", "/file/")): - return self._web(path) + return self._web(path, url.query) if not self._authorized(query): return self._error(HTTPStatus.UNAUTHORIZED, "bad token") try: diff --git a/web/app.js b/web/app.js index 78c885d..9c89678 100644 --- a/web/app.js +++ b/web/app.js @@ -3,7 +3,7 @@ import { $, $$, esc, fmtTime, fmtBytes, plural, on, emit, toast, ICON, store, uuid } from "./util.js"; import { S, save, songMixes, saveSongMix, forgetSongMix, playlists, savePlaylists, newPlaylist, addToPlaylist, Offline } from "./store.js"; -import { px, img, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything } from "./plex.js"; +import { px, img, rawImg, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything } from "./plex.js"; import { Stems, Live, stemNow, stemTrack, stemBase, api } from "./stems.js"; import { E, Q, setting, stemGain, presets, allPresets, presetLabel, applyPreset, currentPreset, nextPreset, savePreset, deletePreset, movePreset, restorePresets, deleteAllCustom, toggleLock, mixChanged, setKaraoke, setKaraokeMode, sameMix, setSpeed, saveQueue, saveOffline, Radio } from "./player.js"; @@ -15,6 +15,7 @@ const view = $("#view"); // ---- appearance ------------------------------------------------------------------------------- const THEMES = { + graphite: { bg: "#181819", panel: "#101010", raised: "#262628", line: "#2b2b2e", text: "#e7e7e7", muted: "#a8a8a8", accent: "#3a81ed" }, amber: { bg: "#0d0e12", panel: "#15171d", raised: "#1d2028", line: "#262a33", text: "#eceef3", muted: "#8a8f9c", accent: "#f2b544" }, ocean: { bg: "#0a1018", panel: "#101a26", raised: "#172434", line: "#1f2f42", text: "#e6eef7", muted: "#8698ad", accent: "#4cc2ff" }, rose: { bg: "#120c10", panel: "#1b1218", raised: "#251922", line: "#33222e", text: "#f5e9f0", muted: "#a48b99", accent: "#ff6f9f" }, @@ -28,7 +29,7 @@ const inkFor = hex => { return l > 0.6 ? "#141414" : "#ffffff"; }; function applyTheme() { - const t = THEMES[S.theme] || THEMES.amber, a = S.accent || t.accent; + const t = THEMES[S.theme] || THEMES.graphite, a = S.accent || t.accent; $("#theme").textContent = `:root{--bg:${t.bg};--panel:${t.panel};--raised:${t.raised};--line:${t.line};--text:${t.text};--muted:${t.muted};` + `--accent:${a};--accent-ink:${inkFor(a)};--glass:${t.panel}ee;--hover:${t.text}0d;--shadow:${t.light ? "#0003" : "#0009"};` + `--wave:${t.text}44;--wave-ghost:${t.text}14;color-scheme:${t.light ? "light" : "dark"}}`; @@ -147,6 +148,22 @@ let drawer = null; // "mixer" | "lyrics" | "queue" const Lyr = { id: null, data: null, idx: -1 }; const artOf = (t, size) => t?.srv ? img(t.srv, t.thumb, size) : ""; +// Feishin-style big art at the foot of the sidebar, opened from the art in the player bar. +const wide = matchMedia("(min-width: 861px)"); +const SideArt = { + src: "", + show(on) { S.sideArt = on; save(); this.fill(); }, + fill() { + const t = Radio.station ? null : Q.cur(), src = artOf(t, 640), on = !!(S.sideArt && src && wide.matches); + $("#app").classList.toggle("sideart", on); + $("#player").classList.toggle("sideart", on); + if (!on || src === this.src) return; + // Swap only once the new art has decoded, so it never flashes empty between tracks. + this.src = src; + const im = new Image(); im.src = src; + im.decode().catch(() => {}).then(() => { if (this.src === src) $("#sideart img").src = src; }); + }, +}; const UI = { all() { this.track(); this.transport(); this.progress(); this.drawer(); marks(); }, track() { @@ -157,6 +174,7 @@ const UI = { $("#np-title").textContent = st.name; $("#np-sub").textContent = "Web Radio"; $("#np-art").removeAttribute("src"); + $("#b-art").hidden = true; SideArt.fill(); document.title = `${st.name} · Stemify`; if ("mediaSession" in navigator) navigator.mediaSession.metadata = new MediaMetadata({ title: st.name, artist: "Web Radio" }); return; @@ -167,6 +185,7 @@ const UI = { $("#np-sub").textContent = t ? [t.artist, t.album].filter(Boolean).join(" · ") : ""; const art = artOf(t, 120); if (art) $("#np-art").src = art; else $("#np-art").removeAttribute("src"); + $("#b-art").hidden = !art; SideArt.fill(); document.title = t ? `${t.title} · Stemify` : "Stemify"; if ("mediaSession" in navigator) { navigator.mediaSession.metadata = t ? new MediaMetadata({ @@ -188,6 +207,7 @@ const UI = { for (const d of ["mixer", "lyrics", "queue"]) $(`#b-${d}`).classList.toggle("on", drawer === d); $("#b-mixer").classList.toggle("dot", S.karaoke); if ("mediaSession" in navigator) navigator.mediaSession.playbackState = playing ? "playing" : "paused"; + if (drawer === "mixer") Meter.start(); }, progress() { $("#t-pos").textContent = E.loading ? `${Math.round(E.loadFrac * 100)}%` : fmtTime(E.position()); @@ -207,6 +227,7 @@ const UI = { d.innerHTML = tabs + `
${drawer === "mixer" ? mixerHtml() : drawer === "queue" ? queueHtml() : lyricsShell()}
`; if (drawer === "lyrics") loadLyrics(); if (drawer === "queue") $(".q-item.cur", d)?.scrollIntoView({ block: "center" }); + d.classList.toggle("mixing", drawer === "mixer"); } this.transport(); }, @@ -219,29 +240,91 @@ const karaokeHtml = () => `
${[["off", "No vocals"], ["soft", "Soft vocals"], ["on", "Vocals on"]].map(([m, l]) => ``).join("")}
${S.karaokeMode === "soft" ? `` : ""}
`; +// Stem colours match the iOS app. +const STEM_COLORS = { vocals: "#ff7ab6", drums: "#ffb547", bass: "#7c8cff", other: "#4cd07d", guitar: "#ff8a5c", piano: "#b48cff", instrumental: "#3dd6c6" }; +const pct = v => Math.round(v * 100) + "%"; +function presetsHtml(names) { + const cur = currentPreset(names), lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset); + return presets().map(p => ``).join("") + ``; +} +function mixFoot(names) { + const saved = songMixes[E.entry.key], same = saved && sameMix(saved, S.mix, names); + return `
+ + + ${saved ? `` : ""} +
`; +} function mixerHtml() { const names = mixNames(); - if (!names.length) return `

${E.loading ? "Loading stems…" : Q.cur() ? "This track has no stems yet. Right-click it and pick Stem Now." : "Play something with stems to mix it."}

`; - const cur = currentPreset(names), key = E.entry.key, saved = songMixes[key]; - const lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset); - const savedNote = saved ? (sameMix(saved, S.mix, names) ? "Using this song's saved mix." : "Changed from this song's saved mix.") : ""; - return karaokeHtml() + ` -
${presets().map(p => ``).join("")}
- ${names.map(n => { - const s = setting(n), g = stemGain(n, names); - return `
${esc(n)} - - -
`; - }).join("")} -
- - ${saved ? `` : ""} - -
-

${savedNote} ${S.karaoke ? "Karaoke is on, so saved mixes are ignored until you turn it off." : lock ? `${esc(presetLabel(lock.name))} is locked, so every song starts with it. Long press it to unlock.` - : (S.keepMix ? "Songs without a saved mix keep this mix." : "Songs without a saved mix start at full mix.") + " Long press a preset to lock it."}

`; + if (!names.length) return `

${E.loading ? "Loading stems…" : Q.cur() ? "No stems for this track." : "Nothing playing."}

`; + return `
+
${presetsHtml(names)}
+
${names.map(n => { + const s = setting(n); + return `
+
${pct(s.level)}
+
+
+
${esc(n)}
+
`; + }).join("")}
+
${mixFoot(names)}
`; +} +// Updates the open mixer in place, so taps answer at once and the slider being dragged keeps +// its grip. False when the stems changed and it needs a full render. +function syncMixer() { + const box = $("#mixer"), names = mixNames(); + if (!box || box.dataset.names !== names.join(",")) return false; + const presetBox = box.querySelector(".presets"), html = presetsHtml(names); + if (presetBox.innerHTML !== html) presetBox.innerHTML = html; + for (const row of box.querySelectorAll(".stem")) { + const n = row.dataset.stem, st = setting(n); + row.classList.toggle("silent", !stemGain(n, names)); + row.classList.toggle("muted", !!st.muted); + row.querySelector(".mute").classList.toggle("on", !!st.muted); + row.querySelector(".solo").classList.toggle("on", !!st.solo); + paintFader(row.querySelector(".fader"), st.level); + } + box.querySelector("#mixfoot").innerHTML = mixFoot(names); + return true; +} + +const paintFader = (f, v) => { + if (f.style.getPropertyValue("--v") === String(v)) return; + f.style.setProperty("--v", v); f.setAttribute("aria-valuenow", Math.round(v * 100)); f.parentNode.querySelector(".pct").textContent = pct(v); +}; +// Live meters: each stem's bar rises and falls with its audio (pre-fader peak, shown under the +// fader's level like the iOS mixer). Runs on animation frames only while the mixer is open and +// playing or still falling, and writes nothing but transforms. +const Meter = { + raf: 0, rows: null, box: null, shown: new Map(), + start() { if (!this.raf) this.raf = requestAnimationFrame(this.tick); }, + tick: () => { + const M = Meter, box = $("#mixer"); + M.raf = 0; + if (!box || drawer !== "mixer" || document.hidden) return; + if (M.box !== box) { M.box = box; M.rows = [...box.querySelectorAll(".stem")].map(r => ({ n: r.dataset.stem, el: r.querySelector(".mtr") })); M.shown.clear(); } + const playing = E.playing && !E.buffering, names = mixNames(); + let moving = false; + for (const r of M.rows) { + const st = setting(r.n), live = playing && stemGain(r.n, names) ? E.meter(r.n) * st.level : 0; + const prev = M.shown.get(r.n) || 0, v = live >= prev ? live : Math.max(live, prev - 0.025); + if (Math.abs(v - prev) > 0.002 || (v === 0 && prev !== 0)) { r.el.style.transform = `scaleY(${v.toFixed(3)})`; M.shown.set(r.n, v); } + if (v > 0) moving = true; + } + if (playing || moving) M.start(); + }, +}; +// Sets a stem's level live; the save and mixer refresh wait until the gesture settles. +let levelSave = 0; +function setLevel(n, v) { + v = Math.round(Math.max(0, Math.min(1, v)) * 100) / 100; + if (setting(n).level === v) return; + S.mix[n] = { ...setting(n), level: v }; E.applyGains(); Wave.draw(); + const f = $(`#mixer .fader[data-fader="${CSS.escape(n)}"]`); if (f) paintFader(f, v); + clearTimeout(levelSave); levelSave = setTimeout(() => { save(); syncMixer(); }, 250); } function queueHtml() { @@ -292,21 +375,60 @@ d$.addEventListener("click", ev => { else if (ds.solo) { S.mix[ds.solo] = { ...setting(ds.solo), solo: !setting(ds.solo).solo }; mixChanged(); } else if ("kara" in ds) setKaraoke(!S.karaoke); else if (ds.kmode) setKaraokeMode(ds.kmode); - else if ("savemix" in ds) { saveSongMix(E.entry.key, S.mix); toast("Saved the mix for this song"); UI.drawer(); } - else if ("forgetmix" in ds) { forgetSongMix(E.entry.key); UI.drawer(); } + else if ("savemix" in ds) { saveSongMix(E.entry.key, S.mix); toast("Saved the mix for this song"); syncMixer() || UI.drawer(); } + else if ("forgetmix" in ds) { forgetSongMix(E.entry.key); syncMixer() || UI.drawer(); } else if ("mixtopl" in ds) { const r = b.getBoundingClientRect(); pickPlaylist(r.left, r.bottom, [Q.cur()], S.mix); } else if ("qclear" in ds) Q.clear(); else if (ds.qx) Q.remove(+ds.qx); else if (ds.q) Q.jump(+ds.q); else if (ds.li) E.seek(Lyr.data.lines[+ds.li].t); }); +// Faders: vertical. Grabbing the cap (or any touch) moves it from where it is; a mouse press +// elsewhere on the track jumps there first. Touches never scroll the drawer from a fader. +{ + let drag = null; + const span = r => r.height - 8, val = (r, y) => (r.bottom - 4 - y) / span(r); + d$.addEventListener("pointerdown", ev => { + const f = ev.target.closest(".fader"); + if (!f || ev.button) return; + ev.preventDefault(); + const n = f.dataset.fader, r = f.getBoundingClientRect(), v = setting(n).level; + const onCap = Math.abs(ev.clientY - (r.bottom - 4 - v * span(r))) < 14; + drag = { f, n, id: ev.pointerId, y0: ev.clientY, v0: v, r, rel: onCap || ev.pointerType !== "mouse" }; + f.setPointerCapture(ev.pointerId); f.classList.add("drag"); + if (!drag.rel) setLevel(n, val(r, ev.clientY)); + }); + d$.addEventListener("pointermove", ev => { + if (!drag || ev.pointerId !== drag.id) return; + setLevel(drag.n, drag.rel ? drag.v0 + (drag.y0 - ev.clientY) / span(drag.r) : val(drag.r, ev.clientY)); + }); + const end = ev => { + if (!drag || ev.pointerId !== drag.id) return; + drag.f.classList.remove("drag"); drag = null; + }; + d$.addEventListener("pointerup", end); + d$.addEventListener("pointercancel", end); + d$.addEventListener("dblclick", ev => { const f = ev.target.closest(".fader"); if (f) setLevel(f.dataset.fader, 1); }); + d$.addEventListener("wheel", ev => { + const f = ev.target.closest(".fader"); + if (!f) return; + ev.preventDefault(); + setLevel(f.dataset.fader, setting(f.dataset.fader).level - Math.sign(ev.deltaY || ev.deltaX) * 0.02); + }, { passive: false }); + d$.addEventListener("keydown", ev => { + const f = ev.target.closest(".fader"); + if (!f) return; + const n = f.dataset.fader, v = setting(n).level, step = ev.shiftKey ? 0.1 : 0.02; + const to = { ArrowRight: v + step, ArrowUp: v + step, ArrowLeft: v - step, ArrowDown: v - step, Home: 0, End: 1 }[ev.key]; + if (to == null) return; + ev.preventDefault(); ev.stopPropagation(); setLevel(n, to); + }); +} d$.addEventListener("input", ev => { const ds = ev.target.dataset; - if (ds.level) { S.mix[ds.level] = { ...setting(ds.level), level: +ev.target.value }; E.applyGains(); Wave.draw(); save(); } if (ds.softdb) $("#softdb").textContent = ev.target.value + " dB"; }); d$.addEventListener("change", ev => { - if (ev.target.dataset.level) UI.drawer(); if (ev.target.dataset.softdb) setKaraokeMode("soft", +ev.target.value); }); // Long press (or right-click) a preset chip to lock it. @@ -373,6 +495,10 @@ function applyBar() { $("#speed").style.display = S.bar.speed ? "" : "none"; for (const k of ["mixer", "lyrics", "queue"]) $(`#b-${k}`).style.display = S.bar[k] ? "" : "none"; } +$("#b-art").onclick = ev => { if (wide.matches) { ev.stopPropagation(); SideArt.show(true); } }; +$("#sideart .sa-col").onclick = () => SideArt.show(false); +$("#sideart .sa-img").onclick = () => { const t = Q.cur(); if (t?.albumKey) location.hash = `#/album/${t.srv}:${t.albumKey}`; }; +wide.addEventListener("change", () => SideArt.fill()); $(".np").onclick = () => { const t = Q.cur(); if (t?.albumKey) location.hash = `#/album/${t.srv}:${t.albumKey}`; }; if ("mediaSession" in navigator) { @@ -420,21 +546,24 @@ on("queue", () => { if (drawer === "queue") UI.drawer(); }); on("radio", () => { UI.track(); UI.transport(); const el = $("#stations"); if (el) el.innerHTML = stationsHtml(); }); on("mix", () => { Wave.draw(); UI.transport(); - if (drawer === "mixer") UI.drawer(); + if (drawer === "mixer") syncMixer() || UI.drawer(); else if (drawer === "lyrics" && $("#lyrhead")) $("#lyrhead").innerHTML = mixNames().includes("vocals") ? karaokeHtml() : ""; }); // ---- live stem status --------------------------------------------------------------------------- const base = p => (p || "").split("/").pop().replace(/\.[^.]+$/, ""); +// Stems are the norm, so only songs without them get a tag (once the index has loaded). const badge = t => { - if (Stems.find(t)) return 'STEMS'; + if (Stems.find(t)) return ""; const s = Live.state(t); - return s ? `${{ queued: "QUEUED", stemming: "STEMMING", failed: "FAILED" }[s]}` : ""; + if (s) return `${{ queued: "QUEUED", stemming: "STEMMING", failed: "FAILED" }[s]}`; + return Stems.entries.length ? 'NO STEMS' : ""; }; // Refreshes playing, stem and download markers in whatever is on screen. function marks() { const id = Q.cur()?.id; + document.body.classList.toggle("stems-ready", Stems.entries.length > 0); for (const r of $$("tr[data-list]", view)) { const t = lists[r.dataset.list]?.[+r.dataset.i]; if (!t) continue; @@ -549,11 +678,19 @@ function playFrom(listId, i) { Q.playList(vis.includes(pick) ? vis : all, Math.max(0, (vis.includes(pick) ? vis : all).indexOf(pick)), false); } -function card({ href, img: src, t, s = "", round, kind, srv, key }) { +// A broken image tries its fallback (data-fb) once, then shows the placeholder. +const FB = `onerror="if(this.dataset.fb){this.src=this.dataset.fb;this.dataset.fb=''}else{this.onerror=null;this.src='data:image/gif;base64,R0lGODlhAQABAAAAACw='}"`; +function card({ href, img: src, fb, t, s = "", round, kind, srv, key }) { const nk = kind === "album" || kind === "artist" ? nameKey(t) : ""; const hide = nk && !stemSets()[kind].has(nk); return ` - ${src ? `` : `
`}
${esc(t)}
${esc(s)}
`; +
${src ? `` : `
`}${kind ? `` : ""}
${esc(t)}
${esc(s)}
`; +} +// Tracks behind a card, for its play button and right-click menu. +async function cardTracks(c) { + const { kind, srv, key } = c.dataset; + if (kind === "playlist") return ((await px(srv, `/playlists/${key}/items`)).Metadata || []).map(m => track(srv, m)); + return leaves(srv, key); } const albumCard = m => card({ href: `#/album/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, s: [m.parentTitle, m.year].filter(Boolean).join(" · "), kind: "album", srv: m._srv, key: m.ratingKey }); const artistCard = m => card({ href: `#/artist/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, round: true, kind: "artist", srv: m._srv, key: m.ratingKey }); @@ -561,15 +698,18 @@ const artistCard = m => card({ href: `#/artist/${m._srv}:${m.ratingKey}`, img: i const rowHtml = (listId, t, i, { numbers, album = true, mix } = {}) => ` ${numbers ? t.index ?? i + 1 : i + 1} - ${esc(t.title)}${badge(t)}${mix ? 'MIX' : ""}${album ? `${esc([t.artist, t.album].filter(Boolean).join(" · "))}` : ""} +
${esc(t.title)}${badge(t)}${mix ? 'MIX' : ""}
${esc(t.artist || "")} + ${album ? `${esc(t.album || "")}` : ""} ${Offline.has(t.id) ? ICON.download : ""} ${fmtTime(t.duration / 1000)} `; +const CLOCK = ''; +const thead = (album = true) => `#Title${album ? 'Album' : ""}${CLOCK}`; function trackTable(listId, tracks, opts = {}) { lists[listId] = tracks; if (!tracks.length) return `

Nothing here.

`; - return `${tracks.map((t, i) => rowHtml(listId, t, i, { ...opts, mix: listItems[listId]?.[i]?.mix })).join("")}
+ return `${thead(opts.album)}${tracks.map((t, i) => rowHtml(listId, t, i, { ...opts, mix: listItems[listId]?.[i]?.mix })).join("")}

None of these have stems yet.

All of these have stems.

`; } @@ -584,12 +724,13 @@ function sortControl(screen) { const bar = (title, { sort, filter = true, extra = "" } = {}) => `

${esc(title)}

${extra}${filter ? stemsChip() : ""}${sort ? sortControl(sort) : ""}
`; const actions = id => `
- - + + -
`; -const hero = (src, kind, title, sub, id, round) => `
${src ? `` : `
`} -
${kind}

${esc(title)}

${sub}
${id ? actions(id) : ""}
`; + `; +const hero = (src, kind, title, sub, id, round, fb) => `
${src ? `
` : ""} +
${src ? `` : `
`} +
${kind}

${esc(title)}

${sub}
${id ? actions(id) : ""}`; function needPlex() { view.innerHTML = `

Welcome

Add a Plex server in Settings to browse your library, or browse the stems on their own.

`; @@ -684,7 +825,7 @@ const stationsHtml = () => S.stations.length ? `
${S.sta return `
${esc(st.name)}${esc(st.url)}
`; -}).join("")}
` : `

No stations yet. Add one with its stream URL.

`; +}).join("")}` : `

No stations yet.

`; const routes = { async home(my) { @@ -717,8 +858,7 @@ const routes = {

Add a station

-
-

Any stream the browser can play, like MP3, AAC or Ogg. Playing a station pauses the queue, and playing the queue stops the station.

`; +
`; }, async albums(my) { const srcs = sources(); @@ -736,7 +876,7 @@ const routes = { const srcs = sources(); if (!srcs.length) return needPlex(); view.innerHTML = bar("Songs", { sort: "songs", extra: `` }) - + `

No songs with stems loaded yet. Scroll for more.

Every song loaded so far has stems. Scroll for more.

`; + + `${thead()}

No songs with stems yet.

Every song has stems.

`; lists.songs = []; const size = S.stemFilter ? 1000 : 150; await paged(my, $("tbody", view), new Pager(srcs, secPath, { type: 10, sort: sortState("songs").param }, size), size, (ms, off) => { @@ -768,14 +908,15 @@ const routes = { view.innerHTML = bar("Playlists", { sort: "playlists", filter: false }) + `

Stem playlists

` + (playlists.length ? `
${playlists.map(p => card({ href: `#/stemplaylist/${p.id}`, img: artOf(p.items[0]?.track, 300), t: p.title, s: plural(p.items.length, "track") })).join("")}
` - : `

Stem playlists remember a mix for each song. Right-click any song to add it.

`) + : `

No stem playlists.

`) + `

Plex playlists

${liveServers().length ? "Loading…" : "No Plex server set up."}

`; if (!liveServers().length) return; let pls = await everything(liveServers().map(srv => ({ srv })), "/playlists", { playlistType: "audio" }); if (my !== seq) return; pls = st.random ? pls.sort(() => Math.random() - 0.5) : pls.sort(comparator(st.param)); count(pls.length + playlists.length, "playlist"); - $("#plexpl").innerHTML = pls.length ? `
${pls.map(p => card({ href: `#/playlist/${p._srv}:${p.ratingKey}`, img: img(p._srv, p.composite || p.thumb), t: p.title, s: plural(p.leafCount || 0, "track") })).join("")}
` + + $("#plexpl").innerHTML = pls.length ? `
${pls.map(p => card({ href: `#/playlist/${p._srv}:${p.ratingKey}`, img: img(p._srv, p.thumb || p.composite), fb: p.composite && rawImg(p._srv, p.composite), t: p.title, s: plural(p.leafCount || 0, "track"), kind: "playlist", srv: p._srv, key: p.ratingKey })).join("")}
` : `

No music playlists.

`; }, async album(my, arg) { @@ -805,7 +946,7 @@ const routes = { const [info, items] = await Promise.all([px(srv, `/playlists/${key}`), px(srv, `/playlists/${key}/items`)]); if (my !== seq) return; const p = info.Metadata?.[0] || {}, tracks = sortTracks((items.Metadata || []).map(m => track(srv, m)), sortState("playlist")); - view.innerHTML = hero(img(srv, p.composite || p.thumb, 420), "Playlist", p.title, plural(tracks.length, "track"), "playlist") + view.innerHTML = hero(img(srv, p.thumb || p.composite, 420), "Playlist", p.title, plural(tracks.length, "track"), "playlist", false, p.composite && rawImg(srv, p.composite, 420)) + `
${stemsChip()}${sortControl("playlist")}
` + trackTable("playlist", tracks); }, async stemplaylist(my, id) { @@ -840,7 +981,7 @@ const routes = { view.innerHTML = bar("Downloads", { filter: false, extra: recs.length ? `` : "" }) + `

${plural(recs.length, "track")}, ${fmtBytes(total)} stored in this browser${est?.quota ? ` (${fmtBytes(est.usage)} of ${fmtBytes(est.quota)} used)` : ""}. Downloads play without the network. ${isSecureContext ? "" : "This page isn't on HTTPS, so the browser may clear them when space runs low."}

` - + (recs.length ? dlGroups(recs) : `

Nothing downloaded. Right-click a song or album and pick Download for offline.

`); + + (recs.length ? dlGroups(recs) : `

Nothing downloaded.

`); count(recs.length, "track"); }, async stems(my) { @@ -852,7 +993,7 @@ const routes = { const f = $("#sf").value.toLowerCase(); const hits = f ? all.filter(t => t.stem.key.toLowerCase().includes(f)) : all; $("#sl").innerHTML = (hits.length ? trackTable("stems", hits.slice(0, 400)) : `

${Stems.ok ? "No matches." : "Can't reach stemserve. Check Settings."}

`) - + (hits.length > 400 ? `

Showing 400 of ${hits.length}. Filter to narrow it down.

` : ""); + + (hits.length > 400 ? `

400 of ${hits.length}

` : ""); }; $("#sf").oninput = render; render(); @@ -884,6 +1025,11 @@ view.addEventListener("click", async ev => { const el = ev.target.closest("button, tr[data-list]"); if (!el) return; const ds = el.dataset, row = ev.target.closest("tr[data-list]"); + if ("cardplay" in ds) { + ev.preventDefault(); + const ts = await cardTracks(el.closest(".card")); + return ts.length ? Q.playList(ts, 0, false) : toast("Nothing to play"); + } if (ds.stemfilter) { S.stemFilter = S.stemFilter === ds.stemfilter ? "" : ds.stemfilter; save(); applyStemFilter(); return; } if ("sortdir" in ds) { pickSort(ds.sortdir, sortState(ds.sortdir).i); return route(); } if ("reshuffle" in ds) return route(); @@ -950,7 +1096,7 @@ view.addEventListener("change", ev => { view.addEventListener("contextmenu", ev => { const row = ev.target.closest("tr[data-list]"), c = ev.target.closest(".card[data-kind]"); if (row) { ev.preventDefault(); trackMenu(ev.clientX, ev.clientY, row.dataset.list, +row.dataset.i); } - else if (c) { ev.preventDefault(); listMenu(ev.clientX, ev.clientY, () => leaves(c.dataset.srv, c.dataset.key), { title: $(".t", c).textContent, href: c.getAttribute("href") }); } + else if (c) { ev.preventDefault(); listMenu(ev.clientX, ev.clientY, () => cardTracks(c), { title: $(".t", c).textContent, href: c.getAttribute("href") }); } }); // ---- settings ----------------------------------------------------------------------------------- @@ -963,7 +1109,6 @@ function presetEditor() { const ps = presets(), lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset); return `

Locked

${lock ? `
${ICON.lock}${esc(presetLabel(lock.name))}
` : `

Nothing locked.

`} -

Every song starts with this mix, whether or not Keep Stem Mix Between Songs is on. Long press a preset in the mixer to lock or unlock it.

Mixer Bar

${ps.map((p, i) => `
${esc(presetLabel(p.name))}${p.custom ? ' CUSTOM' : ""} @@ -989,10 +1134,9 @@ function serverHtml(srv) { } function renderSettings() { - const theme = THEMES[S.theme] || THEMES.amber; + const theme = THEMES[S.theme] || THEMES.graphite; view.innerHTML = `

Plex

-

Turn on the music libraries you want. Everything that's on is browsed as one library.

${S.servers.map(serverHtml).join("") || `

No servers yet.

`}
Add a server by URL and token
@@ -1008,19 +1152,15 @@ function renderSettings() {

Stems

-

Stems are downloaded whole before a song starts. Opus 160 is about 1 MB per stem-minute; FLAC is around eight times that.

-

How many upcoming songs load their stems in the background. Each one is held in memory, so keep it low on phones. FLAC loads one at most.

-

Songs without a saved mix keep the current mix. When it's off they start at full mix, and karaoke turns off.

${plural(Object.keys(songMixes).length, "saved song mix")}${Object.keys(songMixes).length ? `` : ""}

Stem Editor

${presetEditor()}

Karaoke

- -

Synced lyrics come from LRCLIB, shown in the Lyrics drawer (L).

+

Appearance

${Object.entries(THEMES).map(([k, t]) => ``).join("")}
@@ -1028,14 +1168,14 @@ function renderSettings() {
Player bar${BAR.map(([k, l]) => ``).join("")}
-

Applied live, after the theme. Variables: --bg --panel --raised --line --text --muted --accent --accent-ink --radius --wave --wave-ghost.

+

--bg --panel --raised --line --text --muted --accent --accent-ink --radius --wave --wave-ghost

Offline

${plural(Offline.ids.size, "track")} downloaded. Manage downloads

- ${isSecureContext && navigator.storage?.persist ? `
` : `

Over plain HTTP the browser may clear downloads when it's short on space.

`} + ${isSecureContext && navigator.storage?.persist ? `
` : ""}

Backup

-

Settings, saved mixes and stem playlists. The file includes your Plex tokens.

+

Includes your Plex tokens.

Keys

Space play/pause · ←/→ seek 5s (shift 30s) · S shuffle · R repeat · [ ] speed · M mixer · L lyrics · Q queue · K karaoke · P next preset · hold Next to skip the album · right-click a song or album for more

@@ -1162,15 +1302,17 @@ async function connect() { save(); } +let connecting = null; (async () => { applyTheme(); applyStemFilter(); applyBar(); await Offline.init(); - await Promise.race([connect(), new Promise(r => setTimeout(r, 5000))]); + connecting = connect(); + await Promise.race([connecting, new Promise(r => setTimeout(r, 5000))]); Q.restore(); UI.all(); route(); Live.poll(); - setInterval(() => { if (!document.hidden) Stems.refresh(); }, 5 * 60 * 1000); + setInterval(() => { if (!document.hidden) { Stems.refresh(); } }, 5 * 60 * 1000); })(); diff --git a/web/index.html b/web/index.html index 42e0ebd..0645829 100644 --- a/web/index.html +++ b/web/index.html @@ -3,7 +3,7 @@ - + Stemify @@ -14,25 +14,28 @@