Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 104 additions & 12 deletions App/AppModel.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import AVFoundation
import BackgroundTasks
import ClementineKit
import SwiftUI
Expand Down Expand Up @@ -71,7 +72,16 @@ final class AppModel {
init() {
let session = RemoteSession()
self.session = session
renderer = Renderer(playback: AVPlayback(), server: { session.endpoint }) { session.send($0) }
renderer = Renderer(
playback: AVPlayback(
// Use AppModel.shared because `self` isn't fully initialized yet (nowPlaying/watch
// come later), and route session changes through the central coordinator.
onActivateAudio: { AppModel.shared?.activatePlaybackSession(for: .clementine) },
onDeactivateAudio: { AppModel.shared?.deactivateAudioSessionIfIdle() }),
// Prefer the active TCP socket's resolved IP so AVPlayer HTTP requests hit the same
// IP family; Clementine's MediaHttpServer rejects mismatched peer IPs with 403.
server: { session.connectedEndpoint ?? session.endpoint }
) { session.send($0) }
internet = InternetBrowser { session.send($0) }
syncer = Syncer(
session: session, store: TestingFeatures.enabled ? Self.openSyncStore() : nil, folder: Self.syncedFolder)
Expand All @@ -84,6 +94,7 @@ final class AppModel {
self.nowPlaying = nowPlaying
renderer.onUpdate = { nowPlaying.update() }
phonePlayer.onUpdate = { nowPlaying.update() }
phonePlayer.onActivateAudio = { [weak self] in self?.activatePlaybackSession(for: .phone) }
syncer.networkAllows = { [network] in network.allows($0) }
session.addObserver { [weak self, renderer, internet] message in
renderer.handle(message)
Expand Down Expand Up @@ -138,7 +149,8 @@ final class AppModel {
func connectFromPhone() {
isWithoutClementine = false
let name = settings.lastServerName
connect(host: settings.lastHost, name: name.isEmpty ? nil : name)
// Pass saved lastPort so non-default ports are preserved when reconnecting from offline mode.
connect(host: settings.lastHost, port: settings.lastPort, name: name.isEmpty ? nil : name)
}

/// Offers Play on this phone on the app's icon while there's something to play.
Expand Down Expand Up @@ -209,6 +221,54 @@ final class AppModel {
}
}

/// Coordinates the single shared `AVAudioSession` between remote streaming (`Renderer`),
/// local phone playback (`PhonePlayer`), and physical volume-button interception.
var volumeButtonsShouldBeActive: Bool {
volumeButtonsShouldBeActive(enabled: settings.volumeButtons, scenePhase: scenePhase)
}

/// Takes `enabled` and `scenePhase` explicitly so `VolumeButtonsView` participates in SwiftUI
/// updates, and yields hardware buttons to iOS whenever audio plays on this phone.
func volumeButtonsShouldBeActive(enabled: Bool, scenePhase: ScenePhase) -> Bool {
enabled && scenePhase == .active && session.status.isActive
&& !session.isPlayingHere && !isPlayingFromPhone
}

func activatePlaybackSession(for source: PlayFrom) {
// Pause the competing local audio owner before claiming the shared `.playback` session.
if source == .clementine, phonePlayer.isPlaying {
phonePlayer.pause()
} else if source == .phone {
pauseClementine()
renderer.pauseLocally()
}
let audio = AVAudioSession.sharedInstance()
try? audio.setCategory(.playback, mode: .default, policy: .longFormAudio)
try? audio.setActive(true)
}

func activateVolumeButtonSession() -> Bool {
// Never downgrade an active `.playback` session to `.ambient`, which would let the mute
// switch or screen lock silence audio playing on this phone.
guard renderer.item == nil, !phonePlayer.isPlaying else { return false }
let audio = AVAudioSession.sharedInstance()
do {
try audio.setCategory(.ambient, options: [.mixWithOthers])
try audio.setActive(true)
return true
} catch {
return false
}
}

func deactivateAudioSessionIfIdle(includingVolumeButtons: Bool = false) {
// Keep the session active if another owner (`PhonePlayer`, `Renderer`, or active
// volume-button monitoring) still relies on it.
guard renderer.item == nil, !phonePlayer.isPlaying,
includingVolumeButtons || !volumeButtonsShouldBeActive else { return }
try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation])
}

/// Where synced songs go: beside the downloaded ones, so the Files app shows them too.
static let syncedFolder = URL.documentsDirectory.appending(path: "Clementine/Synced", directoryHint: .isDirectory)

Expand Down Expand Up @@ -270,7 +330,7 @@ final class AppModel {
func connect(host: String, port: UInt16? = nil, name: String? = nil) {
let host = host.trimmingCharacters(in: .whitespaces)
guard !host.isEmpty else { return }
settings.remember(host: host, name: name)
settings.remember(host: host, name: name, port: port)
stopAutoConnecting()
connectProblem = nil
session.connect(
Expand All @@ -286,7 +346,7 @@ final class AppModel {
guard settings.autoConnect, !isAutoConnectOver, !settings.lastHost.isEmpty,
session.status == .disconnected else { return }
let name = settings.lastServerName
connect(host: settings.lastHost, name: name.isEmpty ? nil : name)
connect(host: settings.lastHost, port: settings.lastPort, name: name.isEmpty ? nil : name)
autoConnectName = name.isEmpty ? nil : name
}

Expand All @@ -299,7 +359,9 @@ final class AppModel {
case .disconnected:
// Only when the saved address couldn't be reached: not, say, for a wrong auth code.
guard case .couldNotConnect? = session.closeReason else { return }
case .connecting where server.host != session.endpoint?.host:
// Compare host and port so a server restarted on a new port at the same IP still triggers
// reconnect.
case .connecting where Endpoint(host: server.host, port: server.port) != session.endpoint:
break
default:
return
Expand Down Expand Up @@ -451,12 +513,17 @@ extension AppModel {
/// Syncs for [task], over a network Download over allows, and asks for the next one.
private func runBackgroundSync(_ task: BGTask) {
scheduleBackgroundSync()
let run = Task {
guard let path = await NetworkMonitor.currentPath(),
let completion = BGTaskCompletion(task)
let run = Task<Bool, Never> {
// Check cancellation around the async path lookup so an already-expired task bails out
// without opening a connection.
guard !Task.isCancelled,
let path = await NetworkMonitor.currentPath(),
BackgroundSync.allows(
settings.downloadNetwork, expensive: path.expensive, constrained: path.constrained)
else { return }
await BackgroundSync.run(session: session, syncer: syncer, settings: settings) {
settings.downloadNetwork, expensive: path.expensive, constrained: path.constrained),
!Task.isCancelled
else { return false }
return await BackgroundSync.run(session: session, syncer: syncer, settings: settings) {
UIApplication.shared.applicationState == .background
}
}
Expand All @@ -465,11 +532,36 @@ extension AppModel {
Task { @MainActor in
syncer.stop()
run.cancel()
// Report completion immediately on expiration rather than waiting for `run` to
// unwind so iOS doesn't terminate the process for missing the deadline.
completion.complete(success: false)
}
}
Task {
await run.value
task.setTaskCompleted(success: true)
let success = await run.value
completion.complete(success: success)
}
}
}

/// Ensures `BGTask.setTaskCompleted(success:)` is invoked at most once across the competing
/// normal-finish and iOS-expiration paths.
private final class BGTaskCompletion: @unchecked Sendable {
private let task: BGTask
private let lock = NSLock()
private var finished = false

init(_ task: BGTask) {
self.task = task
}

func complete(success: Bool) {
lock.lock()
let shouldComplete = !finished
finished = true
lock.unlock()
if shouldComplete {
task.setTaskCompleted(success: success)
}
}
}
Expand Down
22 changes: 16 additions & 6 deletions App/Connect/ConnectView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ struct ConnectView: View {
.keyboardType(.numberPad)
Button("Cancel", role: .cancel) {}
Button("Connect") {
if let code = Int32(authCode) {
if let code = Int32(authCode.trimmingCharacters(in: .whitespaces)) {
model.connect(authCode: code)
} else {
model.toasts.show("That isn't a valid code")
Expand All @@ -149,15 +149,25 @@ struct ConnectView: View {
} else {
Button("OK") {}
if model.songsOnPhone > 0 {
Button(String(
localized: "Play on this phone",
comment: "A button in the dialog when connecting fails, and a shortcut on the app's icon: play the music saved on the phone instead of connecting."),
Button(UIDevice.current.userInterfaceIdiom == .pad
? String(
localized: "Play on this iPad",
comment: "A button in the dialog when connecting fails on iPad: play the music saved on the iPad instead of connecting.")
: String(
localized: "Play on this phone",
comment: "A button in the dialog when connecting fails, and a shortcut on the app's icon: play the music saved on the phone instead of connecting."),
action: model.playWithoutClementine)
}
}
} message: { problem in
Text(problemMessage(problem))
}
.onChange(of: model.connectProblem) { _, problem in
// Clear any previously entered code so re-prompting doesn't prefill a rejected one.
if problem == .authCode {
authCode = ""
}
}
}

static let clementineVersion = "1.3"
Expand Down Expand Up @@ -425,9 +435,9 @@ private struct OnPhoneRow: View {
var body: some View {
Button(action: action) {
HStack(spacing: Metrics.space4) {
IconTile(systemImage: UIDevice.current.userInterfaceIdiom == .pad ? "ipad" : "iphone")
IconTile(systemImage: ThisDevice.systemImage)
VStack(alignment: .leading, spacing: 2) {
Text("On this phone")
Text(ThisDevice.label)
.textStyle(.bodyLarge)
.foregroundStyle(Palette.onSurface)
Text(connecting
Expand Down
3 changes: 2 additions & 1 deletion App/Connection/ConnectionSheet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ struct ConnectionSheet: View {
}

Section {
if let endpoint = session.endpoint {
// Prefer the active socket's resolved IP over the configured hostname.
if let endpoint = session.connectedEndpoint ?? session.endpoint {
LabeledContent("Address", value: "\(endpoint.host) · port \(String(endpoint.port))")
}
if !session.clementineVersion.isEmpty {
Expand Down
25 changes: 14 additions & 11 deletions App/Downloads/DownloadsModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ final class DownloadsModel {
let id: Int
let kind: Kind
var status = DownloadStatus()
/// Bytes a second, over the last few seconds.
var speed: Int64 = 0
fileprivate var samples: [(time: ContinuousClock.Instant, bytes: Int64)] = []
fileprivate var rate = TrafficRate(window: .seconds(3))

var isFinished: Bool {
if case .finished = status.state { return true }
Expand Down Expand Up @@ -91,7 +90,9 @@ final class DownloadsModel {
}

private func start(_ kind: Kind, _ request: RemoteMessage, playlistName: String?) {
guard let endpoint = model.session.endpoint else { return }
// Use the active socket's resolved IP so downloads hit the same address family as the
// session.
guard let endpoint = model.session.connectedEndpoint ?? model.session.endpoint else { return }
let id = nextID
nextID += 1
var job = Job(id: id, kind: kind)
Expand All @@ -109,7 +110,10 @@ final class DownloadsModel {
endpoint: endpoint, authCode: model.session.authCode, request: request,
playlistName: playlistName, options: DownloadOptions(directory: directory, settings: model.settings))
let background = UIApplication.shared.beginBackgroundTask(withName: "Download") { [weak self] in
self?.cancel(id)
// iOS can invoke expiration handlers off the main thread; hop to @MainActor for cancel(_:).
Task { @MainActor [weak self] in
self?.cancel(id)
}
}
tasks[id] = Task {
let (updates, continuation) = AsyncStream.makeStream(of: DownloadStatus.self, bufferingPolicy: .bufferingNewest(1))
Expand All @@ -133,12 +137,8 @@ final class DownloadsModel {
guard let index = jobs.firstIndex(where: { $0.id == id }) else { return }
var job = jobs[index]
job.status = status
let now = ContinuousClock.now
job.samples.append((now, status.bytes))
job.samples.removeAll { now - $0.time > .seconds(3) }
if let first = job.samples.first, let last = job.samples.last, last.time > first.time {
let seconds = (last.time - first.time).timeInterval
job.speed = Int64(Double(last.bytes - first.bytes) / max(seconds, 0.001))
if let rate = job.rate.add(Int(clamping: status.bytes)) {
job.speed = Int64(rate)
}
jobs[index] = job
}
Expand Down Expand Up @@ -224,8 +224,11 @@ extension DownloadsModel.Job {

/// Bytes so far, of the total, and the speed while downloading.
var sizes: String {
// Hide counts and speed until chunk 0 arrives or bytes transfer (e.g. while starting or on
// early failure).
guard status.totalBytes > 0 || status.bytes > 0 else { return "" }
var text = "\(formatBytes(status.bytes)) / \(formatBytes(status.totalBytes))"
if !isFinished {
if !isFinished, speed > 0 {
text += " (\(formatBytes(speed))/s)"
}
return text
Expand Down
Loading
Loading