From 9d5292512a4bbb3ee3db9a412363300d0a5c5a48 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 15:19:24 -0500 Subject: [PATCH 01/15] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=92=AD=E5=AE=A2?= =?UTF-8?q?=E8=AF=AD=E9=9F=B3=E5=A2=9E=E5=BC=BA=20AirPlay=20=E6=97=81?= =?UTF-8?q?=E8=B7=AF=E3=80=81=E7=89=87=E5=A4=B4=E7=89=87=E5=B0=BE=E3=80=81?= =?UTF-8?q?=E5=B7=B2=E6=92=AD=E4=B8=8B=E8=BD=BD=E6=B8=85=E7=90=86=E3=80=81?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=B8=8E=E5=A4=9A=E7=AB=AF=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?=E7=BC=BA=E9=99=B7=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 6 + Primuse/App/CarPlaySceneDelegate.swift | 5 +- .../Audio/AudioEngine+Varispeed.swift | 8 +- .../Audio/AudioPlayerService+Podcast.swift | 58 +++- .../Audio/AudioPlayerService+SpokenWord.swift | 8 +- .../Audio/AudioPlayerService+Varispeed.swift | 13 +- .../Services/Audio/AudioPlayerService.swift | 4 +- .../Services/Library/SpokenWordStore.swift | 8 +- Primuse/Services/Podcast/PodcastNetwork.swift | 2 +- Primuse/Services/Podcast/PodcastStore.swift | 35 ++- .../Services/Watch/WatchSessionBridge.swift | 5 + .../Podcast/PodcastEpisodeDetailView.swift | 27 +- .../Metadata/ISOBaseMediaChapterParser.swift | 17 ++ .../Podcast/PodcastLibraryPolicy.swift | 20 +- .../Podcast/PodcastSubscriptionSync.swift | 5 + .../ISOBaseMediaChapterParserTests.swift | 18 ++ .../Podcast/PodcastReliabilityTests.swift | 140 ++++++++++ PrimuseTests/PodcastReliabilityTests.swift | 257 ++++++++++++++++++ project.yml | 1 + 19 files changed, 579 insertions(+), 58 deletions(-) create mode 100644 PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift create mode 100644 PrimuseTests/PodcastReliabilityTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index c9d8b369f..9c142c790 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -1197,6 +1197,7 @@ 58B0C50E48FFEA1914609B68 /* BuiltInCloudCredentials.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82C951D83E89D86B5BBCCF22 /* BuiltInCloudCredentials.swift */; }; 58BDB314AFD11B5502593328 /* OfflineDownloadQualityPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC363EA431D461D912A58D09 /* OfflineDownloadQualityPolicy.swift */; }; 58E0139A2C8F5AB39E59B590 /* SongRowColumnsPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BAE5638B34082C5AF33ABAF /* SongRowColumnsPolicy.swift */; }; + 58E28F4BF9FE8E9EDCCBD43A /* PodcastReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7D86215C4E483E3C522F818 /* PodcastReliabilityTests.swift */; }; 58F28522CA674CBA0DE46DD3 /* SnapshotFileTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED5F60291AA4F12F41523A6 /* SnapshotFileTransaction.swift */; }; 58F7430F387DEC35AF090DD2 /* RadioStationsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 619F72A778551BB017F0840A /* RadioStationsView.swift */; }; 591312FA8EA28FD8C7EE8B81 /* CatalogUpgradeBootstrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = B05C3E3D2C8CE7AA701E0992 /* CatalogUpgradeBootstrap.swift */; }; @@ -2859,6 +2860,7 @@ D6F7EB5FA2C8C801022305C0 /* GoogleDriveSource+Changes.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4DBEA8DD56487CF9192CB18 /* GoogleDriveSource+Changes.swift */; }; D701072DE04F201883F35E8F /* TVPlexSignInView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88300BB8E3512BAF11A2D5B5 /* TVPlexSignInView.swift */; }; D71A326EEEF5016E847109F1 /* ServerMediaShareSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 228E9AF235163595E752F32C /* ServerMediaShareSheet.swift */; }; + D7246AB38783D12F3CF32E06 /* PodcastReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7D86215C4E483E3C522F818 /* PodcastReliabilityTests.swift */; }; D75258D23E433FE0D1EC9702 /* SafeByteRange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98FCF75D5146C4F071876CDA /* SafeByteRange.swift */; }; D75F3CECE43988C7E655D461 /* LastFmSimilarAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86755A200F0E3D194EE50F3E /* LastFmSimilarAPI.swift */; }; D76528706ED5C400B9DBBCCA /* NowPlayingPlayerLayoutPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE6443F9642FFE1A41F6ED1C /* NowPlayingPlayerLayoutPolicy.swift */; }; @@ -5880,6 +5882,7 @@ E724CE28F07A908CB4DDBE05 /* SourceManager+FolderPages.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SourceManager+FolderPages.swift"; sourceTree = ""; }; E77C291D51A0577AAC67C318 /* PrimuseTV.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = PrimuseTV.app; sourceTree = BUILT_PRODUCTS_DIR; }; E7BBFA50461FE980684501FA /* AddSourceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddSourceView.swift; sourceTree = ""; }; + E7D86215C4E483E3C522F818 /* PodcastReliabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PodcastReliabilityTests.swift; sourceTree = ""; }; E7F90F8D26A59F3DF6BF867F /* SidecarMetadataLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidecarMetadataLoader.swift; sourceTree = ""; }; E80755940DB08FFD5675F64F /* UncroppedArtworkRenderingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UncroppedArtworkRenderingTests.swift; sourceTree = ""; }; E83823660C5D7DB0660080E3 /* ServerBookFavoriteSyncService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerBookFavoriteSyncService.swift; sourceTree = ""; }; @@ -8987,6 +8990,7 @@ EFC98C4E381BB319949FD4CF /* PlaylistSongOrderDraftTests.swift */, A0F1B49E194F2BFAB1BEFD6F /* PlaylistsPageReleasedTests.swift */, 247FA6AA88C20EB75A0191EF /* PlexSignInQuotaTests.swift */, + E7D86215C4E483E3C522F818 /* PodcastReliabilityTests.swift */, 8588FF66CDAF4456FDD06B95 /* PodcastRequestQuotaTests.swift */, 1596A6C3EAF6B4960406BBCC /* PortableSnapshotPreparationStreamingTests.swift */, 766981F3FAD61D135993C16C /* PrimuseAIRelayClientTests.swift */, @@ -10175,6 +10179,7 @@ 8263182BD9D107552C52A104 /* PlaylistSongOrderDraftTests.swift in Sources */, DE34D917D323C8390F7393FC /* PlaylistsPageReleasedTests.swift in Sources */, 2D788F10C37E1FDD99D1F7AF /* PlexSignInQuotaTests.swift in Sources */, + D7246AB38783D12F3CF32E06 /* PodcastReliabilityTests.swift in Sources */, 3B90A8089DD3427257B46F87 /* PodcastRequestQuotaTests.swift in Sources */, 370F1ECAE97DEEE8AD62D5C9 /* PortableSnapshotPreparationStreamingTests.swift in Sources */, 66DA814A2AC936FD19DFA2FC /* PrimuseAIRelayClientTests.swift in Sources */, @@ -11214,6 +11219,7 @@ F7C720384AC5CB98C038FD6D /* MusicLibrary+CatalogTestInspection.swift in Sources */, 514340818667E192440C5081 /* PlaylistPartialImportNoticeTests.swift in Sources */, 25634A6C6AED55EF956E2614 /* PlexSignInQuotaTests.swift in Sources */, + 58E28F4BF9FE8E9EDCCBD43A /* PodcastReliabilityTests.swift in Sources */, 316AAF7F2D630CF7373C7F07 /* PodcastRequestQuotaTests.swift in Sources */, F6A43AC9B08602D0FE810B42 /* RadioDirectoryQuotaTests.swift in Sources */, 54422655A97AF4B14BCFB2DD /* RemoteMediaHTTPErrorTests.swift in Sources */, diff --git a/Primuse/App/CarPlaySceneDelegate.swift b/Primuse/App/CarPlaySceneDelegate.swift index 3c2327b91..f63736e29 100644 --- a/Primuse/App/CarPlaySceneDelegate.swift +++ b/Primuse/App/CarPlaySceneDelegate.swift @@ -308,7 +308,10 @@ extension CarPlaySceneDelegate: CPNowPlayingTemplateObserver { guard !player.isLiveRadio, let song = player.currentSong else { return } let library = AppServices.shared.musicLibrary // Prefer the album view; fall back to artist if the song has no album. - if let albumID = song.albumID, + if PodcastPlaybackSong.isEpisode(song), + let showID = PodcastStore.shared.episode(id: song.id)?.show.id { + self.pushPodcastShow(showID) + } else if let albumID = song.albumID, let album = library.visibleAlbum(id: albumID) { self.pushAlbumDetail(album) } else if let artistID = song.artistID, diff --git a/Primuse/Services/Audio/AudioEngine+Varispeed.swift b/Primuse/Services/Audio/AudioEngine+Varispeed.swift index 19913ea50..ae6fdfc1c 100644 --- a/Primuse/Services/Audio/AudioEngine+Varispeed.swift +++ b/Primuse/Services/Audio/AudioEngine+Varispeed.swift @@ -217,14 +217,8 @@ extension AudioEngine { func applyVolumeToAirPlaySampleBufferBackend() { guard let backend = sampleBufferBackend else { return } - let userGain: Float - #if os(iOS) - userGain = applicationVolumeEnabled ? userVolume : 1 - #else - userGain = userVolume - #endif let split = AirPlayBufferedPlaybackPolicy.gainSplit( - userVolume: userGain, + userVolume: userVolume, programVolume: outputMode == .effects ? primaryProgramVolume : 1 ) backend.setVolume(rendererVolume: split.rendererVolume, sampleScale: split.sampleScale) diff --git a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift index a80cd84d4..0be59b348 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift @@ -213,11 +213,18 @@ extension AudioPlayerService { let found = PodcastStore.shared.episode(id: song.id) else { return } PodcastPlaybackState.shared.outroHandledEpisodeID = nil PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = nil - let intro = found.show.settings.skipIntroSeconds - if intro > 0, - pendingSpokenWordSeekOverride == nil, - SpokenWordStore.shared.resumePosition(for: song) == nil { - pendingSpokenWordSeekOverride = (song.id, TimeInterval(intro)) + let skip = SpokenWordIntroOutro( + introSeconds: found.show.settings.skipIntroSeconds, + outroSeconds: found.show.settings.skipOutroSeconds + ) + if skip.introSeconds > 0, pendingSpokenWordSeekOverride == nil { + let resume = SpokenWordStore.shared.resumePosition(for: song) + let episodeDuration = found.episode.duration ?? 0 + let total = episodeDuration > 0 ? episodeDuration : song.duration + if let target = SpokenWordIntroOutroPolicy.startPosition(resume: resume, duration: total, skip: skip), + target != resume { + pendingSpokenWordSeekOverride = (song.id, target) + } } if !found.episode.chapters.isEmpty { spokenWordChapters = found.episode.chapters.map { MediaChapter(startTime: $0.start, title: $0.title) } @@ -236,22 +243,43 @@ extension AudioPlayerService { } } - /// 播放时钟每拍调:离结尾不到节目设的片尾秒数,就当这集听完,接着放下一集。 + /// 播放时钟每拍调:离结尾不到节目设的片尾秒数,就当这集听完,经曲终流程决定停下还是放下一集。 func applyPodcastOutroSkipIfNeeded() { guard isPlaying, let song = currentSong, PodcastPlaybackSong.isEpisode(song), - PodcastPlaybackState.shared.outroHandledEpisodeID != song.id, let found = PodcastStore.shared.episode(id: song.id) else { return } - let outro = TimeInterval(found.show.settings.skipOutroSeconds) - let total = duration > 0 ? duration : song.duration - guard outro > 0, total > outro + 30, currentTime > 10, total - currentTime <= outro else { return } + let skip = SpokenWordIntroOutro( + introSeconds: found.show.settings.skipIntroSeconds, + outroSeconds: found.show.settings.skipOutroSeconds + ) + let total = duration > 0 ? duration : (found.episode.duration ?? song.duration) + if !SpokenWordIntroOutroPolicy.shouldSkipOutro(position: currentTime, duration: total, skip: skip) { + if PodcastPlaybackState.shared.outroHandledEpisodeID == song.id { + PodcastPlaybackState.shared.outroHandledEpisodeID = nil + PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = nil + } + return + } + guard PodcastPlaybackState.shared.outroHandledEpisodeID != song.id, + let ticket = localPipelineAdvanceTicket ?? playbackAdvancePolicy.activeTicket, + automaticAdvanceDecision( + for: ticket, + trigger: "podcast-outro", + consume: false, + transportIsActive: isPlaying + ) == .accepted else { return } PodcastPlaybackState.shared.outroHandledEpisodeID = song.id PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = song.id - plog("🎙️ Skipping the last \(Int(outro))s of '\(song.title)'") - SpokenWordStore.shared.markFinished(true, songIDs: [song.id]) + plog("🎙️ Skipping the last \(skip.outroSeconds)s of '\(song.title)'") + PodcastStore.shared.setPlayed(true, episode: found.episode) + SpokenWordStore.shared.persistLocally() + let endedPlayID = playID Task { @MainActor [weak self] in - guard let self else { return } - let advanced = await self.next(isAutomaticAdvance: true) - if !advanced { self.pause() } + guard let self, self.currentSong?.id == song.id, self.playID == endedPlayID else { return } + await self.handleTrackEnd( + advanceTicket: ticket, + trigger: "podcast-outro", + transportIsActive: self.isPlaying + ) } } } diff --git a/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift b/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift index 4a732bb9b..f51f93d83 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift @@ -47,9 +47,8 @@ extension AudioPlayerService { smartSpeedSavingsMeter.reset() smartSpeedNowPlayingBaseline = 0 defer { - // Spoken word runs at its own speed; switching between a book and a - // song switches the rate with it. - if wasSpokenWord != currentItemIsSpokenWord { applyPlaybackRate() } + // Spoken word runs at its own speed (including per-book/show rates). + if wasSpokenWord || currentItemIsSpokenWord { applyPlaybackRate() } // 语音增强同理:换到有声内容时换上说话用的均衡与压缩,换回音乐时还原。 applySpokenWordVoiceBoost() } @@ -396,7 +395,8 @@ extension AudioPlayerService { // MARK: - Per-book intro and outro func spokenWordIntroOutro(for song: Song) -> SpokenWordIntroOutro? { - guard SpokenWordStore.shared.kind(for: song) == .spokenWord, + guard SpokenWordStore.shared.kind(for: song).isSpokenWordListening, + !PodcastPlaybackSong.isEpisode(song), song.appliedPlaybackRange == nil, !medleySongIDs.contains(song.id) else { return nil } return SpokenWordIntroOutroPreferences.shared.settings( forBookID: spokenWordBookID(for: song), server: serverSpokenWordIntroOutro(for: song) diff --git a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift index 3f476cdca..9a308161c 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift @@ -116,13 +116,15 @@ extension AudioPlayerService { : Self.decodedAudioLookahead } - func shouldUseAirPlaySampleBufferBackend(for song: Song?) -> Bool { + func shouldUseAirPlaySampleBufferBackend(for song: Song?, isAirPlayOutput: Bool? = nil) -> Bool { guard let song else { return false } if airPlaySampleBufferFallbackSongID == song.id { return false } - let effectsEnabled = audioEffectsService.effectChainEnabled - && (audioEffectsService.compressorEnabled || audioEffectsService.reverbEnabled) + let voiceBoostActive = SpokenWordStore.shared.isSpokenWord(song) && playbackSettings.spokenWordVoiceBoostEnabled + let effectsEnabled = (audioEffectsService.effectChainEnabled + && (audioEffectsService.compressorEnabled || audioEffectsService.reverbEnabled)) + || voiceBoostActive let musicHapticsActive: Bool #if os(iOS) musicHapticsActive = playbackSettings.musicHapticsEnabled && MusicHapticsEngine.isHardwareSupported @@ -130,7 +132,7 @@ extension AudioPlayerService { musicHapticsActive = false #endif return AirPlayBufferedPlaybackPolicy.shouldUseSampleBufferBackend( - isAirPlayOutput: audioEngine.outputRouteIsAirPlay, + isAirPlayOutput: isAirPlayOutput ?? audioEngine.outputRouteIsAirPlay, isDSDCarrier: false, isLiveRadio: isLiveRadio, isAppleMusic: isAppleMusicMode, @@ -138,7 +140,7 @@ extension AudioPlayerService { isKaraokeActive: isKaraokeSessionActive, isMedleyActive: isMedleyActive, isHighFidelityOutput: outputMode(for: song) == .highFidelity, - equalizerEnabled: equalizerService.isEnabled, + equalizerEnabled: equalizerService.isEnabled || voiceBoostActive, effectsEnabled: effectsEnabled, spatialAudioEnabled: playbackSettings.spatialAudioEnabled, crossfadeEnabled: playbackSettings.crossfadeEnabled, @@ -175,6 +177,7 @@ extension AudioPlayerService { _ = audioEffectsService.effectChainEnabled _ = audioEffectsService.compressorEnabled _ = audioEffectsService.reverbEnabled + _ = playbackSettings.spokenWordVoiceBoostEnabled _ = playbackSettings.spatialAudioEnabled _ = playbackSettings.crossfadeEnabled } onChange: { [weak self] in diff --git a/Primuse/Services/Audio/AudioPlayerService.swift b/Primuse/Services/Audio/AudioPlayerService.swift index df07e11cb..ca9f0ec72 100644 --- a/Primuse/Services/Audio/AudioPlayerService.swift +++ b/Primuse/Services/Audio/AudioPlayerService.swift @@ -9755,8 +9755,8 @@ extension AudioPlayerService { return } if isSystemMediaPlaybackActive { - // 放画面的有声内容停得久了,同样往回退一点再接着放(#363)。 - if isMusicVideoPlaybackActive, currentItemIsSpokenWord, !isPlaying { + // 走系统播放器(视频/音频播客)的有声内容停得久了,同样往回退一点再接着放(#363)。 + if currentItemIsSpokenWord, !isPlaying { let rewind = spokenWordSmartRewindTarget(for: song, from: currentTime, seeksInPlace: true) refreshServerSpokenWordState(for: song, resuming: true, resumingFrom: rewind) if let rewind { diff --git a/Primuse/Services/Library/SpokenWordStore.swift b/Primuse/Services/Library/SpokenWordStore.swift index cb4608e3d..01d9f8067 100644 --- a/Primuse/Services/Library/SpokenWordStore.swift +++ b/Primuse/Services/Library/SpokenWordStore.swift @@ -169,6 +169,7 @@ final class SpokenWordStore { /// depends only on classification, folder tags, bookmarks, speeds or /// archiving keys on this instead. @ObservationIgnored private(set) var nonProgressRevision = 0 + @ObservationIgnored private(set) var completionRevision = 0 /// 设置里的「单独归类环境音」(`AmbientSoundPreferences`)。本机设置,不跟着修正记录同步; /// 关掉时手动归属与目录标签照旧记着,只是分类时一律按音乐算。 private(set) var separatesAmbient = AmbientSoundPreferences.isEnabled(in: .standard) @@ -211,7 +212,7 @@ final class SpokenWordStore { loadBookItemFolders() if syncsThroughICloud { publishSharedClassificationSnapshot() - CloudKVSSync.shared.register(key: Self.cloudStorageKey) { [weak self] in + CloudKVSSync.shared.registerMerging(key: Self.cloudStorageKey) { [weak self] in guard let self else { return } if self.isRegisteredWithCloud { self.mergeCloudCopy() @@ -977,6 +978,7 @@ extension SpokenWordStore { changed = true } guard changed else { return false } + if isFinished { completionRevision &+= 1 } remoteListeningAt[songID] = updatedAt evictOldestIfNeeded() didChange(cloud: .relaxed, progressOnly: true) @@ -1027,6 +1029,7 @@ extension SpokenWordStore { } } guard changed else { return } + completionRevision &+= 1 evictOldestIfNeeded() didChange(cloud: .prompt, progressOnly: true) } @@ -1094,6 +1097,7 @@ extension SpokenWordStore { func clearPosition(forSongID songID: String) { guard removePosition(songID, at: Date()) else { return } + completionRevision &+= 1 didChange(cloud: .prompt, progressOnly: true) } @@ -1370,7 +1374,9 @@ extension SpokenWordStore { && records.bookmarks == bookmarks && records.bookRates == bookRates && records.archivedAt == archivedAt + let completionChanged = records.finishedAt != finishedAt || Set(nextPositions.keys) != Set(positions.keys) guard contentChanged || records.ledger != ledger else { return } + if completionChanged { completionRevision &+= 1 } positions = nextPositions finishedAt = records.finishedAt bookmarks = records.bookmarks diff --git a/Primuse/Services/Podcast/PodcastNetwork.swift b/Primuse/Services/Podcast/PodcastNetwork.swift index 6644e5447..dcd5fcfbe 100644 --- a/Primuse/Services/Podcast/PodcastNetwork.swift +++ b/Primuse/Services/Podcast/PodcastNetwork.swift @@ -376,7 +376,7 @@ enum PodcastChapterLoader { let embedded: [MediaChapter]? if let local = PodcastDownloadStore.shared.localURL(for: episode.id) { embedded = await Task.detached(priority: .utility) { - ID3ChapterParser.chapters(fileURL: local) + MediaChapter.embeddedChapters(inLocalFile: local) }.value } else if readsRemoteFile { // 探过、明确不认 Range 的地址,要文件头就等于把整集下下来。 diff --git a/Primuse/Services/Podcast/PodcastStore.swift b/Primuse/Services/Podcast/PodcastStore.swift index 37ef5b814..00ee20e75 100644 --- a/Primuse/Services/Podcast/PodcastStore.swift +++ b/Primuse/Services/Podcast/PodcastStore.swift @@ -73,7 +73,7 @@ final class PodcastStore { /// 单集 id → 喜欢时留的快照。 @ObservationIgnored private var likedSnapshots: [String: PodcastLikedEpisode] = [:] @ObservationIgnored nonisolated(unsafe) private var spokenWordObserver: NSObjectProtocol? - @ObservationIgnored private var lastSpokenWordNonProgressRevision = -1 + @ObservationIgnored private var lastSpokenWordCompletionRevision = -1 @ObservationIgnored private var deferredKeepLatestTask: Task? /// 正在放的那一集。删已播下载时要跳过它;各端启动时接上自己的播放器。 @ObservationIgnored var nowPlayingEpisodeID: @MainActor () -> String? = { nil } @@ -158,8 +158,7 @@ extension PodcastStore { self.observeSpokenWordCompletionIfNeeded() self.registerWithCloud() self.postChange() - self.purgeUnsubscribedDownloads() - self.purgeKeepLatestDownloads() + self.purgePlayedDownloads() self.verifyRegionalAvailabilityIfNeeded() plog("🎙️ Podcasts loaded: \(self.subscribedShows.count) shows, \(self.episodeShowIndex.count) episodes") } @@ -167,19 +166,19 @@ extension PodcastStore { private func observeSpokenWordCompletionIfNeeded() { guard spokenWordObserver == nil else { return } - lastSpokenWordNonProgressRevision = SpokenWordStore.shared.nonProgressRevision + lastSpokenWordCompletionRevision = SpokenWordStore.shared.completionRevision spokenWordObserver = NotificationCenter.default.addObserver( forName: .primuseSpokenWordDidChange, object: nil, queue: .main ) { [weak self] _ in Task { @MainActor [weak self] in guard let self else { return } - let rev = SpokenWordStore.shared.nonProgressRevision - guard rev != self.lastSpokenWordNonProgressRevision else { return } - self.lastSpokenWordNonProgressRevision = rev + let rev = SpokenWordStore.shared.completionRevision + guard rev != self.lastSpokenWordCompletionRevision else { return } + self.lastSpokenWordCompletionRevision = rev self.deferredKeepLatestTask?.cancel() self.deferredKeepLatestTask = Task { @MainActor [weak self] in try? await Task.sleep(for: .seconds(2)) - if !Task.isCancelled { self?.purgeKeepLatestDownloads() } + if !Task.isCancelled { self?.purgePlayedDownloads() } } } } @@ -188,10 +187,10 @@ extension PodcastStore { private func registerWithCloud() { guard !isRegisteredWithCloud, defaults === UserDefaults.standard else { return } isRegisteredWithCloud = true - CloudKVSSync.shared.register(key: CloudKVSKey.podcastSubscriptions) { [weak self] in + CloudKVSSync.shared.registerMerging(key: CloudKVSKey.podcastSubscriptions) { [weak self] in Task { @MainActor [weak self] in self?.mergeCloudCopy() } } - CloudKVSSync.shared.register(key: CloudKVSKey.podcastLikedEpisodes) { [weak self] in + CloudKVSSync.shared.registerMerging(key: CloudKVSKey.podcastLikedEpisodes) { [weak self] in Task { @MainActor [weak self] in self?.mergeCloudLikes() } } } @@ -266,10 +265,10 @@ extension PodcastStore { } func latestEpisodes(limit: Int, includeFinished: Bool = false) -> [PodcastEpisode] { - PodcastEpisodeListPolicy.latest( - episodesByShow: visibleEpisodesByShow, state: state(for:), - excludingFinished: !includeFinished, limit: limit - ) + latestEpisodes(limit: limit, filter: includeFinished ? .all : .unplayed) + } + func latestEpisodes(limit: Int, filter: PodcastEpisodeFilter) -> [PodcastEpisode] { + PodcastEpisodeListPolicy.latest(episodesByShow: visibleEpisodesByShow, state: state(for:), filter: filter, limit: limit) } private var visibleEpisodesByShow: [String: [PodcastEpisode]] { @@ -543,10 +542,8 @@ extension PodcastStore { /// 整档标为已播:水位线拉到最新一集。 func markAllPlayed(showID: String) { let latest = episodes(forShowID: showID).compactMap(\.publishedAt).max() ?? Date() - updateDefinition(showID) { - $0.playedThrough = max(latest, $0.playedThrough ?? .distantPast) - $0.reopenedEpisodeIDs = [] - } + updateDefinition(showID) { $0.playedThrough = max(latest, $0.playedThrough ?? .distantPast); $0.reopenedEpisodeIDs = [] } + purgePlayedDownloads() } /// 这一集之前(更早发布)的都标为已播,这一集自己不动。 @@ -558,6 +555,7 @@ extension PodcastStore { self.episode(id: id)?.episode.publishedAt.map { $0.timeIntervalSinceReferenceDate >= published.timeIntervalSinceReferenceDate } ?? false } } + purgePlayedDownloads() } // MARK: - Refreshing @@ -671,6 +669,7 @@ extension PodcastStore { show.feedURL = upgradedURL } let feedMoved = show.feedURL != current.feedURL + if feedMoved { show.definitionModifiedAt = max(Date(), current.definitionModifiedAt.addingTimeInterval(1)) } let episodesChanged = episodesByShow[show.id] != merged.episodes subscribedShows[index] = show if episodesChanged { diff --git a/Primuse/Services/Watch/WatchSessionBridge.swift b/Primuse/Services/Watch/WatchSessionBridge.swift index 12fff16dc..16dc81306 100644 --- a/Primuse/Services/Watch/WatchSessionBridge.swift +++ b/Primuse/Services/Watch/WatchSessionBridge.swift @@ -1012,6 +1012,11 @@ extension WatchSessionBridge: WCSessionDelegate { // 等其它外部播放入口口径一致。 if let song = library.visibleSong(id: id) { await player.play(song: song, caller: "watch") + } else if let queueIndex = player.queueEntries.firstIndex(where: { $0.song.id == id }), + PodcastPlaybackSong.isEpisode(player.queueEntries[queueIndex].song) { + await player.playFromQueue(at: queueIndex) + } else if let found = PodcastStore.shared.episode(id: id) { + await player.playPodcast(found.episode) } else { // 未命中 (源已停用 / 队列已变) ── 清掉去重 hash 强推一次最新 // 队列, 让 watch 列表自我修正。注意推送的是 player.queue, 仅当 diff --git a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift index 50c664fa5..b74c4449b 100644 --- a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift +++ b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift @@ -331,6 +331,7 @@ private struct PodcastEpisodeActions: View { /// 所有订阅的单集按发布时间排:主页「最新单集」的「全部」。可筛未播、听到一半、已下载。 struct PodcastEpisodeFeedView: View { + @Environment(AudioPlayerService.self) private var player @AppStorage("primuse.podcast.feed.filter") private var filterRawValue = PodcastEpisodeFilter.unplayed.rawValue @State private var pushedEpisodeID: String? @State private var pushedShowID: String? @@ -339,8 +340,7 @@ struct PodcastEpisodeFeedView: View { private var filter: PodcastEpisodeFilter { PodcastEpisodeFilter(rawValue: filterRawValue) ?? .unplayed } var body: some View { - let episodes = store.latestEpisodes(limit: 300, includeFinished: true) - .filter { filter.includes(store.state(for: $0)) } + let episodes = store.latestEpisodes(limit: 300, filter: filter) List { #if os(macOS) PodcastInlineBackButton() @@ -386,6 +386,29 @@ struct PodcastEpisodeFeedView: View { } .tint(ListeningSpace.podcast.tint) } + .swipeActions(edge: .trailing, allowsFullSwipe: false) { + if PodcastDownloadStore.shared.isDownloaded(episode.id) { + Button(role: .destructive) { + PodcastDownloadStore.shared.delete(episode.id) + } label: { + Label("podcast_remove_download", systemImage: "trash") + } + } else { + Button { + PodcastDownloadStore.shared.download(episode) + } label: { + Label("podcast_download", systemImage: "arrow.down.circle") + } + .tint(.blue) + } + Button { + let song = PodcastPlaybackSong.song(for: episode, show: store.show(id: episode.showID)) + _ = player.insertNextInQueue([song]) + } label: { + Label("insert_next_short", systemImage: "text.line.first.and.arrowtriangle.forward") + } + .tint(.orange) + } } } .listStyle(.plain) diff --git a/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift b/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift index 2f5169604..aa0719a7f 100644 --- a/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift +++ b/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift @@ -16,6 +16,23 @@ public struct MediaChapter: Equatable, Sendable, Codable, Identifiable { } } +public extension MediaChapter { + static let isoBaseMediaExtensions: Set = ["m4a", "m4b", "mp4", "m4v", "mov", "alac"] + + static func embeddedChapters(inLocalFile fileURL: URL) -> [MediaChapter] { + guard fileURL.isFileURL else { return [] } + let ext = fileURL.pathExtension.lowercased() + if ext == "mp3" { + return ID3ChapterParser.chapters(fileURL: fileURL) + } + if isoBaseMediaExtensions.contains(ext) { + guard let data = try? Data(contentsOf: fileURL, options: .mappedIfSafe) else { return [] } + return ISOBaseMediaChapterParser.chapters(in: data) + } + return ID3ChapterParser.chapters(fileURL: fileURL) + } +} + public extension Array where Element == MediaChapter { /// Index of the chapter covering `position`, or nil when the marks start /// after it. Chapters are expected sorted; playback asks this on every diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift index 35375f30f..5f4f472e0 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift @@ -234,16 +234,32 @@ public enum PodcastEpisodeListPolicy { excludingFinished: Bool = true, since: Date? = nil, limit: Int + ) -> [PodcastEpisode] { + latest( + episodesByShow: episodesByShow, + state: state, + filter: excludingFinished ? .unplayed : .all, + since: since, + limit: limit + ) + } + + /// 所有订阅里符合筛选条件且最近发布的单集,从新到旧。先筛选再截断,较早下载或听到一半的单集不会被新集挤掉。 + public static func latest( + episodesByShow: [String: [PodcastEpisode]], + state: (PodcastEpisode) -> PodcastEpisodeState, + filter: PodcastEpisodeFilter, + since: Date? = nil, + limit: Int ) -> [PodcastEpisode] { guard limit > 0 else { return [] } var candidates: [PodcastEpisode] = [] for episodes in episodesByShow.values { - // 每档节目已经是从新到旧,取前 limit 个就够。 var taken = 0 for episode in episodes { guard taken < limit else { break } if let since, let published = episode.publishedAt, published < since { break } - if excludingFinished, state(episode).isFinished { continue } + guard filter.includes(state(episode)) else { continue } candidates.append(episode) taken += 1 } diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSubscriptionSync.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSubscriptionSync.swift index 5eb508fc2..4da3e42f3 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSubscriptionSync.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSubscriptionSync.swift @@ -84,6 +84,11 @@ public struct PodcastSubscriptionRecord: Codable, Hashable, Sendable { /// 把记录里的用户决定写到已有的节目上,节目自己的信息和刷新状态不动。 public func apply(to show: inout PodcastShow) { + if show.feedURL != feedURL { + show.feedURL = feedURL + show.httpETag = nil + show.httpLastModified = nil + } show.settings = settings show.playedThrough = playedThrough show.reopenedEpisodeIDs = Set(reopenedEpisodeIDs) diff --git a/PrimuseKit/Tests/PrimuseKitTests/Metadata/ISOBaseMediaChapterParserTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Metadata/ISOBaseMediaChapterParserTests.swift index 4954e25c9..fd40b7298 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Metadata/ISOBaseMediaChapterParserTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Metadata/ISOBaseMediaChapterParserTests.swift @@ -36,6 +36,24 @@ struct ISOBaseMediaChapterParserTests { #expect(chapters[1].startTime == 5) } + @Test("Local file chapter helper dispatches M4A and M4B to ISO Base Media parser") + func embeddedChaptersInLocalFileReadsISOBaseMedia() throws { + let payload = mediaFile(moovChildren: udta(chpl( + version: 1, + entries: [(0, "Intro"), (120_000_000, "Topic")] + ))) + for ext in ["m4a", "m4b"] { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("chapter-test-\(UUID().uuidString).\(ext)") + defer { try? FileManager.default.removeItem(at: url) } + try payload.write(to: url) + let chapters = MediaChapter.embeddedChapters(inLocalFile: url) + #expect(chapters.map(\.title) == ["Intro", "Topic"]) + #expect(chapters.map(\.startTime) == [0, 12]) + } + #expect(MediaChapter.embeddedChapters(inLocalFile: URL(string: "https://example.com/a.m4a")!).isEmpty) + } + @Test("Sorts marks and drops repeated start times") func neroSortsAndDeduplicates() { let file = mediaFile(moovChildren: udta(chpl( diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift new file mode 100644 index 000000000..2b800bedd --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift @@ -0,0 +1,140 @@ +import Foundation +import Testing +@testable import PrimuseKit + +@Suite("Podcast reliability") +struct PodcastReliabilityTests { + private let oldURL = URL(string: "https://old.example.com/feed.xml")! + private let newURL = URL(string: "https://new.example.com/feed.xml")! + private let baseDate = Date(timeIntervalSince1970: 1_800_000_000) + + @Test("Synced feed migration updates feedURL and clears stale HTTP validators") + func feedMoveSyncsFeedURLAndClearsValidators() { + let showID = PodcastIdentity.showID(feedURL: oldURL) + let localShow = PodcastShow( + id: showID, + feedURL: oldURL, + title: "Show", + subscribedAt: baseDate, + httpETag: "\"v1\"", + httpLastModified: "Mon, 01 Jan 2026 00:00:00 GMT", + definitionModifiedAt: baseDate + ) + var movedShow = localShow + movedShow.feedURL = newURL + movedShow.definitionModifiedAt = baseDate.addingTimeInterval(600) + + let remoteDoc = PodcastSubscriptionSync.document( + shows: [movedShow], + removed: [:], + now: baseDate.addingTimeInterval(600) + ) + let outcome = PodcastSubscriptionSync.merge( + local: [localShow], + localRemoved: [:], + remote: remoteDoc, + now: baseDate.addingTimeInterval(700) + ) + + #expect(outcome.shows.count == 1) + #expect(outcome.shows[0].id == showID) + #expect(outcome.shows[0].feedURL == newURL) + #expect(outcome.shows[0].httpETag == nil) + #expect(outcome.shows[0].httpLastModified == nil) + } + + @Test("Unchanged feedURL preserves local HTTP validators during sync") + func unchangedFeedURLKeepsValidatorsOnSync() { + let showID = PodcastIdentity.showID(feedURL: oldURL) + let localShow = PodcastShow( + id: showID, + feedURL: oldURL, + title: "Show", + subscribedAt: baseDate, + httpETag: "\"v1\"", + httpLastModified: "Mon, 01 Jan 2026 00:00:00 GMT", + definitionModifiedAt: baseDate + ) + var updatedShow = localShow + updatedShow.settings.skipIntroSeconds = 15 + updatedShow.definitionModifiedAt = baseDate.addingTimeInterval(600) + + let remoteDoc = PodcastSubscriptionSync.document( + shows: [updatedShow], + removed: [:], + now: baseDate.addingTimeInterval(600) + ) + let outcome = PodcastSubscriptionSync.merge( + local: [localShow], + localRemoved: [:], + remote: remoteDoc, + now: baseDate.addingTimeInterval(700) + ) + + #expect(outcome.shows[0].feedURL == oldURL) + #expect(outcome.shows[0].httpETag == "\"v1\"") + #expect(outcome.shows[0].httpLastModified == "Mon, 01 Jan 2026 00:00:00 GMT") + #expect(outcome.shows[0].settings.skipIntroSeconds == 15) + } + + @Test("Episode feed filter applies before truncating to limit") + func latestWithFilterAppliesFilterBeforeLimit() { + let showA = "podcast-show:a" + let showB = "podcast-show:b" + var episodesA: [PodcastEpisode] = [] + for idx in 0..<10 { + let published = baseDate.addingTimeInterval(Double(100 - idx) * 3600) + episodesA.append(PodcastEpisode( + id: PodcastIdentity.episodeID(showID: showA, guid: "a-\(idx)"), + showID: showA, + guid: "a-\(idx)", + title: "Recent \(idx)", + publishedAt: published, + enclosureURL: URL(string: "https://media.example.com/a-\(idx).mp3")!, + firstSeenAt: published + )) + } + let olderDownloaded = PodcastEpisode( + id: PodcastIdentity.episodeID(showID: showB, guid: "b-downloaded"), + showID: showB, + guid: "b-downloaded", + title: "Older Downloaded", + publishedAt: baseDate.addingTimeInterval(-3600), + enclosureURL: URL(string: "https://media.example.com/b-downloaded.mp3")!, + firstSeenAt: baseDate + ) + let olderInProgress = PodcastEpisode( + id: PodcastIdentity.episodeID(showID: showB, guid: "b-progress"), + showID: showB, + guid: "b-progress", + title: "Older In Progress", + publishedAt: baseDate.addingTimeInterval(-7200), + enclosureURL: URL(string: "https://media.example.com/b-progress.mp3")!, + firstSeenAt: baseDate + ) + let byShow: [String: [PodcastEpisode]] = [ + showA: episodesA, + showB: [olderDownloaded, olderInProgress], + ] + let states: [String: PodcastEpisodeState] = [ + olderDownloaded.id: PodcastEpisodeState(isDownloaded: true), + olderInProgress.id: PodcastEpisodeState(position: 120), + ] + + let downloaded = PodcastEpisodeListPolicy.latest( + episodesByShow: byShow, + state: { states[$0.id] ?? .untouched }, + filter: .downloaded, + limit: 3 + ) + #expect(downloaded.map(\.id) == [olderDownloaded.id]) + + let inProgress = PodcastEpisodeListPolicy.latest( + episodesByShow: byShow, + state: { states[$0.id] ?? .untouched }, + filter: .inProgress, + limit: 3 + ) + #expect(inProgress.map(\.id) == [olderInProgress.id]) + } +} diff --git a/PrimuseTests/PodcastReliabilityTests.swift b/PrimuseTests/PodcastReliabilityTests.swift new file mode 100644 index 000000000..bb854faaf --- /dev/null +++ b/PrimuseTests/PodcastReliabilityTests.swift @@ -0,0 +1,257 @@ +import Foundation +import PrimuseKit +import XCTest +@testable import Primuse + +@MainActor +final class PodcastReliabilityTests: XCTestCase { + private var cleanups: [() -> Void] = [] + + override func tearDown() { + for cleanup in cleanups.reversed() { cleanup() } + cleanups.removeAll() + super.tearDown() + } + + private func makeDefaults() throws -> UserDefaults { + let suite = "podcast-reliability-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + cleanups.append { defaults.removePersistentDomain(forName: suite) } + return defaults + } + + private func makeDirectory() -> URL { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("podcast-reliability-\(UUID().uuidString)", isDirectory: true) + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + cleanups.append { try? FileManager.default.removeItem(at: directory) } + return directory + } + + private func makePlayer() throws -> AudioPlayerService { + let directory = makeDirectory() + let defaults = try makeDefaults() + let settings = PlaybackSettingsStore( + defaults: defaults, + cloudSync: CloudKVSSync(store: nil, defaults: defaults, observing: nil) + ) + let player = AudioPlayerService( + library: nil, + playbackSettings: settings, + playbackSessionStore: PlaybackSessionStore(url: directory.appendingPathComponent("session.json")), + activateAudioSession: { _ in XCTFail("Podcast reliability tests must not activate audio") } + ) + let modes = ListeningPlayModeStore.shared.ledger + let persistence = player.playbackSessionPersistence + cleanups.append { + player.currentSong = nil + player.stop() + player.persistPlaybackSession(flushImmediately: true) + XCTAssertNil(persistence.drain().failureDescription) + ListeningPlayModeStore.shared.update { $0 = modes } + } + return player + } + + func testSpokenWordCompletionRevisionBumpsOnFinishAndClearNotOnAutosave() { + let directory = makeDirectory() + let store = SpokenWordStore(storeURL: directory.appendingPathComponent("spoken.json")) + let songID = "podcast:\(UUID().uuidString)" + + let initial = store.completionRevision + store.rememberPosition(120, duration: 1800, forSongID: songID) + XCTAssertEqual(store.completionRevision, initial, "Mid-episode autosaves must not trigger download purge") + + store.markFinished(true, songIDs: [songID]) + let afterFinish = store.completionRevision + XCTAssertGreaterThan(afterFinish, initial) + + store.markFinished(false, songIDs: [songID]) + let afterUnfinish = store.completionRevision + XCTAssertGreaterThan(afterUnfinish, afterFinish) + + store.rememberPosition(300, duration: 1800, forSongID: songID) + XCTAssertEqual(store.completionRevision, afterUnfinish) + + store.clearPosition(forSongID: songID) + XCTAssertGreaterThan(store.completionRevision, afterUnfinish) + } + + func testAirPlaySampleBufferBackendDisabledWhenVoiceBoostActive() throws { + let player = try makePlayer() + let episode = Song( + id: "podcast:\(UUID().uuidString)", + title: "Episode 1", + albumTitle: "Show", + artistName: "Host", + duration: 1800, + fileFormat: .mp3, + filePath: "https://media.example.com/ep1.mp3", + sourceID: PodcastPlaybackSong.sourceID, + genre: PodcastPlaybackSong.genre + ) + let previousEQ = player.equalizerService.isEnabled + let previousFX = player.audioEffectsService.effectChainEnabled + cleanups.append { + player.equalizerService.isEnabled = previousEQ + player.audioEffectsService.effectChainEnabled = previousFX + } + player.equalizerService.isEnabled = false + player.audioEffectsService.effectChainEnabled = false + player.playbackSettings.spatialAudioEnabled = false + player.playbackSettings.crossfadeEnabled = false + player.playbackSettings.spokenWordVoiceBoostEnabled = false + + XCTAssertTrue(player.shouldUseAirPlaySampleBufferBackend(for: episode, isAirPlayOutput: true)) + + player.playbackSettings.spokenWordVoiceBoostEnabled = true + XCTAssertFalse( + player.shouldUseAirPlaySampleBufferBackend(for: episode, isAirPlayOutput: true), + "AirPlay 2 must route through AVAudioEngine when Voice Boost is active" + ) + } + + func testSpokenWordToSpokenWordTrackChangeReappliesPerBookRate() throws { + let player = try makePlayer() + let bookA = Song( + id: "local-book-a-\(UUID().uuidString)", + title: "Episode A", + albumTitle: "Show Alpha \(UUID().uuidString)", + artistName: "Host Alpha", + albumArtistName: "Host Alpha", + duration: 1800, + fileFormat: .mp3, + filePath: "/Books/Alpha/01.mp3", + sourceID: "local-source", + genre: "Audiobook" + ) + let bookB = Song( + id: "local-book-b-\(UUID().uuidString)", + title: "Episode B", + albumTitle: "Show Beta \(UUID().uuidString)", + artistName: "Host Beta", + albumArtistName: "Host Beta", + duration: 1800, + fileFormat: .mp3, + filePath: "/Books/Beta/01.mp3", + sourceID: "local-source", + genre: "Audiobook" + ) + let bookAID = player.spokenWordBookID(for: bookA) + let bookBID = player.spokenWordBookID(for: bookB) + cleanups.append { + SpokenWordStore.shared.setPlaybackRate(nil, forBookID: bookAID) + SpokenWordStore.shared.setPlaybackRate(nil, forBookID: bookBID) + } + player.playbackSettings.spokenWordPlaybackRate = 1.0 + SpokenWordStore.shared.setPlaybackRate(1.25, forBookID: bookAID) + SpokenWordStore.shared.setPlaybackRate(1.75, forBookID: bookBID) + + player.currentSong = bookA + player.handleSpokenWordItemChange(to: bookA) + XCTAssertEqual(player.audioEngine.playbackRate, 1.25, accuracy: 0.001) + + player.currentSong = bookB + player.handleSpokenWordItemChange(to: bookB) + XCTAssertEqual(player.audioEngine.playbackRate, 1.75, accuracy: 0.001) + } + + func testLocalPodcastUsesSpokenWordIntroOutro() throws { + let player = try makePlayer() + let localPodcast = Song( + id: "local-podcast-\(UUID().uuidString)", + title: "Episode 1", + albumTitle: "Local Show \(UUID().uuidString)", + artistName: "Creator", + albumArtistName: "Creator", + duration: 1800, + fileFormat: .mp3, + filePath: "/Podcasts/LocalShow/01.mp3", + sourceID: "local-source", + genre: "Podcast" + ) + let bookID = player.spokenWordBookID(for: localPodcast) + let expected = SpokenWordIntroOutro(introSeconds: 30, outroSeconds: 15) + cleanups.append { SpokenWordIntroOutroPreferences.shared.set(nil, forBookID: bookID) } + SpokenWordIntroOutroPreferences.shared.set(expected, forBookID: bookID) + + XCTAssertEqual(player.spokenWordIntroOutro(for: localPodcast), expected) + } + + func testPodcastStoreApplyBumpsDefinitionModifiedAtOnFeedMove() async throws { + let defaults = try makeDefaults() + let directory = makeDirectory() + let oldURL = URL(string: "https://old.example.com/rss.xml")! + let newURL = URL(string: "https://new.example.com/rss.xml")! + let t0 = Date(timeIntervalSince1970: 1_700_000_000) + + let initialFeed = PodcastFeed(title: "Moved Show", items: [ + PodcastFeedItem(guid: "ep1", title: "Ep 1", publishedAt: t0, enclosureURL: URL(string: "https://media.example.com/1.mp3")) + ]) + let subscribed = PodcastFeedMerge.subscribe(feed: initialFeed, feedURL: oldURL, now: t0) + struct SeedLibrary: Encodable { var shows: [PodcastShow]; var removed: [String: Date] } + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .secondsSince1970 + let data = try encoder.encode(SeedLibrary(shows: [subscribed.show], removed: [:])) + try data.write(to: directory.appendingPathComponent("shows.json")) + + let store = PodcastStore(defaults: defaults, directory: directory) + store.loadIfNeeded() + for _ in 0..<50 where !store.isLoaded { + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertTrue(store.isLoaded) + XCTAssertEqual(store.subscribedShows.first?.definitionModifiedAt, t0) + + var movedFeed = initialFeed + movedFeed.newFeedURL = newURL + let mergedMove = PodcastFeedMerge.refresh( + show: subscribed.show, + existing: subscribed.episodes, + feed: movedFeed, + now: t0.addingTimeInterval(60) + ) + store.apply(mergedMove, etag: "\"v2\"", lastModified: nil, upgradedURL: newURL) + + let updated = try XCTUnwrap(store.subscribedShows.first) + XCTAssertEqual(updated.feedURL, newURL) + XCTAssertEqual(updated.id, subscribed.show.id) + XCTAssertGreaterThan(updated.definitionModifiedAt, t0) + } + + func testCloudKVSMergingRegistrationPullsRemoteChangesEvenWhenLocalRevisionIsNewer() throws { + let defaults = try makeDefaults() + defaults.set(true, forKey: CloudSyncChannel.masterDefaultsKey) + defaults.set(true, forKey: CloudSyncChannel.settings.defaultsKey) + let key = "primuse_podcast_merging_test_\(UUID().uuidString)" + let remoteStore = InMemoryCloudKVSStore() + let sync = CloudKVSSync(store: remoteStore, defaults: defaults, observing: nil) + + var reloadCount = 0 + sync.registerMerging(key: key) { reloadCount += 1 } + defaults.set(false, forKey: CloudSyncChannel.settings.defaultsKey) + defaults.set("local-copy", forKey: key) + sync.markChanged(key: key) + + remoteStore.set("remote-copy", forKey: key) + remoteStore.set(10.0, forKey: "\(key)__updatedAt") + remoteStore.set("other-device", forKey: "\(key)__writerID") + defaults.set(true, forKey: CloudSyncChannel.settings.defaultsKey) + + let result = sync.catchUp() + XCTAssertEqual(result.pulled, 1) + XCTAssertEqual(result.pushed, 0) + XCTAssertGreaterThanOrEqual(reloadCount, 1) + XCTAssertEqual(defaults.string(forKey: key), "remote-copy") + } +} + +private final class InMemoryCloudKVSStore: CloudKeyValueStore, @unchecked Sendable { + var dictionaryRepresentation: [String: Any] = [:] + func object(forKey key: String) -> Any? { dictionaryRepresentation[key] } + func set(_ value: Any?, forKey key: String) { dictionaryRepresentation[key] = value } + func removeObject(forKey key: String) { dictionaryRepresentation.removeValue(forKey: key) } + func double(forKey key: String) -> Double { (dictionaryRepresentation[key] as? NSNumber)?.doubleValue ?? 0 } + func string(forKey key: String) -> String? { dictionaryRepresentation[key] as? String } + @discardableResult func synchronize() -> Bool { true } +} diff --git a/project.yml b/project.yml index ec3f8e231..5b3436e87 100644 --- a/project.yml +++ b/project.yml @@ -408,6 +408,7 @@ targets: - path: PrimuseTests/WebDAVDirectoryQuotaTests.swift - path: PrimuseTests/LastFmSimilarQuotaTests.swift - path: PrimuseTests/PodcastRequestQuotaTests.swift + - path: PrimuseTests/PodcastReliabilityTests.swift - path: PrimuseTests/CrossFeatureQuotaTests.swift - path: PrimuseTests/RadioDirectoryQuotaTests.swift - path: PrimuseTests/ExternalPlaylistQuotaTests.swift From 137f6e8ecff5aa3e390393496439928cca957ce9 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 15:54:44 -0500 Subject: [PATCH 02/15] =?UTF-8?q?=E6=8A=BD=E5=8F=96=E8=B7=A8=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E8=AF=AD=E9=9F=B3=E5=A2=9E=E5=BC=BA=E4=B8=8E=E5=89=A9?= =?UTF-8?q?=E4=BD=99=E6=97=B6=E9=97=B4=E7=AD=96=E7=95=A5=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E7=94=B5=E5=8F=B0=E9=87=8D=E8=BF=9E=E3=80=81=E5=85=83?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=B0=81=E9=9D=A2=E4=B8=8E=E6=9C=89=E5=A3=B0?= =?UTF-8?q?=E4=B9=A6/Apple=20TV=20=E7=BC=BA=E9=99=B7=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 10 ++ .../Audio/AudioPlayerService+Casting.swift | 3 +- .../Audio/AudioPlayerService+Podcast.swift | 35 ++-- .../Audio/AudioPlayerService+Radio.swift | 35 +++- .../Audio/AudioPlayerService+SmartSpeed.swift | 5 +- .../Audio/AudioPlayerService+SpokenWord.swift | 38 ++--- .../Audio/AudioPlayerService+Varispeed.swift | 5 +- .../Services/Audio/AudioPlayerService.swift | 2 +- .../Services/Library/SpokenWordStore.swift | 9 +- .../Radio/RadioPlaybackController.swift | 5 +- .../Services/Radio/RadioStationsStore.swift | 6 +- .../Radio/RadioTitleHistoryStore.swift | 16 +- .../Sources/AudiobookshelfSource.swift | 4 +- .../Views/Library/SpokenWordLibraryView.swift | 2 +- .../Views/Mac/MacRadioStationEditorView.swift | 5 +- .../Views/NowPlaying/ChapterListView.swift | 2 +- .../SpokenWordPlayerComponents.swift | 19 +-- Primuse/Views/Radio/RadioStationsView.swift | 4 +- .../Radio/RadioPlaybackPolicy.swift | 84 +++++++++ .../SpokenWordNowPlayingPolicy.swift | 15 ++ .../SpokenWordVoiceBoostPolicy.swift | 18 ++ .../AudiobookshelfServiceClient.swift | 2 +- .../Radio/RadioPlaybackPolicyTests.swift | 107 ++++++++++++ .../VoiceBoostActivationPolicyTests.swift | 30 ++++ .../AudiobookshelfServiceTests.swift | 10 ++ PrimuseTV/Model/TVStore.swift | 3 +- PrimuseTV/Views/TVSpokenWordNowPlaying.swift | 26 ++- .../ListeningSpacesReliabilityTests.swift | 161 ++++++++++++++++++ project.yml | 1 + 29 files changed, 573 insertions(+), 89 deletions(-) create mode 100644 PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/SpokenWord/VoiceBoostActivationPolicyTests.swift create mode 100644 PrimuseTests/ListeningSpacesReliabilityTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index 9c142c790..cf274df54 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -2358,6 +2358,7 @@ AFD5B53A36622430D2016CAE /* PrimuseIntentBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EA5291A0332EE798C4EB2C5 /* PrimuseIntentBridge.swift */; }; AFD9B0DC4B13544CF3868D45 /* HomeRecentlyAddedSongsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C086F3CCB681F0307725454 /* HomeRecentlyAddedSongsSection.swift */; }; AFDF2FE24ED3326C89FCCDC0 /* PlayerActivityBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D2785104A3437943C8F439 /* PlayerActivityBar.swift */; }; + AFDF4851DFA45E481C8C69F9 /* ListeningSpacesReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04360A94D291DF769F92B4D3 /* ListeningSpacesReliabilityTests.swift */; }; AFE8B1D83B0A404411167743 /* ImmersivePlayerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 694F8F3DCD98021DF67ED95D /* ImmersivePlayerView.swift */; }; AFEF85BA7F15C90129913A85 /* PlayerMoreMenu+Catalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CB8FF8077C282F0CF903933 /* PlayerMoreMenu+Catalog.swift */; }; AFF393FB60C29E3168632E38 /* AudiobookshelfSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC7328A5A7A53657CC638132 /* AudiobookshelfSource.swift */; }; @@ -3042,6 +3043,7 @@ E4B6017911BEB6E3DDF1824F /* MusicLibrary+CatalogReadToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = A85A01D85D421EEB1B44703D /* MusicLibrary+CatalogReadToken.swift */; }; E4D7D5D468F5DCCDC342C0EC /* OfflineBatchRetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15E3F86552566DF46DEEF008 /* OfflineBatchRetryPolicy.swift */; }; E4EB265E95F26C5F0ABFC277 /* RequestExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0620A5274FFFD11D82AA22 /* RequestExecutor.swift */; }; + E4F136FBADCBBC0CA53BFA81 /* ListeningSpacesReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04360A94D291DF769F92B4D3 /* ListeningSpacesReliabilityTests.swift */; }; E4FED8D07DA2A579C70F7822 /* RadioStationOrganization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E4119E96B1A605CAFA5FE0B /* RadioStationOrganization.swift */; }; E4FFBC9C9F0E360219AB8567 /* ExternalPlaylistFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = D967C992538A3FB39D581F7A /* ExternalPlaylistFiles.swift */; }; E512A4F59CE8685E68557218 /* LibraryFolderSelectionIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22D61593762FC7CE11149EF8 /* LibraryFolderSelectionIndex.swift */; }; @@ -3237,6 +3239,7 @@ F29C06E8B70CEFBC398CA333 /* CatalogUpgradeBootstrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = B05C3E3D2C8CE7AA701E0992 /* CatalogUpgradeBootstrap.swift */; }; F2B61BECA3DCBDD1D5E2E711 /* AppIconStyles.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = B77C96D01870E1688B08B6AE /* AppIconStyles.xcassets */; }; F2BD32368769020E9ECA92C7 /* AppleMusicLibraryIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = A099F9B1472D4ABEA9E86039 /* AppleMusicLibraryIdentity.swift */; }; + F2C3D40C1345C97DFADF9D0C /* RadioPlaybackPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35BD59C29C82505766AAD681 /* RadioPlaybackPolicy.swift */; }; F2CD041D57050FD33E8A5B11 /* WatchConnectionPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C7AA3EAF3D22CD9D0642CDA /* WatchConnectionPresentation.swift */; }; F2CFCCF79AE1E1C60285A078 /* OrderedFileWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F40CBFED01F876CBD8E8DC5 /* OrderedFileWriter.swift */; }; F2EDEF3D5CD6FC408395B48B /* ImmersiveControlsState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 531573F4A84A46214D98DE11 /* ImmersiveControlsState.swift */; }; @@ -3733,6 +3736,7 @@ 040CD8D85207480295C5334F /* PlexServerLinkRefresher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlexServerLinkRefresher.swift; sourceTree = ""; }; 04202B79276932465E3233C4 /* LibrarySearchCatalog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibrarySearchCatalog.swift; sourceTree = ""; }; 04268E35349CDAE4C8DCD94E /* ScrapeOptionsTaskTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrapeOptionsTaskTests.swift; sourceTree = ""; }; + 04360A94D291DF769F92B4D3 /* ListeningSpacesReliabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListeningSpacesReliabilityTests.swift; sourceTree = ""; }; 045159A6132E6BE82E1D593D /* LibrarySnapshotSync+StagedPreparation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibrarySnapshotSync+StagedPreparation.swift"; sourceTree = ""; }; 04692C51642FB767EEC12C0A /* PersistedTaskDeduplicator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistedTaskDeduplicator.swift; sourceTree = ""; }; 04FEFE5387094AF674BC2969 /* CleartextHTTPExchange.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleartextHTTPExchange.swift; sourceTree = ""; }; @@ -4209,6 +4213,7 @@ 358FB5FD1B3511F830365EC8 /* PlaybackRequestGenerationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaybackRequestGenerationPolicy.swift; sourceTree = ""; }; 3591B53DCD5A20410168ADE0 /* QueueAdvancePolicies.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueueAdvancePolicies.swift; sourceTree = ""; }; 35B8B07FDE7B2E757C09FFD2 /* LibraryCatalogReader+P4a2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibraryCatalogReader+P4a2.swift"; sourceTree = ""; }; + 35BD59C29C82505766AAD681 /* RadioPlaybackPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RadioPlaybackPolicy.swift; sourceTree = ""; }; 35D34C21A9B67350654FBE7C /* AppleMusicCatalogHit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleMusicCatalogHit.swift; sourceTree = ""; }; 35F3D38E957ECE0678ADF1BC /* LockScreenMotionArtworkPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LockScreenMotionArtworkPolicy.swift; sourceTree = ""; }; 361CCA1B12F522769DD09B73 /* LibraryCatalog+KindPointReads.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibraryCatalog+KindPointReads.swift"; sourceTree = ""; }; @@ -8150,6 +8155,7 @@ 2958B677CA70E34B8A738557 /* RadioLogoBackdropPolicy.swift */, 3DBCB5A42A29C5A2F88B3F0C /* RadioLogoDiscoveryPolicy.swift */, 5EEC93D45D5A129ED4E3A0D3 /* RadioLogoURLPolicy.swift */, + 35BD59C29C82505766AAD681 /* RadioPlaybackPolicy.swift */, 3C3121FC0DB2F2843B4D7718 /* RadioPlaylistText.swift */, 75E1B693A9FB85D5F3079967 /* RadioStationListeningHistory.swift */, 3E4119E96B1A605CAFA5FE0B /* RadioStationOrganization.swift */, @@ -8945,6 +8951,7 @@ 6501ADF2A78A679B038D1826 /* LibraryStartupPreparationTests.swift */, 72EDF3F4D1CF10A41CE2DA3C /* LifecycleRegressionTests.swift */, AD7784439BAA2CA78032A57B /* ListeningFeaturesTests.swift */, + 04360A94D291DF769F92B4D3 /* ListeningSpacesReliabilityTests.swift */, 5D617CA2E47B244965424CF6 /* LocalReferenceFileChangeTests.swift */, 65C163A6A5CD5B15DA0A6D1D /* LRCLIBHTTPErrorTests.swift */, F6689B45FBB7DF903AEC8EFE /* LyricPosterAudioExportTests.swift */, @@ -10134,6 +10141,7 @@ 1FE2BC706AA7F2A36C401F13 /* LibraryStartupPreparationTests.swift in Sources */, B6BBC2FD980B62AF838C437F /* LifecycleRegressionTests.swift in Sources */, 928146F0EF3650B675D4F97F /* ListeningFeaturesTests.swift in Sources */, + AFDF4851DFA45E481C8C69F9 /* ListeningSpacesReliabilityTests.swift in Sources */, D88A1CF15A06C1CF6688E5A5 /* LocalReferenceFileChangeTests.swift in Sources */, 55C957669733EE4F39E15AC9 /* LyricPosterAudioExportTests.swift in Sources */, 01D6951366B9D34A0CBC68FA /* LyricsDocumentSourcesResolutionTests.swift in Sources */, @@ -10900,6 +10908,7 @@ 1E9B28ACF001E8CE1EF5FE83 /* RadioLogoBackdropPolicy.swift in Sources */, 0EA465C8DC3980650EBD682F /* RadioLogoDiscoveryPolicy.swift in Sources */, 6E4EDD3796879951FDF3A5EF /* RadioLogoURLPolicy.swift in Sources */, + F2C3D40C1345C97DFADF9D0C /* RadioPlaybackPolicy.swift in Sources */, 436583C6E96EB932FBFAA21F /* RadioPlaylistText.swift in Sources */, BF3408300898A64231169232 /* RadioSnapshotUploadPolicy.swift in Sources */, BD977311BC272B1E6739BC96 /* RadioStation.swift in Sources */, @@ -11204,6 +11213,7 @@ B796E7824FC7BB787657F339 /* GeminiAudioQuotaTests.swift in Sources */, AB8254FB95CFBE2DD7D59240 /* LastFmSimilarQuotaTests.swift in Sources */, 83BAF66C03A98631F4B7B8B5 /* LegacyIncrementalSongStoreTestWriter.swift in Sources */, + E4F136FBADCBBC0CA53BFA81 /* ListeningSpacesReliabilityTests.swift in Sources */, 7196904796218B3CA9C68F08 /* LocalReferenceFileChangeTests.swift in Sources */, E6012DAFE207A596D7811C42 /* LyricsCloudAndCacheRegressionTests.swift in Sources */, 5F4635DA93BF420FA5F4A70A /* MacCredentialKeychainTests.swift in Sources */, diff --git a/Primuse/Services/Audio/AudioPlayerService+Casting.swift b/Primuse/Services/Audio/AudioPlayerService+Casting.swift index d53abf016..de5331645 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Casting.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Casting.swift @@ -193,7 +193,7 @@ extension AudioPlayerService { finishingCommittedTransition: true, completionMode: .preserveCachedProgress ) - let resumeSong = currentSong + let resumeSong = isLiveRadio ? nil : currentSong let resumeTime = currentTime let wasPlaying = isPlaying @@ -213,6 +213,7 @@ extension AudioPlayerService { audioEngine.stop() hasPreparedLocalPlayback = false stopMusicVideoPlayback(clearPlayer: true) + if isLiveRadio { stopRadioTransport(clearSelection: true) } isPlaying = false AudioSessionManager.shared.deactivate() updateNowPlayingInfo() diff --git a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift index 0be59b348..7b44be665 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift @@ -245,14 +245,28 @@ extension AudioPlayerService { /// 播放时钟每拍调:离结尾不到节目设的片尾秒数,就当这集听完,经曲终流程决定停下还是放下一集。 func applyPodcastOutroSkipIfNeeded() { - guard isPlaying, let song = currentSong, PodcastPlaybackSong.isEpisode(song), + guard let song = currentSong, PodcastPlaybackSong.isEpisode(song), let found = PodcastStore.shared.episode(id: song.id) else { return } let skip = SpokenWordIntroOutro( introSeconds: found.show.settings.skipIntroSeconds, outroSeconds: found.show.settings.skipOutroSeconds ) let total = duration > 0 ? duration : (found.episode.duration ?? song.duration) - if !SpokenWordIntroOutroPolicy.shouldSkipOutro(position: currentTime, duration: total, skip: skip) { + applyOutroSkipIfNeeded(for: song, skip: skip, totalDuration: total, trigger: "podcast-outro") { + plog("🎙️ Skipping the last \(skip.outroSeconds)s of '\(song.title)'") + PodcastStore.shared.setPlayed(true, episode: found.episode) + } + } + + func applyOutroSkipIfNeeded( + for song: Song, + skip: SpokenWordIntroOutro, + totalDuration: TimeInterval, + trigger: String, + markFinished: () -> Void + ) { + guard isPlaying else { return } + if !SpokenWordIntroOutroPolicy.shouldSkipOutro(position: currentTime, duration: totalDuration, skip: skip) { if PodcastPlaybackState.shared.outroHandledEpisodeID == song.id { PodcastPlaybackState.shared.outroHandledEpisodeID = nil PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = nil @@ -261,25 +275,16 @@ extension AudioPlayerService { } guard PodcastPlaybackState.shared.outroHandledEpisodeID != song.id, let ticket = localPipelineAdvanceTicket ?? playbackAdvancePolicy.activeTicket, - automaticAdvanceDecision( - for: ticket, - trigger: "podcast-outro", - consume: false, - transportIsActive: isPlaying - ) == .accepted else { return } + automaticAdvanceDecision(for: ticket, trigger: trigger, consume: false, + transportIsActive: isPlaying) == .accepted else { return } PodcastPlaybackState.shared.outroHandledEpisodeID = song.id PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = song.id - plog("🎙️ Skipping the last \(skip.outroSeconds)s of '\(song.title)'") - PodcastStore.shared.setPlayed(true, episode: found.episode) + markFinished() SpokenWordStore.shared.persistLocally() let endedPlayID = playID Task { @MainActor [weak self] in guard let self, self.currentSong?.id == song.id, self.playID == endedPlayID else { return } - await self.handleTrackEnd( - advanceTicket: ticket, - trigger: "podcast-outro", - transportIsActive: self.isPlaying - ) + await self.handleTrackEnd(advanceTicket: ticket, trigger: trigger, transportIsActive: self.isPlaying) } } } diff --git a/Primuse/Services/Audio/AudioPlayerService+Radio.swift b/Primuse/Services/Audio/AudioPlayerService+Radio.swift index b818e888c..9838a2132 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Radio.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Radio.swift @@ -141,6 +141,8 @@ extension AudioPlayerService { stopMusicVideoPlayback(clearPlayer: true) stopTimeUpdater() radioPlaybackController.stop() + rememberCurrentMusicQueue() + remembersMusicQueue = false playbackKind = .liveRadio currentRadioStation = station @@ -154,6 +156,7 @@ extension AudioPlayerService { radioStationOrder.append(station) } currentSong = station.playbackSong + handleSpokenWordItemChange(to: nil) currentTime = 0 duration = 0 isAtTrackEnd = false @@ -284,6 +287,7 @@ extension AudioPlayerService { self.applySpatialAudioSettings() self.audioEffectsService.applySettings() self.equalizerService.applySettings() + self.applySpokenWordVoiceBoost() guard let outputFormat = self.audioEngine.outputFormat else { throw AudioDecoderError.decodingFailed("Audio engine not ready") } @@ -466,9 +470,7 @@ extension AudioPlayerService { case .playing: guard interruptionResumePolicy.playbackIsIntended, !interruptionResumePolicy.isAwaitingInterruptionEnd else { - radioPlaybackController.stop() - isLoading = false - isPlaying = false + stopRadioTransport(clearSelection: false) break } isLoading = false @@ -526,7 +528,11 @@ extension AudioPlayerService { radioNowPlaying?.title, metadata.title ) - let artwork = metadata.artworkURL ?? radioNowPlayingArtworkURL + let artwork = RadioLiveMetadataPolicy.resolvedArtworkURL( + incoming: metadata, + previousTitle: radioNowPlaying?.title, + previousArtworkURL: radioNowPlayingArtworkURL + ) guard !isSameTitle || artwork != radioNowPlayingArtworkURL else { return } radioTitleHistory = RadioTitleHistoryPolicy.appending(metadata, to: radioTitleHistory) @@ -646,6 +652,27 @@ extension AudioPlayerService { } } + func recoverDecodedRadioTransportIfNeeded() { + guard isLiveRadio, radioUsesDecodedTransport, + let station = currentRadioStation, + let id = playID else { return } + #if !os(macOS) + if configurationRecoveryOwnerPlayID == id { + configurationRecoveryOwnerPlayID = nil + return + } + #endif + guard (isPlaying || isLoading), + interruptionResumePolicy.playbackIsIntended, + !interruptionResumePolicy.isAwaitingInterruptionEnd else { return } + audioEngine.markHardwareConfigurationChanged() + #if !os(macOS) + configurationRecoveryOwnerPlayID = id + #endif + plog("📻 Rebuilding decoded radio transport after audio configuration change") + startRadioTransport(station: station, playID: id) + } + private func resolveRadioStreamURL( for station: RadioStation, forceRefresh: Bool diff --git a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift index 51290e75b..ba6ed3a4f 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift @@ -230,7 +230,10 @@ extension AudioPlayerService { /// 有声内容在放、语音增强打开时,均衡和压缩器换成说话用的设定;其余时候照用户自己的设置。 func applySpokenWordVoiceBoost() { - let active = currentItemIsSpokenWord && playbackSettings.spokenWordVoiceBoostEnabled + let active = VoiceBoostActivationPolicy.isActive( + space: currentListeningSpace, + spokenWordEnabled: playbackSettings.spokenWordVoiceBoostEnabled + ) audioEffectsService.voiceBoostActive = active equalizerService.voiceBoostActive = active } diff --git a/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift b/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift index f51f93d83..50f461787 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift @@ -62,7 +62,7 @@ extension AudioPlayerService { return } let kind = SpokenWordStore.shared.kind(for: song) - currentItemIsSpokenWord = kind.isSpokenWordListening + currentItemIsSpokenWord = !isRadioPlaybackSong(song) && kind.isSpokenWordListening let isAmbient = kind == .ambient && !isRadioPlaybackSong(song) && !PodcastPlaybackSong.isEpisode(song) if currentItemIsAmbient != isAmbient { currentItemIsAmbient = isAmbient } if let override = pendingSpokenWordSeekOverride, override.songID != song.id { @@ -144,7 +144,7 @@ extension AudioPlayerService { let kind = SpokenWordStore.shared.kind(for: song) let isAmbient = kind == .ambient && !isRadioPlaybackSong(song) && !PodcastPlaybackSong.isEpisode(song) if currentItemIsAmbient != isAmbient { currentItemIsAmbient = isAmbient } - let isSpokenWord = kind.isSpokenWordListening + let isSpokenWord = !isRadioPlaybackSong(song) && kind.isSpokenWordListening currentSpokenWordIntroOutro = isSpokenWord ? spokenWordIntroOutro(for: song) : nil reconcileSpokenWordChapterRepeat() guard isSpokenWord != currentItemIsSpokenWord else { return } @@ -457,34 +457,16 @@ extension AudioPlayerService { } } - /// 片尾通过同一张曲终票据推进,避免解码结束回调再次切章。 + /// 片尾通过同一张曲终票据推进,避免解码结束回调再次切章(有声书与播客共用)。 func applySpokenWordOutroSkipIfNeeded() { - guard currentItemIsSpokenWord, isPlaying, let skip = currentSpokenWordIntroOutro, - let song = currentSong, let ticket = localPipelineAdvanceTicket else { return } + guard currentItemIsSpokenWord, let skip = currentSpokenWordIntroOutro, let song = currentSong else { return } let total = duration > 0 ? duration : song.duration - if !SpokenWordIntroOutroPolicy.shouldSkipOutro(position: currentTime, duration: total, skip: skip) { - if PodcastPlaybackState.shared.outroHandledEpisodeID == song.id { - PodcastPlaybackState.shared.outroHandledEpisodeID = nil - PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = nil - } - return - } - guard PodcastPlaybackState.shared.outroHandledEpisodeID != song.id, - automaticAdvanceDecision(for: ticket, trigger: "spoken-word-outro", consume: false, - transportIsActive: isPlaying) == .accepted else { return } - PodcastPlaybackState.shared.outroHandledEpisodeID = song.id - PodcastPlaybackState.shared.positionSaveSuppressedEpisodeID = song.id - plog("🎧 Spoken word: skipping the last \(skip.outroSeconds)s of '\(song.title)'") - let wasFinished = SpokenWordStore.shared.isFinished(songID: song.id) - SpokenWordStore.shared.markFinished(true, songIDs: [song.id]) - if !wasFinished { reportSpokenWordFinishedToServer(song) } - SpokenWordStore.shared.persistLocally() - pushServerSpokenWordPosition(song: song, position: total, duration: total, force: true) - let endedPlayID = playID - Task { @MainActor [weak self] in - guard let self, self.currentSong?.id == song.id, self.playID == endedPlayID else { return } - await self.handleTrackEnd(advanceTicket: ticket, trigger: "spoken-word-outro", - transportIsActive: self.isPlaying) + applyOutroSkipIfNeeded(for: song, skip: skip, totalDuration: total, trigger: "spoken-word-outro") { + plog("🎧 Spoken word: skipping the last \(skip.outroSeconds)s of '\(song.title)'") + let wasFinished = SpokenWordStore.shared.isFinished(songID: song.id) + SpokenWordStore.shared.markFinished(true, songIDs: [song.id]) + if !wasFinished { reportSpokenWordFinishedToServer(song) } + pushServerSpokenWordPosition(song: song, position: total, duration: total, force: true) } } diff --git a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift index 9a308161c..99406142c 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift @@ -121,7 +121,10 @@ extension AudioPlayerService { if airPlaySampleBufferFallbackSongID == song.id { return false } - let voiceBoostActive = SpokenWordStore.shared.isSpokenWord(song) && playbackSettings.spokenWordVoiceBoostEnabled + let voiceBoostActive = VoiceBoostActivationPolicy.isActive( + space: listeningSpace(of: song), + spokenWordEnabled: playbackSettings.spokenWordVoiceBoostEnabled + ) let effectsEnabled = (audioEffectsService.effectChainEnabled && (audioEffectsService.compressorEnabled || audioEffectsService.reverbEnabled)) || voiceBoostActive diff --git a/Primuse/Services/Audio/AudioPlayerService.swift b/Primuse/Services/Audio/AudioPlayerService.swift index ca9f0ec72..1183f65bf 100644 --- a/Primuse/Services/Audio/AudioPlayerService.swift +++ b/Primuse/Services/Audio/AudioPlayerService.swift @@ -3663,11 +3663,11 @@ extension AudioPlayerService { guard !self.isAppleMusicMode, self.activeAppleMusicRequestID == nil, appleMusic.activePlaybackRequestID == nil, - !self.isLiveRadio, !self.isCastingMode, (self.pendingMusicVideoPlayID == nil || self.pendingMusicVideoPlayID != self.playID), !self.isSystemMediaPlaybackActive else { return } + if self.isLiveRadio { self.recoverDecodedRadioTransportIfNeeded(); return } if self.localRouteFocusRecoveryOwnerPlayID == self.playID { if AudioSessionManager.shared.outputRouteIsBuiltIn { plog("🔧 Audio engine configuration change absorbed by local route focus recovery") diff --git a/Primuse/Services/Library/SpokenWordStore.swift b/Primuse/Services/Library/SpokenWordStore.swift index 01d9f8067..8e0eb7e23 100644 --- a/Primuse/Services/Library/SpokenWordStore.swift +++ b/Primuse/Services/Library/SpokenWordStore.swift @@ -1096,7 +1096,14 @@ extension SpokenWordStore { } func clearPosition(forSongID songID: String) { - guard removePosition(songID, at: Date()) else { return } + clearPositions(forSongIDs: [songID]) + } + + func clearPositions(forSongIDs songIDs: [String]) { + let now = Date() + var changed = false + for songID in songIDs where removePosition(songID, at: now) { changed = true } + guard changed else { return } completionRevision &+= 1 didChange(cloud: .prompt, progressOnly: true) } diff --git a/Primuse/Services/Radio/RadioPlaybackController.swift b/Primuse/Services/Radio/RadioPlaybackController.swift index c28f9561c..18149b623 100644 --- a/Primuse/Services/Radio/RadioPlaybackController.swift +++ b/Primuse/Services/Radio/RadioPlaybackController.swift @@ -73,7 +73,10 @@ final class RadioPlaybackController: NSObject { self.publishReadyState() self.inspectSubtitleTracksIfNeeded(generation: generation) case .failed: - self.publishFailure(item.error, shouldReconnect: false) + self.publishFailure( + item.error, + shouldReconnect: RadioReconnectPolicy.shouldReconnect(error: item.error) + ) case .unknown: break @unknown default: diff --git a/Primuse/Services/Radio/RadioStationsStore.swift b/Primuse/Services/Radio/RadioStationsStore.swift index 4d6ca5552..b512f7cd2 100644 --- a/Primuse/Services/Radio/RadioStationsStore.swift +++ b/Primuse/Services/Radio/RadioStationsStore.swift @@ -627,10 +627,8 @@ extension RadioStationsStore { persist() notifyChanged(ids: changedIDs) #if !os(tvOS) - // 台标发现的退避记录照样清掉,免得状态文件随「加了又删」无限长大。 - if !excludedIDs.isEmpty { - RadioLogoDiscoveryService.shared.forget(stationIDs: excludedIDs) - } + if !excludedIDs.isEmpty { RadioLogoDiscoveryService.shared.forget(stationIDs: excludedIDs) } + RadioTitleHistoryStore.shared.clear(stationIDs: changedIDs) #endif for id in deletedIDs { NotificationCenter.default.post( diff --git a/Primuse/Services/Radio/RadioTitleHistoryStore.swift b/Primuse/Services/Radio/RadioTitleHistoryStore.swift index 1b2839418..61fedee84 100644 --- a/Primuse/Services/Radio/RadioTitleHistoryStore.swift +++ b/Primuse/Services/Radio/RadioTitleHistoryStore.swift @@ -13,8 +13,6 @@ import PrimuseKit @MainActor @Observable final class RadioTitleHistoryStore { - static let shared = RadioTitleHistoryStore() - private(set) var log: [String: RadioStationHeardTitles] = [:] @ObservationIgnored private let storeURL: URL @@ -32,6 +30,10 @@ final class RadioTitleHistoryStore { } load() } +} + +extension RadioTitleHistoryStore { + static let shared = RadioTitleHistoryStore() /// 这个台听到过的标题,最新的在最前。 func entries(forStationID stationID: String) -> [RadioHeardTitle] { @@ -57,7 +59,15 @@ final class RadioTitleHistoryStore { /// 清掉一个台的记录(详情页「清除」、电台被删除时)。 func clear(stationID: String) { - guard log.removeValue(forKey: stationID) != nil else { return } + clear(stationIDs: [stationID]) + } + + func clear(stationIDs: [String]) { + var removedAny = false + for stationID in stationIDs where log.removeValue(forKey: stationID) != nil { + removedAny = true + } + guard removedAny else { return } scheduleSave() } diff --git a/Primuse/Services/Sources/AudiobookshelfSource.swift b/Primuse/Services/Sources/AudiobookshelfSource.swift index 931ca489b..785ceffad 100644 --- a/Primuse/Services/Sources/AudiobookshelfSource.swift +++ b/Primuse/Services/Sources/AudiobookshelfSource.swift @@ -432,8 +432,8 @@ extension AudiobookshelfSource: ServerListeningProgressConnector { try await connect() var result: [ServerListeningProgress] = [] for progress in try await client.mediaProgress() where wantedItemIDs.contains(progress.libraryItemID) { - guard let item = try await catalogItem(id: progress.libraryItemID) else { continue } - let stamp = progress.lastUpdate ?? Date() + guard let stamp = progress.lastUpdate, + let item = try await catalogItem(id: progress.libraryItemID) else { continue } for track in item.trackProgress(from: progress) { let path = AudiobookshelfAPIProtocol.trackPath( itemID: item.id, diff --git a/Primuse/Views/Library/SpokenWordLibraryView.swift b/Primuse/Views/Library/SpokenWordLibraryView.swift index 5d5ee2374..f5c2f3e09 100644 --- a/Primuse/Views/Library/SpokenWordLibraryView.swift +++ b/Primuse/Views/Library/SpokenWordLibraryView.swift @@ -1180,7 +1180,7 @@ struct SpokenWordShelfContent: View { .accessibilityIdentifier("spokenWord.book.removeAllCaches") if book.lastListenedAt != nil { Button(role: .destructive) { - for item in book.items { store.clearPosition(forSongID: item.id) } + store.clearPositions(forSongIDs: book.items.map(\.id)) store.markFinished(false, songIDs: book.items.map(\.id)) } label: { Label( diff --git a/Primuse/Views/Mac/MacRadioStationEditorView.swift b/Primuse/Views/Mac/MacRadioStationEditorView.swift index db73bf8a9..c3e5d80c8 100644 --- a/Primuse/Views/Mac/MacRadioStationEditorView.swift +++ b/Primuse/Views/Mac/MacRadioStationEditorView.swift @@ -478,14 +478,15 @@ struct MacRadioStationEditorView: View { forSongID: RadioStationArtworkResolutionPolicy.remoteLogoCacheSongID(for: id) ) } + let stream = RadioStationStreamCharacteristicsPolicy.resolve(streamURL: url, previousStation: station) let value = RadioStation( id: id, name: RadioStationValidation.normalizedName(name), streamURL: normalizedURL, logoData: logoData, logoFileName: logoFileName, - streamFormat: station?.streamFormat ?? RadioStreamFormat.inferred(from: url), - bitRate: station?.bitRate, + streamFormat: stream.streamFormat, + bitRate: stream.bitRate, createdAt: station?.createdAt ?? Date(), modifiedAt: Date(), lastPlayedAt: station?.lastPlayedAt, diff --git a/Primuse/Views/NowPlaying/ChapterListView.swift b/Primuse/Views/NowPlaying/ChapterListView.swift index 36280f498..4ec45387d 100644 --- a/Primuse/Views/NowPlaying/ChapterListView.swift +++ b/Primuse/Views/NowPlaying/ChapterListView.swift @@ -137,7 +137,7 @@ struct SpokenWordContentsView: View { .frame(height: 0.5) .padding(.leading, Self.tabLeadingInset) - if let song = player.currentSong { + if tab == .contents, let song = player.currentSong { HStack { Spacer() Button { chapterSong = song } label: { diff --git a/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift b/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift index aefb878e3..8cff3b680 100644 --- a/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift +++ b/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift @@ -160,21 +160,17 @@ enum SpokenWordPlayerText { /// "本章还剩约 18 分钟", in listening time at the book's speed. static func partRemaining(_ player: AudioPlayerService) -> String? { guard let remaining = player.spokenWordPartRemaining else { return nil } - let listening = SpokenWordNowPlayingPolicy.listeningTime( - forContent: remaining, - rate: player.currentSpokenWordRate - ) - // 没有章节的播客单集只有它自己,说「剩余」,不说「本章」。 let isWholeEpisode = player.currentListeningSpace == .podcast && player.spokenWordChapters.isEmpty - // 不到一分钟单独一句,免得拼成「本章还剩约 不到 1 分钟」。 - guard listening.isFinite, listening >= 60 else { + switch SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: remaining, rate: player.currentSpokenWordRate) { + case .underAMinute: let key: String.LocalizationValue = isWholeEpisode ? "podcast_remaining_under_minute" : "spoken_word_part_remaining_under_minute" return String(localized: key) + case .roundedMinutes(let rounded): + let key: String.LocalizationValue = isWholeEpisode + ? "podcast_remaining_format" : "spoken_word_part_remaining_format" + return String(format: String(localized: key), approximateDuration(rounded)) } - let key: String.LocalizationValue = isWholeEpisode - ? "podcast_remaining_format" : "spoken_word_part_remaining_format" - return String(format: String(localized: key), approximateDuration(listening)) } static func bookFraction(_ fraction: Double) -> String { @@ -238,6 +234,9 @@ enum SpokenWordPlayerText { /// What the sleep tile says while a timer is armed. Nil for a timed /// sleep, which draws its own countdown. static func sleepTileLabel(_ player: AudioPlayerService) -> String { + if let selection = player.selectedChapterSleep { + return String(format: String(localized: "sleep_after_selected_chapter_format"), selection.chapter.title) + } if player.sleepStopAfterChapter != nil { return String(localized: "spoken_word_sleep_chapter_short") } diff --git a/Primuse/Views/Radio/RadioStationsView.swift b/Primuse/Views/Radio/RadioStationsView.swift index 5c8bacb16..7a535cf39 100644 --- a/Primuse/Views/Radio/RadioStationsView.swift +++ b/Primuse/Views/Radio/RadioStationsView.swift @@ -2092,14 +2092,14 @@ struct RadioStationEditorView: View { forSongID: RadioStationArtworkResolutionPolicy.remoteLogoCacheSongID(for: id) ) } + let stream = RadioStationStreamCharacteristicsPolicy.resolve(streamURL: URL(string: normalizedURL)!, previousStation: station) let value = RadioStation( id: id, name: RadioStationValidation.normalizedName(name), streamURL: normalizedURL, logoData: logoData, logoFileName: logoFileName, - streamFormat: station?.streamFormat ?? RadioStreamFormat.inferred(from: URL(string: normalizedURL)!), - bitRate: station?.bitRate, + streamFormat: stream.streamFormat, bitRate: stream.bitRate, createdAt: station?.createdAt ?? Date(), modifiedAt: Date(), lastPlayedAt: station?.lastPlayedAt, diff --git a/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift new file mode 100644 index 000000000..e18daaae7 --- /dev/null +++ b/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift @@ -0,0 +1,84 @@ +import Foundation + +/// 直播电台连接失败时是否值得自动重连的分类策略。 +/// 瞬时网络错误(超时、断网、DNS/主机暂时不可达等)应触发指数退避重连; +/// 永久性配置错误(无效地址、TLS 拒绝、媒体格式不受支持等)不应死循环重连。 +public enum RadioReconnectPolicy { + private static let transientURLErrorCodes: Set = [ + NSURLErrorTimedOut, + NSURLErrorCannotFindHost, + NSURLErrorCannotConnectToHost, + NSURLErrorNetworkConnectionLost, + NSURLErrorDNSLookupFailed, + NSURLErrorResourceUnavailable, + NSURLErrorNotConnectedToInternet, + NSURLErrorCallIsActive, + NSURLErrorDataNotAllowed, + NSURLErrorInternationalRoamingOff, + ] + + public static func shouldReconnect(errorDomain: String, errorCode: Int) -> Bool { + errorDomain == NSURLErrorDomain && transientURLErrorCodes.contains(errorCode) + } + + public static func shouldReconnect(error: Error?) -> Bool { + guard let error else { return false } + let nsError = error as NSError + if shouldReconnect(errorDomain: nsError.domain, errorCode: nsError.code) { + return true + } + if let underlying = nsError.userInfo[NSUnderlyingErrorKey] as? NSError { + return shouldReconnect(errorDomain: underlying.domain, errorCode: underlying.code) + } + return false + } +} + +/// 编辑电台时决定流格式与码率:只有流地址未变时才沿用旧值,换了新流地址就重新推断格式并清空旧码率。 +public enum RadioStationStreamCharacteristicsPolicy { + public struct Characteristics: Equatable, Sendable { + public let streamFormat: RadioStreamFormat + public let bitRate: Int? + + public init(streamFormat: RadioStreamFormat, bitRate: Int?) { + self.streamFormat = streamFormat + self.bitRate = bitRate + } + } + + public static func resolve( + streamURL: URL, + previousStation: RadioStation? + ) -> Characteristics { + if let previousStation, previousStation.streamURL == streamURL.absoluteString { + return Characteristics( + streamFormat: previousStation.streamFormat, + bitRate: previousStation.bitRate + ) + } + return Characteristics( + streamFormat: RadioStreamFormat.inferred(from: streamURL), + bitRate: nil + ) + } +} + +/// 电台实时元数据更新时的封面解析:换了新曲目且新元数据未带封面时清空旧图,回退到台标; +/// 同一首歌重复推送或无标题更新时沿用当前封面。 +public enum RadioLiveMetadataPolicy { + public static func resolvedArtworkURL( + incoming: RadioLiveMetadata, + previousTitle: RadioStreamTitle?, + previousArtworkURL: String? + ) -> String? { + if let artwork = incoming.artworkURL { + return artwork + } + guard let incomingTitle = incoming.title else { + return previousArtworkURL + } + return RadioStreamTitleParser.isSameTrack(previousTitle, incomingTitle) + ? previousArtworkURL + : nil + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift index b3bd1976e..9f513a54e 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift @@ -53,6 +53,12 @@ public struct SpokenWordPartPosition: Equatable, Sendable { } } +/// 剩余收听时间的统一展示形态(iOS / macOS / tvOS 共用同一套一分钟边界与取整规则)。 +public enum SpokenWordRemainingTimeDisplay: Equatable, Sendable { + case underAMinute + case roundedMinutes(TimeInterval) +} + public enum SpokenWordNowPlayingPolicy { /// 已有关联文件时保留入口,读取中或失败也能进去查看和重试。 public static func offersTranscript( @@ -155,6 +161,15 @@ public enum SpokenWordNowPlayingPolicy { return seconds / rate } + public static func remainingTimeDisplay( + forContent seconds: TimeInterval, + rate: Float + ) -> SpokenWordRemainingTimeDisplay { + let listening = listeningTime(forContent: seconds, rate: rate) + guard listening.isFinite, listening >= 60 else { return .underAMinute } + return .roundedMinutes((listening / 60).rounded() * 60) + } + /// Content time left in the part being heard: to the next chapter mark /// when the file has marks, to the end of the file otherwise. Nil when /// the end is unknown. diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordVoiceBoostPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordVoiceBoostPolicy.swift index 80d2a1bae..fbd11333a 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordVoiceBoostPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordVoiceBoostPolicy.swift @@ -51,3 +51,21 @@ public enum SpokenWordVoiceBoostPolicy { return EQRenderConfiguration(filters: combined, preampDB: min(0, base.preampDB, safety)) } } + +/// 跨收听空间共用的语音增强启用策略(播客、有声书、以及支持人声增强的电台)。 +public enum VoiceBoostActivationPolicy { + public static func isActive( + space: ListeningSpace?, + spokenWordEnabled: Bool, + radioEnabled: Bool = false + ) -> Bool { + switch space { + case .spokenWord, .podcast: + return spokenWordEnabled + case .radio: + return radioEnabled + case .music, .ambient, nil: + return false + } + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/Streaming/AudiobookshelfServiceClient.swift b/PrimuseKit/Sources/PrimuseKit/Streaming/AudiobookshelfServiceClient.swift index 38f77f7f2..fc9c01416 100644 --- a/PrimuseKit/Sources/PrimuseKit/Streaming/AudiobookshelfServiceClient.swift +++ b/PrimuseKit/Sources/PrimuseKit/Streaming/AudiobookshelfServiceClient.swift @@ -1543,7 +1543,7 @@ public actor AudiobookshelfServiceClient { } private static func isAuthenticationFailure(_ statusCode: Int) -> Bool { - statusCode == 401 || statusCode == 403 + statusCode == 401 } private static func makeSession() -> URLSession { diff --git a/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift new file mode 100644 index 000000000..ff9c90251 --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift @@ -0,0 +1,107 @@ +import Foundation +import Testing +@testable import PrimuseKit + +@Suite("RadioPlaybackPolicy") +struct RadioPlaybackPolicyTests { + @Test func reconnectPolicyAcceptsTransientNetworkErrorsAndRejectsPermanentOnes() { + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.timedOut)) == true) + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.networkConnectionLost)) == true) + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.notConnectedToInternet)) == true) + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.cannotConnectToHost)) == true) + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.dnsLookupFailed)) == true) + + let wrapped = NSError( + domain: "AVFoundationErrorDomain", + code: -11800, + userInfo: [NSUnderlyingErrorKey: NSError(domain: NSURLErrorDomain, code: NSURLErrorNetworkConnectionLost)] + ) + #expect(RadioReconnectPolicy.shouldReconnect(error: wrapped) == true) + + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.badURL)) == false) + #expect(RadioReconnectPolicy.shouldReconnect(error: URLError(.serverCertificateUntrusted)) == false) + #expect(RadioReconnectPolicy.shouldReconnect(error: NSError(domain: "OtherDomain", code: -1001)) == false) + #expect(RadioReconnectPolicy.shouldReconnect(error: nil) == false) + } + + @Test func streamCharacteristicsPreserveMetadataOnlyWhenURLIsUnchanged() throws { + let originalURL = try #require(URL(string: "https://radio.example.com/stream.mp3")) + let flacURL = try #require(URL(string: "https://radio.example.com/lossless.flac")) + let unknownURL = try #require(URL(string: "https://radio.example.com/live")) + let existing = RadioStation( + name: "Demo FM", + streamURL: originalURL.absoluteString, + streamFormat: .aac, + bitRate: 192_000 + ) + + let unchanged = RadioStationStreamCharacteristicsPolicy.resolve( + streamURL: originalURL, + previousStation: existing + ) + #expect(unchanged.streamFormat == .aac) + #expect(unchanged.bitRate == 192_000) + + let changedToFlac = RadioStationStreamCharacteristicsPolicy.resolve( + streamURL: flacURL, + previousStation: existing + ) + #expect(changedToFlac.streamFormat == .flac) + #expect(changedToFlac.bitRate == nil) + + let changedToUnknown = RadioStationStreamCharacteristicsPolicy.resolve( + streamURL: unknownURL, + previousStation: existing + ) + #expect(changedToUnknown.streamFormat == .automatic) + #expect(changedToUnknown.bitRate == nil) + + let created = RadioStationStreamCharacteristicsPolicy.resolve( + streamURL: flacURL, + previousStation: nil + ) + #expect(created.streamFormat == .flac) + #expect(created.bitRate == nil) + } + + @Test func liveMetadataArtworkClearsWhenTrackChangesWithoutNewArtwork() { + let trackA = RadioStreamTitle(rawText: "Artist A - Song A", artist: "Artist A", title: "Song A") + let trackB = RadioStreamTitle(rawText: "Artist B - Song B", artist: "Artist B", title: "Song B") + + let sameTrackRepeat = RadioLiveMetadata(title: trackA, artworkURL: nil, homepageURL: nil) + #expect( + RadioLiveMetadataPolicy.resolvedArtworkURL( + incoming: sameTrackRepeat, + previousTitle: trackA, + previousArtworkURL: "https://img.example.com/a.jpg" + ) == "https://img.example.com/a.jpg" + ) + + let newTrackNoArt = RadioLiveMetadata(title: trackB, artworkURL: nil, homepageURL: nil) + #expect( + RadioLiveMetadataPolicy.resolvedArtworkURL( + incoming: newTrackNoArt, + previousTitle: trackA, + previousArtworkURL: "https://img.example.com/a.jpg" + ) == nil + ) + + let newTrackWithArt = RadioLiveMetadata(title: trackB, artworkURL: "https://img.example.com/b.jpg", homepageURL: nil) + #expect( + RadioLiveMetadataPolicy.resolvedArtworkURL( + incoming: newTrackWithArt, + previousTitle: trackA, + previousArtworkURL: "https://img.example.com/a.jpg" + ) == "https://img.example.com/b.jpg" + ) + + let homepageOnly = RadioLiveMetadata(title: nil, artworkURL: nil, homepageURL: "https://radio.example.com") + #expect( + RadioLiveMetadataPolicy.resolvedArtworkURL( + incoming: homepageOnly, + previousTitle: trackA, + previousArtworkURL: "https://img.example.com/a.jpg" + ) == "https://img.example.com/a.jpg" + ) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/VoiceBoostActivationPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/VoiceBoostActivationPolicyTests.swift new file mode 100644 index 000000000..f15837424 --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/VoiceBoostActivationPolicyTests.swift @@ -0,0 +1,30 @@ +import Foundation +import Testing +@testable import PrimuseKit + +@Suite("VoiceBoostActivationPolicy & SpokenWordRemainingTimeDisplay") +struct VoiceBoostActivationPolicyTests { + @Test func voiceBoostPolicyAppliesAcrossSpokenSpacesAndOptionalRadio() { + #expect(VoiceBoostActivationPolicy.isActive(space: .podcast, spokenWordEnabled: true) == true) + #expect(VoiceBoostActivationPolicy.isActive(space: .spokenWord, spokenWordEnabled: true) == true) + #expect(VoiceBoostActivationPolicy.isActive(space: .podcast, spokenWordEnabled: false) == false) + #expect(VoiceBoostActivationPolicy.isActive(space: .spokenWord, spokenWordEnabled: false) == false) + + #expect(VoiceBoostActivationPolicy.isActive(space: .radio, spokenWordEnabled: true) == false) + #expect(VoiceBoostActivationPolicy.isActive(space: .radio, spokenWordEnabled: false, radioEnabled: true) == true) + + #expect(VoiceBoostActivationPolicy.isActive(space: .music, spokenWordEnabled: true, radioEnabled: true) == false) + #expect(VoiceBoostActivationPolicy.isActive(space: .ambient, spokenWordEnabled: true, radioEnabled: true) == false) + #expect(VoiceBoostActivationPolicy.isActive(space: nil, spokenWordEnabled: true, radioEnabled: true) == false) + } + + @Test func remainingTimeDisplaySharesOneMinuteBoundaryAndRounding() { + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: 0, rate: 1.0) == .underAMinute) + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: -5, rate: 1.0) == .underAMinute) + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: .nan, rate: 1.0) == .underAMinute) + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: 80, rate: 1.5) == .underAMinute) + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: 60, rate: 1.0) == .roundedMinutes(60)) + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: 90, rate: 1.0) == .roundedMinutes(120)) + #expect(SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: 3_600, rate: 1.5) == .roundedMinutes(2_400)) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Streaming/AudiobookshelfServiceTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Streaming/AudiobookshelfServiceTests.swift index bd1fb9d3a..ca180f52b 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Streaming/AudiobookshelfServiceTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Streaming/AudiobookshelfServiceTests.swift @@ -521,6 +521,16 @@ struct AudiobookshelfDeletionTests { _ = try await client.deleteTrack(reference: file) } } + + /// 403 是权限不足而非会话过期,读接口也不应误判为认证失效或触发换 token 重试。 + @Test func forbiddenOnReadEndpointIsBadServerResponseNotAuthenticationFailure() async throws { + let recorder = AudiobookshelfDeletionRequests() + let client = Self.client(status: 403, recorder: recorder) + await #expect(throws: AudiobookshelfServiceError.badServerResponse(403)) { + _ = try await client.mediaProgress() + } + #expect(await recorder.requests.count == 1) + } } private actor AudiobookshelfDeletionRequests { diff --git a/PrimuseTV/Model/TVStore.swift b/PrimuseTV/Model/TVStore.swift index d69a466b0..315cae8e6 100644 --- a/PrimuseTV/Model/TVStore.swift +++ b/PrimuseTV/Model/TVStore.swift @@ -6577,7 +6577,8 @@ extension TVStore { } func spokenWordIntroOutro(for song: Song) -> SpokenWordIntroOutro? { - guard SpokenWordStore.shared.kind(for: song) == .spokenWord, + guard SpokenWordStore.shared.kind(for: song).isSpokenWordListening, + !PodcastPlaybackSong.isEpisode(song), song.appliedPlaybackRange == nil, !isMedleyActive, let bookID = spokenWordBookID(forSongID: song.id) else { return nil } if currentSongID == song.id, currentPlaybackRange != nil { return nil } diff --git a/PrimuseTV/Views/TVSpokenWordNowPlaying.swift b/PrimuseTV/Views/TVSpokenWordNowPlaying.swift index 3a726ff80..f3a80a1ee 100644 --- a/PrimuseTV/Views/TVSpokenWordNowPlaying.swift +++ b/PrimuseTV/Views/TVSpokenWordNowPlaying.swift @@ -60,14 +60,18 @@ enum TVSpokenWordText { /// 「本章还剩约 18 分钟」,按这本书的语速折算。 static func partRemaining(_ store: TVStore) -> String? { guard let content = store.spokenWordPartRemaining else { return nil } - let remaining = SpokenWordNowPlayingPolicy.listeningTime( - forContent: content, - rate: store.currentSpokenWordRate - ) // 没有章节的播客单集只有它自己,说「剩余」,不说「本章」。 - let key: String.LocalizationValue = store.currentItemIsPodcast && store.spokenWordChapters.isEmpty - ? "podcast_remaining_format" : "spoken_word_part_remaining_format" - return String(format: String(localized: key), approximateDuration(remaining)) + let isWholeEpisode = store.currentItemIsPodcast && store.spokenWordChapters.isEmpty + switch SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: content, rate: store.currentSpokenWordRate) { + case .underAMinute: + let key: String.LocalizationValue = isWholeEpisode + ? "podcast_remaining_under_minute" : "spoken_word_part_remaining_under_minute" + return String(localized: key) + case .roundedMinutes(let rounded): + let key: String.LocalizationValue = isWholeEpisode + ? "podcast_remaining_format" : "spoken_word_part_remaining_format" + return String(format: String(localized: key), TVSpokenWordBooks.duration(rounded)) + } } static func sleepLabel(_ store: TVStore) -> String { @@ -439,9 +443,13 @@ private struct TVSpokenWordChoicePanel: View { TVColor.bg.opacity(0.52).ignoresSafeArea() VStack(alignment: .leading, spacing: 22) { Text(title).tvFont(.sectionTitle).foregroundStyle(TVColor.text) - VStack(alignment: .leading, spacing: 12) { - content() + ScrollView { + VStack(alignment: .leading, spacing: 12) { + content() + } + .padding(4) } + .frame(maxHeight: 620) .focusSection() if let footnote { Text(footnote).tvFont(.caption).foregroundStyle(TVColor.textFaint) diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift new file mode 100644 index 000000000..731de3d96 --- /dev/null +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -0,0 +1,161 @@ +import Foundation +import PrimuseKit +import XCTest +@testable import Primuse + +@MainActor +final class ListeningSpacesReliabilityTests: XCTestCase { + private var cleanups: [() -> Void] = [] + + override func tearDown() { + for cleanup in cleanups.reversed() { cleanup() } + cleanups.removeAll() + super.tearDown() + } + + private func makeTempDirectory() -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("primuse-spaces-\(UUID().uuidString)", isDirectory: true) + try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + cleanups.append { try? FileManager.default.removeItem(at: url) } + return url + } + + func testRadioSongFromSpokenWordTaggedSourceNeverActivatesSpokenWordMode() { + let sourceID = "abs-spoken-source-\(UUID().uuidString)" + let store = SpokenWordStore.shared + cleanups.append { store.setWholeSourceKind(nil, sourceID: sourceID) } + store.setWholeSourceKind(.spokenWord, sourceID: sourceID) + + let station = RadioStation( + id: "station-\(UUID().uuidString)", + name: "Talk Radio", + streamURL: "https://radio.example.com/live.mp3", + sourceID: sourceID, + serverStationID: "srv-1" + ) + let radioSong = station.playbackSong + let player = AudioPlayerService() + + XCTAssertEqual(player.listeningSpace(of: radioSong), .radio) + player.currentSong = radioSong + player.handleSpokenWordItemChange(to: radioSong) + XCTAssertFalse(player.currentItemIsSpokenWord) + + player.refreshCurrentItemContentKind() + XCTAssertFalse(player.currentItemIsSpokenWord) + } + + func testSpokenWordStoreClearPositionsBatchesIntoSingleNotification() { + let store = SpokenWordStore.shared + let ids = (1...3).map { "batch-clear-\(UUID().uuidString)-\($0)" } + cleanups.append { store.clearPositions(forSongIDs: ids) } + for id in ids { + store.rememberPosition(120, duration: 600, forSongID: id) + } + + let startRevision = store.completionRevision + var notificationCount = 0 + let token = NotificationCenter.default.addObserver( + forName: .primuseSpokenWordDidChange, + object: nil, + queue: .main + ) { _ in + notificationCount += 1 + } + cleanups.append { NotificationCenter.default.removeObserver(token) } + + store.clearPositions(forSongIDs: ids) + + XCTAssertEqual(store.completionRevision, startRevision + 1) + XCTAssertEqual(notificationCount, 1) + for id in ids { + XCTAssertNil(store.position(forSongID: id)) + } + } + + func testRadioTitleHistoryStoreClearsMultipleDeletedStations() { + let dir = makeTempDirectory() + let store = RadioTitleHistoryStore(storeURL: dir.appendingPathComponent("history.json")) + let meta = RadioLiveMetadata( + title: RadioStreamTitle(rawText: "Artist - Song", artist: "Artist", title: "Song"), + artworkURL: nil, + homepageURL: nil + ) + store.record(meta, stationID: "s1") + store.record(meta, stationID: "s2") + store.record(meta, stationID: "s3") + XCTAssertEqual(store.entries(forStationID: "s1").count, 1) + XCTAssertEqual(store.entries(forStationID: "s2").count, 1) + XCTAssertEqual(store.entries(forStationID: "s3").count, 1) + + store.clear(stationIDs: ["s1", "s3"]) + + XCTAssertTrue(store.entries(forStationID: "s1").isEmpty) + XCTAssertEqual(store.entries(forStationID: "s2").count, 1) + XCTAssertTrue(store.entries(forStationID: "s3").isEmpty) + } + + func testAirPlaySampleBufferBackendUsesSharedVoiceBoostPolicyAcrossSpaces() { + let player = AudioPlayerService() + let previousVoiceBoost = player.playbackSettings.spokenWordVoiceBoostEnabled + let previousEQ = player.equalizerService.isEnabled + let previousChain = player.audioEffectsService.effectChainEnabled + let previousSpatial = player.playbackSettings.spatialAudioEnabled + let previousCrossfade = player.playbackSettings.crossfadeEnabled + cleanups.append { + player.playbackSettings.spokenWordVoiceBoostEnabled = previousVoiceBoost + player.equalizerService.isEnabled = previousEQ + player.audioEffectsService.effectChainEnabled = previousChain + player.playbackSettings.spatialAudioEnabled = previousSpatial + player.playbackSettings.crossfadeEnabled = previousCrossfade + } + + player.equalizerService.isEnabled = false + player.audioEffectsService.effectChainEnabled = false + player.playbackSettings.spatialAudioEnabled = false + player.playbackSettings.crossfadeEnabled = false + player.playbackSettings.spokenWordVoiceBoostEnabled = true + + let bookSong = Song( + id: "book-\(UUID().uuidString)", + title: "Chapter 1", + artistName: "Author", + duration: 1_800, + fileFormat: .m4a, + filePath: "/books/ch1.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + let musicSong = Song( + id: "music-\(UUID().uuidString)", + title: "Track 1", + artistName: "Artist", + duration: 240, + fileFormat: .flac, + filePath: "/music/t1.flac", + sourceID: "local-music", + genre: "Rock" + ) + + XCTAssertFalse(player.shouldUseAirPlaySampleBufferBackend(for: bookSong, isAirPlayOutput: true)) + XCTAssertTrue(player.shouldUseAirPlaySampleBufferBackend(for: musicSong, isAirPlayOutput: true)) + } + + func testSpokenWordSleepTileLabelShowsSelectedChapterTitle() throws { + let player = AudioPlayerService() + let chapter = SpokenWordSleepChapter(songID: "ch-1", title: "Chapter 7", startTime: 0, endTime: 600) + let selection = try XCTUnwrap( + SpokenWordSleepSelection( + chapter: chapter, + orderedSongIDs: ["ch-1"], + currentSongID: "ch-1", + position: 10, + chapterRevision: nil + ) + ) + player.selectedChapterSleep = selection + let label = SpokenWordPlayerText.sleepTileLabel(player) + XCTAssertTrue(label.contains("Chapter 7"), "Expected selected chapter title in '\(label)'") + } +} diff --git a/project.yml b/project.yml index 5b3436e87..deedc72e4 100644 --- a/project.yml +++ b/project.yml @@ -409,6 +409,7 @@ targets: - path: PrimuseTests/LastFmSimilarQuotaTests.swift - path: PrimuseTests/PodcastRequestQuotaTests.swift - path: PrimuseTests/PodcastReliabilityTests.swift + - path: PrimuseTests/ListeningSpacesReliabilityTests.swift - path: PrimuseTests/CrossFeatureQuotaTests.swift - path: PrimuseTests/RadioDirectoryQuotaTests.swift - path: PrimuseTests/ExternalPlaylistQuotaTests.swift From 195c03343e1bf7901299c03c3766cf3c4c9b4b34 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 16:34:03 -0500 Subject: [PATCH 03/15] =?UTF-8?q?=E5=8F=82=E8=80=83=20Overcast=20=E6=99=BA?= =?UTF-8?q?=E8=83=BD=E5=80=8D=E9=80=9F=E4=BC=98=E5=8C=96=E6=9C=89=E5=A3=B0?= =?UTF-8?q?=E5=86=85=E5=AE=B9=203=20=E5=80=8D=E9=80=9F=E3=80=81=E5=A4=9A?= =?UTF-8?q?=E6=A1=A3=E6=99=BA=E8=83=BD=E9=80=9F=E5=BA=A6=E4=B8=8E=E6=8C=89?= =?UTF-8?q?=E9=A1=B9=E8=A6=86=E7=9B=96=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 10 + .../Resources/ar.lproj/Localizable.strings | 12 + .../Resources/de.lproj/Localizable.strings | 12 + .../Resources/en.lproj/Localizable.strings | 12 + .../Resources/es-MX.lproj/Localizable.strings | 12 + .../Resources/fr.lproj/Localizable.strings | 12 + .../Resources/hi.lproj/Localizable.strings | 12 + .../Resources/ja.lproj/Localizable.strings | 12 + .../Resources/ko.lproj/Localizable.strings | 12 + .../Resources/pl.lproj/Localizable.strings | 12 + .../Resources/pt-BR.lproj/Localizable.strings | 12 + .../Resources/ru.lproj/Localizable.strings | 12 + .../Resources/th.lproj/Localizable.strings | 12 + .../Resources/tr.lproj/Localizable.strings | 12 + .../Resources/uk.lproj/Localizable.strings | 12 + .../zh-Hans.lproj/Localizable.strings | 12 + .../zh-Hant.lproj/Localizable.strings | 12 + .../Audio/AudioEngine+Varispeed.swift | 14 +- Primuse/Services/Audio/AudioEngine.swift | 6 +- .../Audio/AudioPlayerService+SmartSpeed.swift | 94 ++++- .../Audio/AudioPlayerService+Varispeed.swift | 7 +- .../Audio/PlaybackSettingsStore.swift | 17 + .../Services/Library/SpokenWordStore.swift | 8 +- .../Views/Library/SpokenWordLibraryView.swift | 44 +-- Primuse/Views/Mac/MacSettingsView.swift | 22 +- .../SpokenWordAudioEffectsSheet.swift | 372 ++++++++++++++++++ .../SpokenWordPlayerComponents.swift | 70 ++-- Primuse/Views/Settings/SettingsView.swift | 10 + .../Audio/PlaybackTimePitchProcessor.swift | 2 +- .../SpokenWordAudioEffectsPolicy.swift | 162 ++++++++ .../SpokenWordListeningPolicy.swift | 48 ++- .../SpokenWord/SpokenWordSmartSpeed.swift | 69 ++++ .../PlaybackTimePitchProcessorTests.swift | 7 +- .../SpokenWordAudioEffectsPolicyTests.swift | 87 ++++ .../SpokenWordListeningPolicyTests.swift | 32 +- .../SpokenWordNowPlayingPolicyTests.swift | 4 +- .../SpokenWordSmartSpeedTests.swift | 36 ++ .../SpokenWordSyncPolicyTests.swift | 4 +- PrimuseTV/Audio/TVAudioEngine.swift | 2 +- PrimuseTV/Audio/TVSFBEngine.swift | 2 +- .../ListeningSpacesReliabilityTests.swift | 83 ++++ 41 files changed, 1269 insertions(+), 135 deletions(-) create mode 100644 Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift create mode 100644 PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordAudioEffectsPolicy.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordAudioEffectsPolicyTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index cf274df54..757696698 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -960,6 +960,7 @@ 47288F24B75CA733589D5E01 /* ListeningSpacePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 941D54E9A1C2C7137C9BE775 /* ListeningSpacePolicy.swift */; }; 475191F1ADA076E5E7443574 /* LibrarySnapshotSync+KeptStages.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89FF14DBB3310207F68760C3 /* LibrarySnapshotSync+KeptStages.swift */; }; 4760452E65ABD40929A63842 /* CarPlaySceneDelegate+AudioQualityPopup.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA9F51698118F20BD37ABB5 /* CarPlaySceneDelegate+AudioQualityPopup.swift */; }; + 4762E3A1D33DF00109E3D3ED /* SpokenWordAudioEffectsSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A3E3A8C5CAAC5102749BCE /* SpokenWordAudioEffectsSheet.swift */; }; 476ABB1A64AC9D81950EA6CD /* OpenAICompatibleProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 182840B263E637C233CBB7DE /* OpenAICompatibleProvider.swift */; }; 476EC9D09A58CC86AE48AD86 /* DislikedSongsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 017BCFAEA8531A27C8DED490 /* DislikedSongsView.swift */; }; 47739E0B4A1BF80DBFEAEACB /* HomeSectionsSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F9BAE1D915901E05BF85719 /* HomeSectionsSettingsView.swift */; }; @@ -1280,6 +1281,7 @@ 5EDA9AE3EF12EAEA6FA3F7C5 /* SongPathPresentationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CA0107D4DD6B04392DE7723 /* SongPathPresentationPolicy.swift */; }; 5EE3D0480E41B3A6A36227B2 /* LibraryInsight.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA3D8782700F6AEAAFDD3AD4 /* LibraryInsight.swift */; }; 5EFBE59C148CC748DAF8D577 /* LibraryCatalogSchema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16B6915A4612311D7BE159BC /* LibraryCatalogSchema.swift */; }; + 5F133463C5181309B2302647 /* SpokenWordAudioEffectsPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEE7E68003963C8CE6C0FC75 /* SpokenWordAudioEffectsPolicy.swift */; }; 5F193CB416043B051E3D3B6C /* AlbumMetadataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41755983E9DC7312DACA2DDA /* AlbumMetadataTests.swift */; }; 5F41A5A6CB3BF0FA9AF20ADE /* WordLyricsAlignmentService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01B1A9B933225AD47640E876 /* WordLyricsAlignmentService.swift */; }; 5F4635DA93BF420FA5F4A70A /* MacCredentialKeychainTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 509C6BA1A4E5385E8395839E /* MacCredentialKeychainTests.swift */; }; @@ -2775,6 +2777,7 @@ CD9A71AAAF2507192D415B71 /* AppleMusicLibrarySource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BE82C5DF65A566D6D3CDE4E /* AppleMusicLibrarySource.swift */; }; CDBD0B8CE2640CC6AE815FAD /* PlayerTextFont.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFB1A119B3344B83A31B67D5 /* PlayerTextFont.swift */; }; CDCB2B131606F12140CD5AF1 /* LibrarySearchIndex+CatalogPreparation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70995769C2339FBC71FD4F36 /* LibrarySearchIndex+CatalogPreparation.swift */; }; + CE032D95D148739697F195D6 /* SpokenWordAudioEffectsSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A3E3A8C5CAAC5102749BCE /* SpokenWordAudioEffectsSheet.swift */; }; CE14FE12FB1FF6D66625D2FD /* ListeningShareDownload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EF0BEBF95B0084EC26BCBC0 /* ListeningShareDownload.swift */; }; CE40D8BDEF11398B40964F4A /* ParametricEqualizerUnit.swift in Sources */ = {isa = PBXBuildFile; fileRef = E29AA1A6283A60FD0B2BA640 /* ParametricEqualizerUnit.swift */; }; CE52AE04E3ADA2E8AD2BE6A3 /* AudioStreamHeaderParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = B89BB98A6C3A6867E408C907 /* AudioStreamHeaderParser.swift */; }; @@ -3911,6 +3914,7 @@ 1576FEA02472EAE01D3B8952 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/InfoPlist.strings; sourceTree = ""; }; 158F8D4350FF71B06C4DD26F /* AIRecommendationLibraryView+Catalog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AIRecommendationLibraryView+Catalog.swift"; sourceTree = ""; }; 1596A6C3EAF6B4960406BBCC /* PortableSnapshotPreparationStreamingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PortableSnapshotPreparationStreamingTests.swift; sourceTree = ""; }; + 15A3E3A8C5CAAC5102749BCE /* SpokenWordAudioEffectsSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordAudioEffectsSheet.swift; sourceTree = ""; }; 15DE24BBD4912430AE9639AB /* ListeningIntentAI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListeningIntentAI.swift; sourceTree = ""; }; 15E3F86552566DF46DEEF008 /* OfflineBatchRetryPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OfflineBatchRetryPolicy.swift; sourceTree = ""; }; 1603266ACAF7DE873AAA857A /* EmbeddedKaraokeAudio.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmbeddedKaraokeAudio.swift; sourceTree = ""; }; @@ -5388,6 +5392,7 @@ AEC319E38B82FE71D5DCEA09 /* MacHomeRecentlyAddedPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacHomeRecentlyAddedPage.swift; sourceTree = ""; }; AEC39297EEA0DE678B391304 /* es-MX */ = {isa = PBXFileReference; lastKnownFileType = text.plist; name = "es-MX"; path = "es-MX.lproj/AppIntentVocabulary.plist"; sourceTree = ""; }; AECF36E20CC45C0A79E011AC /* LibraryCatalog+ReleaseCategoryHealth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibraryCatalog+ReleaseCategoryHealth.swift"; sourceTree = ""; }; + AEE7E68003963C8CE6C0FC75 /* SpokenWordAudioEffectsPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordAudioEffectsPolicy.swift; sourceTree = ""; }; AF1D8CFBCDA161E39FD948E2 /* TVSpokenWordNowPlaying.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TVSpokenWordNowPlaying.swift; sourceTree = ""; }; AF1E7A40D2D8B42A419AFA43 /* pt-BR */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/CacheSync.strings"; sourceTree = ""; }; AF23E2C32C29F875836D06BE /* FFmpegDecoderBridge.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FFmpegDecoderBridge.m; sourceTree = ""; }; @@ -7256,6 +7261,7 @@ 1E4C3266509DEBD737D2392F /* SpokenTranscriptGenerationSheet.swift */, DC8CBD3E3429A33B962A9388 /* SpokenTranscriptImportSheet.swift */, B54E4A33620B159934373C2C /* SpokenTranscriptSourcePresentations.swift */, + 15A3E3A8C5CAAC5102749BCE /* SpokenWordAudioEffectsSheet.swift */, 28A13C5C56C77AC4A1F8232C /* SpokenWordPlayerComponents.swift */, 73022D35CBBFA6DC0236DE62 /* SpokenWordTranscriptSelection.swift */, FDD0AECB6D461DFB993C8CD2 /* TabletopQueueStrip.swift */, @@ -7575,6 +7581,7 @@ A030D8AD71D4A5246B0645C8 /* SpokenChapterImport.swift */, 2CC0AAFC72677216495BC44E /* SpokenTranscriptImport.swift */, F23E2B9031979010BC0EE0DF /* SpokenTranscriptSources.swift */, + AEE7E68003963C8CE6C0FC75 /* SpokenWordAudioEffectsPolicy.swift */, F67D0DFD2D268A69E3E3568D /* SpokenWordBookFollowPolicy.swift */, B3A79EB60A0F510ECD29B6FC /* SpokenWordBookGroupingRules.swift */, A5C9BAC7DCEC31B638DBB2B3 /* SpokenWordBookItem+Song.swift */, @@ -11067,6 +11074,7 @@ 2C720880F1B5659342E41792 /* SpokenTranscriptGeneration.swift in Sources */, DF4E4F5457AC0D4D22675EBD /* SpokenTranscriptImport.swift in Sources */, 9E07EEDDB79A29D275DD6B52 /* SpokenTranscriptSources.swift in Sources */, + 5F133463C5181309B2302647 /* SpokenWordAudioEffectsPolicy.swift in Sources */, AB5E7703566D4F60C875F838 /* SpokenWordBookFollowPolicy.swift in Sources */, 818C876AA92CF08C1851849C /* SpokenWordBookGroupingRules.swift in Sources */, 1BEF8A9377F00D14A5DA5A37 /* SpokenWordBookItem+Song.swift in Sources */, @@ -12054,6 +12062,7 @@ 85960C7E87FC73B994919019 /* SpokenTranscriptGenerator.swift in Sources */, 22D2BC69F14896363AA2F92C /* SpokenTranscriptImportSheet.swift in Sources */, 750E9F37E5140B1D43987936 /* SpokenTranscriptSourcePresentations.swift in Sources */, + CE032D95D148739697F195D6 /* SpokenWordAudioEffectsSheet.swift in Sources */, E832C29C4C386EE38301229F /* SpokenWordCatalogShelf.swift in Sources */, 620C22596174B16A2958B096 /* SpokenWordLibraryView.swift in Sources */, 7814030E97D0D88E7252DC4D /* SpokenWordPlayerComponents.swift in Sources */, @@ -13271,6 +13280,7 @@ 484C0D5CA776650444786167 /* SpokenTranscriptGenerator.swift in Sources */, 65213C75F6A370A4B6DA929E /* SpokenTranscriptImportSheet.swift in Sources */, 4198A9CC7086C3250F527F22 /* SpokenTranscriptSourcePresentations.swift in Sources */, + 4762E3A1D33DF00109E3D3ED /* SpokenWordAudioEffectsSheet.swift in Sources */, F78F387A926C7B0F45F8B8E6 /* SpokenWordCatalogShelf.swift in Sources */, 278054AFB875BFD0D4548D29 /* SpokenWordLibraryView.swift in Sources */, 77D0B826FFF2C7ECF3507191 /* SpokenWordPlayerComponents.swift in Sources */, diff --git a/Primuse/Resources/ar.lproj/Localizable.strings b/Primuse/Resources/ar.lproj/Localizable.strings index af85e28c5..b7893f44c 100644 --- a/Primuse/Resources/ar.lproj/Localizable.strings +++ b/Primuse/Resources/ar.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "لا يمكن أن تحتوي القيمة على فواصل أسطر أو أحرف فارغة."; "custom_header_error_value_too_long" = "القيمة طويلة جدًا (4096 بايت كحد أقصى)."; "custom_header_error_too_many" = "يمكن إضافة 16 رأسًا كحد أقصى."; +"smart_speed_level_title" = "مستوى السرعة الذكية"; +"smart_speed_level_off" = "إيقاف"; +"smart_speed_level_mild" = "خفيف"; +"smart_speed_level_standard" = "قياسي"; +"smart_speed_level_strong" = "قوي"; +"audio_effects_scope_all" = "الكل"; +"audio_effects_scope_this_show" = "هذا البرنامج"; +"audio_effects_scope_this_book" = "هذا الكتاب"; +"audio_effects_reset_custom" = "إعادة تعيين"; +"audio_effects_effective_rate_format" = "≈ %@ فعليًا"; +"radio_voice_boost" = "تعزيز الصوت للراديو"; +"radio_voice_boost_desc" = "يعيد استخدام تعزيز الصوت لبث الراديو المفكك محليًا، مثالي لمحطات الأخبار والحوار."; diff --git a/Primuse/Resources/de.lproj/Localizable.strings b/Primuse/Resources/de.lproj/Localizable.strings index c69570130..3c8b64061 100644 --- a/Primuse/Resources/de.lproj/Localizable.strings +++ b/Primuse/Resources/de.lproj/Localizable.strings @@ -8452,3 +8452,15 @@ "custom_header_error_invalid_value" = "Der Wert darf keine Zeilenumbrüche oder Nullzeichen enthalten."; "custom_header_error_value_too_long" = "Der Wert ist zu lang (höchstens 4.096 Byte)."; "custom_header_error_too_many" = "Es können höchstens 16 Header hinzugefügt werden."; +"smart_speed_level_title" = "Smart-Speed-Stärke"; +"smart_speed_level_off" = "Aus"; +"smart_speed_level_mild" = "Sanft"; +"smart_speed_level_standard" = "Standard"; +"smart_speed_level_strong" = "Stark"; +"audio_effects_scope_all" = "Alle"; +"audio_effects_scope_this_show" = "Diese Sendung"; +"audio_effects_scope_this_book" = "Dieses Buch"; +"audio_effects_reset_custom" = "Zurücksetzen"; +"audio_effects_effective_rate_format" = "≈ %@ effektiv"; +"radio_voice_boost" = "Radio-Stimmverstärkung"; +"radio_voice_boost_desc" = "Nutzt die Stimmverstärkung auch für lokal dekodierte Radiosender, ideal für Nachrichten und Talk-Radio."; diff --git a/Primuse/Resources/en.lproj/Localizable.strings b/Primuse/Resources/en.lproj/Localizable.strings index 8e9395b05..9b9770561 100644 --- a/Primuse/Resources/en.lproj/Localizable.strings +++ b/Primuse/Resources/en.lproj/Localizable.strings @@ -8214,3 +8214,15 @@ "custom_header_error_invalid_value" = "The value cannot contain line breaks or null characters."; "custom_header_error_value_too_long" = "The value is too long (4,096 bytes at most)."; "custom_header_error_too_many" = "At most 16 headers can be added."; +"smart_speed_level_title" = "Smart Speed Level"; +"smart_speed_level_off" = "Off"; +"smart_speed_level_mild" = "Mild"; +"smart_speed_level_standard" = "Standard"; +"smart_speed_level_strong" = "Strong"; +"audio_effects_scope_all" = "All"; +"audio_effects_scope_this_show" = "This Show"; +"audio_effects_scope_this_book" = "This Book"; +"audio_effects_reset_custom" = "Reset"; +"audio_effects_effective_rate_format" = "≈ %@ effective"; +"radio_voice_boost" = "Radio Voice Boost"; +"radio_voice_boost_desc" = "Reuses Voice Boost for locally decoded radio streams, ideal for news and talk stations."; diff --git a/Primuse/Resources/es-MX.lproj/Localizable.strings b/Primuse/Resources/es-MX.lproj/Localizable.strings index 6c1027376..e6d2d1b14 100644 --- a/Primuse/Resources/es-MX.lproj/Localizable.strings +++ b/Primuse/Resources/es-MX.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "El valor no puede contener saltos de línea ni caracteres nulos."; "custom_header_error_value_too_long" = "El valor es demasiado largo (máximo 4.096 bytes)."; "custom_header_error_too_many" = "Se pueden agregar como máximo 16 encabezados."; +"smart_speed_level_title" = "Nivel de velocidad inteligente"; +"smart_speed_level_off" = "Desactivado"; +"smart_speed_level_mild" = "Suave"; +"smart_speed_level_standard" = "Estándar"; +"smart_speed_level_strong" = "Fuerte"; +"audio_effects_scope_all" = "Todos"; +"audio_effects_scope_this_show" = "Este programa"; +"audio_effects_scope_this_book" = "Este libro"; +"audio_effects_reset_custom" = "Restablecer"; +"audio_effects_effective_rate_format" = "≈ %@ efectivo"; +"radio_voice_boost" = "Realce de voz en radio"; +"radio_voice_boost_desc" = "Reutiliza el realce de voz en estaciones decodificadas localmente, ideal para noticias y programas hablados."; diff --git a/Primuse/Resources/fr.lproj/Localizable.strings b/Primuse/Resources/fr.lproj/Localizable.strings index 9ee78dc60..0e2b8af08 100644 --- a/Primuse/Resources/fr.lproj/Localizable.strings +++ b/Primuse/Resources/fr.lproj/Localizable.strings @@ -8452,3 +8452,15 @@ "custom_header_error_invalid_value" = "La valeur ne peut pas contenir de saut de ligne ni de caractère nul."; "custom_header_error_value_too_long" = "La valeur est trop longue (4 096 octets maximum)."; "custom_header_error_too_many" = "16 en-têtes au maximum."; +"smart_speed_level_title" = "Niveau de vitesse intelligente"; +"smart_speed_level_off" = "Désactivé"; +"smart_speed_level_mild" = "Doux"; +"smart_speed_level_standard" = "Standard"; +"smart_speed_level_strong" = "Fort"; +"audio_effects_scope_all" = "Tout"; +"audio_effects_scope_this_show" = "Cette émission"; +"audio_effects_scope_this_book" = "Ce livre"; +"audio_effects_reset_custom" = "Réinitialiser"; +"audio_effects_effective_rate_format" = "≈ %@ effectif"; +"radio_voice_boost" = "Amplification vocale radio"; +"radio_voice_boost_desc" = "Réutilise l’amplification vocale sur les flux radio décodés localement, idéal pour l’info et les débats."; diff --git a/Primuse/Resources/hi.lproj/Localizable.strings b/Primuse/Resources/hi.lproj/Localizable.strings index 201b3366b..1d65cbfcf 100644 --- a/Primuse/Resources/hi.lproj/Localizable.strings +++ b/Primuse/Resources/hi.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "मान में लाइन ब्रेक या नल वर्ण नहीं हो सकते।"; "custom_header_error_value_too_long" = "मान बहुत लंबा है (अधिकतम 4,096 बाइट)।"; "custom_header_error_too_many" = "अधिकतम 16 हेडर जोड़े जा सकते हैं।"; +"smart_speed_level_title" = "स्मार्ट स्पीड स्तर"; +"smart_speed_level_off" = "बंद"; +"smart_speed_level_mild" = "हल्का"; +"smart_speed_level_standard" = "मानक"; +"smart_speed_level_strong" = "तेज़"; +"audio_effects_scope_all" = "सभी"; +"audio_effects_scope_this_show" = "यह शो"; +"audio_effects_scope_this_book" = "यह पुस्तक"; +"audio_effects_reset_custom" = "रीसेट"; +"audio_effects_effective_rate_format" = "≈ %@ प्रभावी"; +"radio_voice_boost" = "रेडियो वॉइस बूस्ट"; +"radio_voice_boost_desc" = "स्थानीय रूप से डिकोड की गई रेडियो स्ट्रीम के लिए वॉइस बूस्ट का उपयोग करता है, समाचार और टॉक स्टेशनों के लिए उपयुक्त।"; diff --git a/Primuse/Resources/ja.lproj/Localizable.strings b/Primuse/Resources/ja.lproj/Localizable.strings index ec6056e07..b431decd6 100644 --- a/Primuse/Resources/ja.lproj/Localizable.strings +++ b/Primuse/Resources/ja.lproj/Localizable.strings @@ -8453,3 +8453,15 @@ "custom_header_error_invalid_value" = "値に改行や NUL 文字は使えません。"; "custom_header_error_value_too_long" = "値が長すぎます(最大4,096バイト)。"; "custom_header_error_too_many" = "ヘッダーは最大16個まで追加できます。"; +"smart_speed_level_title" = "スマート速度の強さ"; +"smart_speed_level_off" = "オフ"; +"smart_speed_level_mild" = "弱"; +"smart_speed_level_standard" = "標準"; +"smart_speed_level_strong" = "強"; +"audio_effects_scope_all" = "すべて"; +"audio_effects_scope_this_show" = "この番組"; +"audio_effects_scope_this_book" = "この本"; +"audio_effects_reset_custom" = "リセット"; +"audio_effects_effective_rate_format" = "実効 約%@"; +"radio_voice_boost" = "ラジオ音声強調"; +"radio_voice_boost_desc" = "ローカルデコードされるラジオ放送で音声強調を再利用します。ニュースやトーク番組に最適です。"; diff --git a/Primuse/Resources/ko.lproj/Localizable.strings b/Primuse/Resources/ko.lproj/Localizable.strings index c8d65effc..a03c2dd4e 100644 --- a/Primuse/Resources/ko.lproj/Localizable.strings +++ b/Primuse/Resources/ko.lproj/Localizable.strings @@ -8452,3 +8452,15 @@ "custom_header_error_invalid_value" = "값에는 줄바꿈이나 널 문자를 넣을 수 없습니다."; "custom_header_error_value_too_long" = "값이 너무 깁니다(최대 4,096바이트)."; "custom_header_error_too_many" = "헤더는 최대 16개까지 추가할 수 있습니다."; +"smart_speed_level_title" = "스마트 속도 강도"; +"smart_speed_level_off" = "끔"; +"smart_speed_level_mild" = "약하게"; +"smart_speed_level_standard" = "표준"; +"smart_speed_level_strong" = "강하게"; +"audio_effects_scope_all" = "전체"; +"audio_effects_scope_this_show" = "이 프로그램"; +"audio_effects_scope_this_book" = "이 책"; +"audio_effects_reset_custom" = "기본값 복원"; +"audio_effects_effective_rate_format" = "체감 약 %@"; +"radio_voice_boost" = "라디오 음성 강조"; +"radio_voice_boost_desc" = "로컬 디코딩 라디오 스트림에서 음성 강조를 함께 사용합니다. 뉴스와 토크 방송에 적합합니다."; diff --git a/Primuse/Resources/pl.lproj/Localizable.strings b/Primuse/Resources/pl.lproj/Localizable.strings index 2983799f9..5355c5de7 100644 --- a/Primuse/Resources/pl.lproj/Localizable.strings +++ b/Primuse/Resources/pl.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "Wartość nie może zawierać podziałów wiersza ani znaków null."; "custom_header_error_value_too_long" = "Wartość jest za długa (maksymalnie 4096 bajtów)."; "custom_header_error_too_many" = "Można dodać co najwyżej 16 nagłówków."; +"smart_speed_level_title" = "Poziom inteligentnej prędkości"; +"smart_speed_level_off" = "Wył."; +"smart_speed_level_mild" = "Łagodny"; +"smart_speed_level_standard" = "Standardowy"; +"smart_speed_level_strong" = "Mocny"; +"audio_effects_scope_all" = "Wszystkie"; +"audio_effects_scope_this_show" = "Ten program"; +"audio_effects_scope_this_book" = "Ta książka"; +"audio_effects_reset_custom" = "Resetuj"; +"audio_effects_effective_rate_format" = "≈ %@ efektywnie"; +"radio_voice_boost" = "Wzmocnienie głosu w radiu"; +"radio_voice_boost_desc" = "Wykorzystuje wzmocnienie głosu dla lokalnie dekodowanych stacji radiowych, idealne do wiadomości i audycji mówionych."; diff --git a/Primuse/Resources/pt-BR.lproj/Localizable.strings b/Primuse/Resources/pt-BR.lproj/Localizable.strings index c85d282eb..e59f7d341 100644 --- a/Primuse/Resources/pt-BR.lproj/Localizable.strings +++ b/Primuse/Resources/pt-BR.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "O valor não pode conter quebras de linha nem caracteres nulos."; "custom_header_error_value_too_long" = "O valor é longo demais (máximo de 4.096 bytes)."; "custom_header_error_too_many" = "É possível adicionar no máximo 16 cabeçalhos."; +"smart_speed_level_title" = "Nível da velocidade inteligente"; +"smart_speed_level_off" = "Desativado"; +"smart_speed_level_mild" = "Suave"; +"smart_speed_level_standard" = "Padrão"; +"smart_speed_level_strong" = "Forte"; +"audio_effects_scope_all" = "Todos"; +"audio_effects_scope_this_show" = "Este programa"; +"audio_effects_scope_this_book" = "Este livro"; +"audio_effects_reset_custom" = "Redefinir"; +"audio_effects_effective_rate_format" = "≈ %@ efetivo"; +"radio_voice_boost" = "Realce de voz no rádio"; +"radio_voice_boost_desc" = "Reaproveita o realce de voz em transmissões de rádio decodificadas localmente, ideal para notícias e entrevistas."; diff --git a/Primuse/Resources/ru.lproj/Localizable.strings b/Primuse/Resources/ru.lproj/Localizable.strings index 400c9a287..c7d481fd3 100644 --- a/Primuse/Resources/ru.lproj/Localizable.strings +++ b/Primuse/Resources/ru.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "Значение не может содержать переводы строки и нулевые символы."; "custom_header_error_value_too_long" = "Значение слишком длинное (не более 4096 байт)."; "custom_header_error_too_many" = "Можно добавить не более 16 заголовков."; +"smart_speed_level_title" = "Уровень умной скорости"; +"smart_speed_level_off" = "Выкл."; +"smart_speed_level_mild" = "Мягко"; +"smart_speed_level_standard" = "Стандарт"; +"smart_speed_level_strong" = "Сильно"; +"audio_effects_scope_all" = "Все"; +"audio_effects_scope_this_show" = "Этот подкаст"; +"audio_effects_scope_this_book" = "Эта книга"; +"audio_effects_reset_custom" = "Сбросить"; +"audio_effects_effective_rate_format" = "≈ %@ факт."; +"radio_voice_boost" = "Усиление голоса для радио"; +"radio_voice_boost_desc" = "Применяет усиление голоса к локально декодируемым радиопотокам — удобно для новостей и разговорных станций."; diff --git a/Primuse/Resources/th.lproj/Localizable.strings b/Primuse/Resources/th.lproj/Localizable.strings index 56f4359d3..f266f4748 100644 --- a/Primuse/Resources/th.lproj/Localizable.strings +++ b/Primuse/Resources/th.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "ค่าต้องไม่มีการขึ้นบรรทัดใหม่หรืออักขระ null"; "custom_header_error_value_too_long" = "ค่ายาวเกินไป (สูงสุด 4,096 ไบต์)"; "custom_header_error_too_many" = "เพิ่มส่วนหัวได้สูงสุด 16 รายการ"; +"smart_speed_level_title" = "ระดับความเร็วอัจฉริยะ"; +"smart_speed_level_off" = "ปิด"; +"smart_speed_level_mild" = "เบา"; +"smart_speed_level_standard" = "มาตรฐาน"; +"smart_speed_level_strong" = "เข้มข้น"; +"audio_effects_scope_all" = "ทั้งหมด"; +"audio_effects_scope_this_show" = "รายการนี้"; +"audio_effects_scope_this_book" = "หนังสือเล่มนี้"; +"audio_effects_reset_custom" = "รีเซ็ต"; +"audio_effects_effective_rate_format" = "≈ %@ โดยประมาณ"; +"radio_voice_boost" = "เร่งเสียงพูดวิทยุ"; +"radio_voice_boost_desc" = "ใช้การเร่งเสียงพูดร่วมกับสตรีมวิทยุที่ถอดรหัสในเครื่อง เหมาะสำหรับสถานีข่าวและรายการสนทนา"; diff --git a/Primuse/Resources/tr.lproj/Localizable.strings b/Primuse/Resources/tr.lproj/Localizable.strings index 9323b0d0c..3351d5c8f 100644 --- a/Primuse/Resources/tr.lproj/Localizable.strings +++ b/Primuse/Resources/tr.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "Değer satır sonu veya boş karakter içeremez."; "custom_header_error_value_too_long" = "Değer çok uzun (en fazla 4.096 bayt)."; "custom_header_error_too_many" = "En fazla 16 üstbilgi eklenebilir."; +"smart_speed_level_title" = "Akıllı Hız Düzeyi"; +"smart_speed_level_off" = "Kapalı"; +"smart_speed_level_mild" = "Hafif"; +"smart_speed_level_standard" = "Standart"; +"smart_speed_level_strong" = "Güçlü"; +"audio_effects_scope_all" = "Tümü"; +"audio_effects_scope_this_show" = "Bu Program"; +"audio_effects_scope_this_book" = "Bu Kitap"; +"audio_effects_reset_custom" = "Sıfırla"; +"audio_effects_effective_rate_format" = "≈ %@ etkin"; +"radio_voice_boost" = "Radyo Ses Güçlendirme"; +"radio_voice_boost_desc" = "Yerel olarak çözülen radyo yayınlarında ses güçlendirmeyi kullanır; haber ve sohbet istasyonları için idealdir."; diff --git a/Primuse/Resources/uk.lproj/Localizable.strings b/Primuse/Resources/uk.lproj/Localizable.strings index 79c2853ce..e287e0de8 100644 --- a/Primuse/Resources/uk.lproj/Localizable.strings +++ b/Primuse/Resources/uk.lproj/Localizable.strings @@ -8358,3 +8358,15 @@ "custom_header_error_invalid_value" = "Значення не може містити розривів рядка чи нульових символів."; "custom_header_error_value_too_long" = "Значення задовге (не більше 4096 байтів)."; "custom_header_error_too_many" = "Можна додати щонайбільше 16 заголовків."; +"smart_speed_level_title" = "Рівень розумної швидкості"; +"smart_speed_level_off" = "Вимк."; +"smart_speed_level_mild" = "М’яко"; +"smart_speed_level_standard" = "Стандарт"; +"smart_speed_level_strong" = "Сильно"; +"audio_effects_scope_all" = "Усі"; +"audio_effects_scope_this_show" = "Цей подкаст"; +"audio_effects_scope_this_book" = "Ця книга"; +"audio_effects_reset_custom" = "Скинути"; +"audio_effects_effective_rate_format" = "≈ %@ факт."; +"radio_voice_boost" = "Підсилення голосу для радіо"; +"radio_voice_boost_desc" = "Застосовує підсилення голосу до локально декодованих радіопотоків — ідеально для новин і розмовних станцій."; diff --git a/Primuse/Resources/zh-Hans.lproj/Localizable.strings b/Primuse/Resources/zh-Hans.lproj/Localizable.strings index a7426ab33..9ae96495a 100644 --- a/Primuse/Resources/zh-Hans.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hans.lproj/Localizable.strings @@ -8545,3 +8545,15 @@ "custom_header_error_invalid_value" = "值里不能包含换行或空字符。"; "custom_header_error_value_too_long" = "值太长(最多 4,096 字节)。"; "custom_header_error_too_many" = "最多只能添加 16 个请求头。"; +"smart_speed_level_title" = "智能速度强度"; +"smart_speed_level_off" = "关闭"; +"smart_speed_level_mild" = "轻柔"; +"smart_speed_level_standard" = "标准"; +"smart_speed_level_strong" = "强力"; +"audio_effects_scope_all" = "全部"; +"audio_effects_scope_this_show" = "当前节目"; +"audio_effects_scope_this_book" = "当前书籍"; +"audio_effects_reset_custom" = "恢复默认"; +"audio_effects_effective_rate_format" = "等效约 %@"; +"radio_voice_boost" = "电台人声增强"; +"radio_voice_boost_desc" = "收听走本地解码的广播电台时复用语音增强,适合新闻与谈话台。"; diff --git a/Primuse/Resources/zh-Hant.lproj/Localizable.strings b/Primuse/Resources/zh-Hant.lproj/Localizable.strings index 94b9273d6..51166e7f0 100644 --- a/Primuse/Resources/zh-Hant.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hant.lproj/Localizable.strings @@ -8429,3 +8429,15 @@ "custom_header_error_invalid_value" = "值裡不能包含換行或空字元。"; "custom_header_error_value_too_long" = "值太長(最多 4,096 位元組)。"; "custom_header_error_too_many" = "最多只能新增 16 個請求標頭。"; +"smart_speed_level_title" = "智慧速度強度"; +"smart_speed_level_off" = "關閉"; +"smart_speed_level_mild" = "輕柔"; +"smart_speed_level_standard" = "標準"; +"smart_speed_level_strong" = "強力"; +"audio_effects_scope_all" = "全部"; +"audio_effects_scope_this_show" = "目前節目"; +"audio_effects_scope_this_book" = "目前書籍"; +"audio_effects_reset_custom" = "恢復預設"; +"audio_effects_effective_rate_format" = "等效約 %@"; +"radio_voice_boost" = "電台人聲增強"; +"radio_voice_boost_desc" = "收聽本機解碼的廣播電台時共用語音增強,適合新聞與談話台。"; diff --git a/Primuse/Services/Audio/AudioEngine+Varispeed.swift b/Primuse/Services/Audio/AudioEngine+Varispeed.swift index ae6fdfc1c..d7ee9c994 100644 --- a/Primuse/Services/Audio/AudioEngine+Varispeed.swift +++ b/Primuse/Services/Audio/AudioEngine+Varispeed.swift @@ -34,7 +34,7 @@ extension AudioEngine { ) { let previousRate = playbackRate let previousVarispeed = self.varispeedEnabled - playbackRate = VarispeedPolicy.clampedRate(rate) + playbackRate = SpokenWordPlaybackRatePolicy.clampedEngineRate(rate, isSpokenWord: isSpokenWord) self.userPitchCents = userPitchCents playbackIsSpokenWord = isSpokenWord self.varispeedEnabled = varispeedEnabled && !isSpokenWord @@ -72,7 +72,7 @@ extension AudioEngine { /// and linked speed/pitch stretching (`AVAudioUnitVarispeed`) so rates never multiply. func applyPitchToGraph() { guard outputMode == .effects else { return } - let safeRate = VarispeedPolicy.clampedRate(playbackRate) + let safeRate = SpokenWordPlaybackRatePolicy.clampedEngineRate(playbackRate, isSpokenWord: playbackIsSpokenWord) // Until the graph is rebuilt with the varispeed unit, keep the requested speed through // time stretching so the clock rate published for progress and lyrics stays true. @@ -226,7 +226,7 @@ extension AudioEngine { func applyRateToAirPlaySampleBufferBackend() { guard let backend = sampleBufferBackend else { return } - let rate: Float = outputMode == .effects ? VarispeedPolicy.clampedRate(playbackRate) : 1 + let rate: Float = outputMode == .effects ? SpokenWordPlaybackRatePolicy.clampedEngineRate(playbackRate, isSpokenWord: playbackIsSpokenWord) : 1 backend.setPlaybackRate(rate, isSpokenWord: playbackIsSpokenWord) } @@ -368,7 +368,7 @@ final class AirPlaySampleBufferBackend: @unchecked Sendable { } func setPlaybackRate(_ rate: Float, isSpokenWord: Bool) { - let safeRate = VarispeedPolicy.clampedRate(rate) + let safeRate = SpokenWordPlaybackRatePolicy.clampedEngineRate(rate, isSpokenWord: isSpokenWord) let algorithm: AVAudioTimePitchAlgorithm = isSpokenWord ? .timeDomain : .spectral queue.async { [weak self] in guard let self else { return } @@ -385,7 +385,7 @@ final class AirPlaySampleBufferBackend: @unchecked Sendable { } func play(rate: Float, isSpokenWord: Bool) -> Bool { - let safeRate = VarispeedPolicy.clampedRate(rate) + let safeRate = SpokenWordPlaybackRatePolicy.clampedEngineRate(rate, isSpokenWord: isSpokenWord) let algorithm: AVAudioTimePitchAlgorithm = isSpokenWord ? .timeDomain : .spectral return queue.sync { let (tornDown, isFailed, alreadyStarted) = stateLock.withLock { (isTornDown, failed, hasStarted) } @@ -413,8 +413,8 @@ final class AirPlaySampleBufferBackend: @unchecked Sendable { } } - func resume(rate: Float) -> Bool { - let safeRate = VarispeedPolicy.clampedRate(rate) + func resume(rate: Float, isSpokenWord: Bool = false) -> Bool { + let safeRate = SpokenWordPlaybackRatePolicy.clampedEngineRate(rate, isSpokenWord: isSpokenWord) return queue.sync { let (tornDown, isFailed) = stateLock.withLock { (isTornDown, failed) } guard !tornDown, !isFailed else { return false } diff --git a/Primuse/Services/Audio/AudioEngine.swift b/Primuse/Services/Audio/AudioEngine.swift index 9a8e434f6..a61157178 100644 --- a/Primuse/Services/Audio/AudioEngine.swift +++ b/Primuse/Services/Audio/AudioEngine.swift @@ -2010,7 +2010,7 @@ extension AudioEngine { syncAirPlaySampleBufferOutputDevice() #endif applyVolumeToAirPlaySampleBufferBackend() - let rate: Float = outputMode == .effects ? VarispeedPolicy.clampedRate(playbackRate) : 1 + let rate: Float = outputMode == .effects ? SpokenWordPlaybackRatePolicy.clampedEngineRate(playbackRate, isSpokenWord: playbackIsSpokenWord) : 1 isPlaying = sampleBufferBackend?.play(rate: rate, isSpokenWord: playbackIsSpokenWord) ?? false playbackClockReadsSuspended = !isPlaying return isPlaying @@ -2175,8 +2175,8 @@ extension AudioEngine { private func resumeImmediately() -> Bool { cancelEngineIdleShutdown() if usesAirPlaySampleBufferBackend { - let rate: Float = outputMode == .effects ? VarispeedPolicy.clampedRate(playbackRate) : 1 - isPlaying = sampleBufferBackend?.resume(rate: rate) ?? false + let rate: Float = outputMode == .effects ? SpokenWordPlaybackRatePolicy.clampedEngineRate(playbackRate, isSpokenWord: playbackIsSpokenWord) : 1 + isPlaying = sampleBufferBackend?.resume(rate: rate, isSpokenWord: playbackIsSpokenWord) ?? false playbackClockReadsSuspended = !isPlaying return isPlaying } diff --git a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift index ba6ed3a4f..9b0fa59be 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift @@ -183,18 +183,86 @@ final class SpokenWordSmartSpeedSavings { } extension AudioPlayerService { - // MARK: - Smart speed + // MARK: - Smart speed & per-item audio effects - /// 本机解码流排进节点前的最后一站:有声内容、开关打开时缩短长停顿,否则原样返回。 + func audioEffectsScopeID(for song: Song?) -> String? { + guard let song else { return nil } + if isRadioPlaybackSong(song) { return song.id } + guard listeningSpace(of: song).playbackFamily == .spokenWord else { return nil } + return spokenWordBookID(for: song) + } + + var globalSmartSpeedLevel: SmartSpeedLevel { + SpokenWordAudioEffectsPolicy.globalSmartSpeedLevel( + enabled: playbackSettings.spokenWordSmartSpeedEnabled, + preferredLevel: playbackSettings.spokenWordSmartSpeedLevel + ) + } + + func setGlobalSmartSpeedLevel(_ level: SmartSpeedLevel) { + if level == .off { + playbackSettings.spokenWordSmartSpeedEnabled = false + } else { + playbackSettings.spokenWordSmartSpeedLevel = level + playbackSettings.spokenWordSmartSpeedEnabled = true + } + } + + func effectiveSmartSpeedLevel(for song: Song?) -> SmartSpeedLevel { + guard let song else { return .off } + let scopeID = audioEffectsScopeID(for: song) + let override = scopeID.flatMap { SpokenWordAudioEffectsPreferences.shared.override(forScopeID: $0) } + return SpokenWordAudioEffectsPolicy.effectiveSmartSpeedLevel( + space: listeningSpace(of: song), + override: override, + globalLevel: globalSmartSpeedLevel + ) + } + + var currentEffectiveSmartSpeedLevel: SmartSpeedLevel { + _ = SpokenWordAudioEffectsPreferences.shared.revision + return effectiveSmartSpeedLevel(for: currentSong) + } + + func effectiveVoiceBoostActive(for song: Song?) -> Bool { + guard let song else { return false } + let scopeID = audioEffectsScopeID(for: song) + let override = scopeID.flatMap { SpokenWordAudioEffectsPreferences.shared.override(forScopeID: $0) } + return SpokenWordAudioEffectsPolicy.effectiveVoiceBoost( + space: listeningSpace(of: song), + override: override, + globalSpokenWordEnabled: playbackSettings.spokenWordVoiceBoostEnabled, + globalRadioEnabled: playbackSettings.radioVoiceBoostEnabled + ) + } + + var currentEffectiveVoiceBoostEnabled: Bool { + _ = SpokenWordAudioEffectsPreferences.shared.revision + return effectiveVoiceBoostActive(for: currentSong) + } + + /// 开启智能速度且当前条目已实际缩短停顿时,估算当前等效倍速(例如 1.5× → 1.72×)。 + var currentSmartSpeedEffectiveRate: Float? { + guard currentItemIsSpokenWord, + !isSystemMediaPlaybackActive, + currentEffectiveSmartSpeedLevel.isEnabled else { return nil } + return SmartSpeedEffectiveRateEstimator.effectiveRate( + baseRate: currentSpokenWordRate, + elapsedSourceSeconds: currentTime, + skippedSourceSeconds: audioEngine.primarySmartSpeedSkippedDuration + ) + } + + /// 本机解码流排进节点前的最后一站:有声内容、智能速度打开时按对应强度缩短长停顿,否则原样返回。 func smartSpeedProcessed( _ stream: AudioBufferStream, for song: Song, passthroughFrames: Int64 = 0 ) -> AudioBufferStream { - guard playbackSettings.spokenWordSmartSpeedEnabled, - SpokenWordStore.shared.isSpokenWord(song) else { return stream } + guard let policy = effectiveSmartSpeedLevel(for: song).policy else { return stream } return SmartSpeedStream.shorteningPauses( stream, + policy: policy, passthroughFrames: max(0, passthroughFrames), registry: audioEngine.nodeRegistry ) @@ -228,30 +296,30 @@ extension AudioPlayerService { // MARK: - Voice boost - /// 有声内容在放、语音增强打开时,均衡和压缩器换成说话用的设定;其余时候照用户自己的设置。 + /// 有声内容或支持人声增强的电台在放且语音增强启用时,均衡和压缩器换成说话用的设定;其余时候照用户自己的设置。 func applySpokenWordVoiceBoost() { - let active = VoiceBoostActivationPolicy.isActive( - space: currentListeningSpace, - spokenWordEnabled: playbackSettings.spokenWordVoiceBoostEnabled - ) + let active = effectiveVoiceBoostActive(for: currentSong) audioEffectsService.voiceBoostActive = active equalizerService.voiceBoostActive = active } // MARK: - Settings - /// 两个开关改了马上生效:语音增强直接切;智能速度要换一条解码流,有声内容正在本机放时 - /// 在原位重建一次(和换输出模式一样)。 + /// 两个开关及按节目/按书覆盖改了马上生效:语音增强直接切;智能速度强度变化时,有声内容正在本机放 + /// 就在原位重建一次(和换输出模式一样)。 func observeSpokenWordListeningAids() { - let smartSpeedEnabled = playbackSettings.spokenWordSmartSpeedEnabled + let activeSmartSpeedLevel = currentEffectiveSmartSpeedLevel withObservationTracking { _ = playbackSettings.spokenWordSmartSpeedEnabled + _ = playbackSettings.spokenWordSmartSpeedLevel _ = playbackSettings.spokenWordVoiceBoostEnabled + _ = playbackSettings.radioVoiceBoostEnabled + _ = SpokenWordAudioEffectsPreferences.shared.revision } onChange: { [weak self] in Task { @MainActor [weak self] in guard let self else { return } self.applySpokenWordVoiceBoost() - if self.playbackSettings.spokenWordSmartSpeedEnabled != smartSpeedEnabled, + if self.currentEffectiveSmartSpeedLevel != activeSmartSpeedLevel, self.currentItemIsSpokenWord, !self.isCastingMode, self.canRebuildOutputPipelineForSettingsChange { diff --git a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift index 99406142c..6f96c07ad 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift @@ -121,10 +121,7 @@ extension AudioPlayerService { if airPlaySampleBufferFallbackSongID == song.id { return false } - let voiceBoostActive = VoiceBoostActivationPolicy.isActive( - space: listeningSpace(of: song), - spokenWordEnabled: playbackSettings.spokenWordVoiceBoostEnabled - ) + let voiceBoostActive = effectiveVoiceBoostActive(for: song) let effectsEnabled = (audioEffectsService.effectChainEnabled && (audioEffectsService.compressorEnabled || audioEffectsService.reverbEnabled)) || voiceBoostActive @@ -181,6 +178,8 @@ extension AudioPlayerService { _ = audioEffectsService.compressorEnabled _ = audioEffectsService.reverbEnabled _ = playbackSettings.spokenWordVoiceBoostEnabled + _ = playbackSettings.radioVoiceBoostEnabled + _ = SpokenWordAudioEffectsPreferences.shared.revision _ = playbackSettings.spatialAudioEnabled _ = playbackSettings.crossfadeEnabled } onChange: { [weak self] in diff --git a/Primuse/Services/Audio/PlaybackSettingsStore.swift b/Primuse/Services/Audio/PlaybackSettingsStore.swift index c8e73eacd..d0d89d8e8 100644 --- a/Primuse/Services/Audio/PlaybackSettingsStore.swift +++ b/Primuse/Services/Audio/PlaybackSettingsStore.swift @@ -143,8 +143,10 @@ struct PlaybackSettings: Codable, Sendable, Equatable { var spokenWordSmartRewindLimitSeconds: Int = SpokenWordSmartRewindPolicy.defaultLimit /// 智能速度(REQ-174): 有声内容里过长的停顿缩短, 语速和音调不变。默认关。 var spokenWordSmartSpeedEnabled: Bool = false + var spokenWordSmartSpeedLevel: SmartSpeedLevel = .standard /// 语音增强(REQ-174): 有声内容时均衡与压缩换成说话用的设定, 小声的节目拉起来、各期响度差不多。默认关。 var spokenWordVoiceBoostEnabled: Bool = false + var radioVoiceBoostEnabled: Bool = false /// 串烧每首截取的秒数(`medleyAutomaticLength` 关着时才用)。 var medleySegmentSeconds: Int = MedleySegmentPolicy.defaultSegmentLength /// 串烧每首按它的高潮段本身的长短播,而不是固定秒数。 @@ -253,7 +255,10 @@ struct PlaybackSettings: Codable, Sendable, Equatable { spokenWordSmartRewindLimitSeconds = try c.decodeIfPresent(Int.self, forKey: .spokenWordSmartRewindLimitSeconds) ?? SpokenWordSmartRewindPolicy.defaultLimit spokenWordSmartSpeedEnabled = try c.decodeIfPresent(Bool.self, forKey: .spokenWordSmartSpeedEnabled) ?? false + let decodedLevel = (try? c.decodeIfPresent(SmartSpeedLevel.self, forKey: .spokenWordSmartSpeedLevel)) ?? .standard + spokenWordSmartSpeedLevel = decodedLevel == .off ? .standard : decodedLevel spokenWordVoiceBoostEnabled = try c.decodeIfPresent(Bool.self, forKey: .spokenWordVoiceBoostEnabled) ?? false + radioVoiceBoostEnabled = try c.decodeIfPresent(Bool.self, forKey: .radioVoiceBoostEnabled) ?? false medleySegmentSeconds = try c.decodeIfPresent(Int.self, forKey: .medleySegmentSeconds) ?? MedleySegmentPolicy.defaultSegmentLength medleyAutomaticLength = try c.decodeIfPresent(Bool.self, forKey: .medleyAutomaticLength) ?? true @@ -322,7 +327,9 @@ struct PlaybackSettings: Codable, Sendable, Equatable { spokenWordSmartRewindEnabled: Bool = SpokenWordSmartRewindPolicy.enabledByDefault, spokenWordSmartRewindLimitSeconds: Int = SpokenWordSmartRewindPolicy.defaultLimit, spokenWordSmartSpeedEnabled: Bool = false, + spokenWordSmartSpeedLevel: SmartSpeedLevel = .standard, spokenWordVoiceBoostEnabled: Bool = false, + radioVoiceBoostEnabled: Bool = false, medleySegmentSeconds: Int = MedleySegmentPolicy.defaultSegmentLength, medleyAutomaticLength: Bool = true, medleyPrefersPlaybackRange: Bool = false, @@ -387,7 +394,9 @@ struct PlaybackSettings: Codable, Sendable, Equatable { self.spokenWordSmartRewindEnabled = spokenWordSmartRewindEnabled self.spokenWordSmartRewindLimitSeconds = spokenWordSmartRewindLimitSeconds self.spokenWordSmartSpeedEnabled = spokenWordSmartSpeedEnabled + self.spokenWordSmartSpeedLevel = spokenWordSmartSpeedLevel == .off ? .standard : spokenWordSmartSpeedLevel self.spokenWordVoiceBoostEnabled = spokenWordVoiceBoostEnabled + self.radioVoiceBoostEnabled = radioVoiceBoostEnabled self.medleySegmentSeconds = medleySegmentSeconds self.medleyAutomaticLength = medleyAutomaticLength self.medleyPrefersPlaybackRange = medleyPrefersPlaybackRange @@ -627,7 +636,9 @@ final class PlaybackSettingsStore { var spokenWordLockScreenUsesChapters: Bool { didSet { persist() } } var spokenWordSmartRewindEnabled: Bool { didSet { persist() } } var spokenWordSmartSpeedEnabled: Bool { didSet { persist() } } + var spokenWordSmartSpeedLevel: SmartSpeedLevel { didSet { persist() } } var spokenWordVoiceBoostEnabled: Bool { didSet { persist() } } + var radioVoiceBoostEnabled: Bool { didSet { persist() } } var spokenWordSmartRewindLimitSeconds: Int { didSet { let clamped = SpokenWordSmartRewindPolicy.clampedLimit(spokenWordSmartRewindLimitSeconds) @@ -728,7 +739,9 @@ final class PlaybackSettingsStore { self.spokenWordSmartRewindEnabled = s.spokenWordSmartRewindEnabled self.spokenWordSmartRewindLimitSeconds = SpokenWordSmartRewindPolicy.clampedLimit(s.spokenWordSmartRewindLimitSeconds) self.spokenWordSmartSpeedEnabled = s.spokenWordSmartSpeedEnabled + self.spokenWordSmartSpeedLevel = s.spokenWordSmartSpeedLevel == .off ? .standard : s.spokenWordSmartSpeedLevel self.spokenWordVoiceBoostEnabled = s.spokenWordVoiceBoostEnabled + self.radioVoiceBoostEnabled = s.radioVoiceBoostEnabled self.medleySegmentSeconds = MedleySegmentPolicy.clampedSegmentLength(s.medleySegmentSeconds) self.medleyAutomaticLength = s.medleyAutomaticLength self.medleyPrefersPlaybackRange = s.medleyPrefersPlaybackRange @@ -860,7 +873,9 @@ extension PlaybackSettingsStore { spokenWordSmartRewindEnabled = s.spokenWordSmartRewindEnabled spokenWordSmartRewindLimitSeconds = SpokenWordSmartRewindPolicy.clampedLimit(s.spokenWordSmartRewindLimitSeconds) spokenWordSmartSpeedEnabled = s.spokenWordSmartSpeedEnabled + spokenWordSmartSpeedLevel = s.spokenWordSmartSpeedLevel == .off ? .standard : s.spokenWordSmartSpeedLevel spokenWordVoiceBoostEnabled = s.spokenWordVoiceBoostEnabled + radioVoiceBoostEnabled = s.radioVoiceBoostEnabled medleySegmentSeconds = MedleySegmentPolicy.clampedSegmentLength(s.medleySegmentSeconds) medleyAutomaticLength = s.medleyAutomaticLength medleyPrefersPlaybackRange = s.medleyPrefersPlaybackRange @@ -936,7 +951,9 @@ extension PlaybackSettingsStore { spokenWordSmartRewindEnabled: spokenWordSmartRewindEnabled, spokenWordSmartRewindLimitSeconds: spokenWordSmartRewindLimitSeconds, spokenWordSmartSpeedEnabled: spokenWordSmartSpeedEnabled, + spokenWordSmartSpeedLevel: spokenWordSmartSpeedLevel, spokenWordVoiceBoostEnabled: spokenWordVoiceBoostEnabled, + radioVoiceBoostEnabled: radioVoiceBoostEnabled, medleySegmentSeconds: medleySegmentSeconds, medleyAutomaticLength: medleyAutomaticLength, medleyPrefersPlaybackRange: medleyPrefersPlaybackRange, diff --git a/Primuse/Services/Library/SpokenWordStore.swift b/Primuse/Services/Library/SpokenWordStore.swift index 8e0eb7e23..cc9b59330 100644 --- a/Primuse/Services/Library/SpokenWordStore.swift +++ b/Primuse/Services/Library/SpokenWordStore.swift @@ -1151,13 +1151,11 @@ extension SpokenWordStore { // MARK: - Books regrouped under new ids - /// The library gave books new ids (old id → new id): their speed and - /// archive mark go with them. The old id keeps its own, for a device that - /// has not read the tags yet and still groups the book the old way; every - /// device carrying the same renames reaches the same state, so nothing - /// bounces between them (`SpokenWordSyncPolicy.carryingBookState`). + /// The library gave books new ids (old id → new id): their speed, effects and + /// archive mark go with them; old ids keep theirs for devices not yet regrouped. func carryBookState(renames: [String: String]) { SpokenWordIntroOutroPreferences.shared.carryBookState(renames: renames) + SpokenWordAudioEffectsPreferences.shared.carryBookState(renames: renames) let affected = renames.keys.contains { bookID in bookRates[bookID] != nil || archivedAt[bookID] != nil || ledger.rateChangedAt[bookID] != nil || ledger.unarchivedAt[bookID] != nil diff --git a/Primuse/Views/Library/SpokenWordLibraryView.swift b/Primuse/Views/Library/SpokenWordLibraryView.swift index f5c2f3e09..dc5cd46b7 100644 --- a/Primuse/Views/Library/SpokenWordLibraryView.swift +++ b/Primuse/Views/Library/SpokenWordLibraryView.swift @@ -2986,39 +2986,13 @@ struct SpokenWordBookSpeedMenu: View { var keyHeight: CGFloat? = nil @Environment(AudioPlayerService.self) private var player + @State private var showsAudioEffects = false var body: some View { _ = SpokenWordStore.shared.revision - let hasOwnRate = SpokenWordStore.shared.playbackRate(forBookID: bookID) != nil let rate = player.spokenWordRate(forBookID: bookID) - let globalRate = SpokenWordPlaybackRatePolicy.clamped(player.playbackSettings.spokenWordPlaybackRate) - return Menu { - Button { - player.setSpokenWordRate(nil, forBookID: bookID) - } label: { - let title = String( - format: String(localized: "spoken_word_book_speed_default_format"), - SpokenWordPlaybackRatePolicy.label(for: globalRate) - ) - if hasOwnRate { - Text(verbatim: title) - } else { - Label(title, systemImage: "checkmark") - } - } - Divider() - ForEach(SpokenWordPlaybackRatePolicy.presets, id: \.self) { preset in - Button { - player.setSpokenWordRate(preset, forBookID: bookID) - } label: { - let title = SpokenWordPlaybackRatePolicy.label(for: preset) - if hasOwnRate, abs(preset - rate) < 0.001 { - Label(title, systemImage: "checkmark") - } else { - Text(verbatim: title) - } - } - } + return Button { + showsAudioEffects = true } label: { #if os(macOS) Label(SpokenWordPlaybackRatePolicy.label(for: rate), systemImage: "gauge.with.dots.needle.67percent") @@ -3050,13 +3024,19 @@ struct SpokenWordBookSpeedMenu: View { #endif } #if os(macOS) - // 与旁边「继续」同高的一颗按钮, 不是系统的弹出菜单外观。 - .menuStyle(.button) .buttonStyle(.plain) - .menuIndicator(.hidden) .fixedSize() + .popover(isPresented: $showsAudioEffects, arrowEdge: .bottom) { + SpokenWordAudioEffectsSheet(targetBookID: bookID) + .frame(width: 340) + } #else .modifier(SpokenWordSpeedKeyStyle(usesKeyFace: keyHeight != nil)) + .sheet(isPresented: $showsAudioEffects) { + SpokenWordAudioEffectsSheet(targetBookID: bookID) + .presentationDetents([.medium, .large]) + .presentationDragIndicator(.visible) + } #endif .accessibilityLabel(Text("spoken_word_book_speed")) .accessibilityValue(Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: rate))) diff --git a/Primuse/Views/Mac/MacSettingsView.swift b/Primuse/Views/Mac/MacSettingsView.swift index f895bc0a2..e074db93f 100644 --- a/Primuse/Views/Mac/MacSettingsView.swift +++ b/Primuse/Views/Mac/MacSettingsView.swift @@ -2982,29 +2982,25 @@ private struct MacSpokenWordListeningAidRows: View { var body: some View { @Bindable var s = store - MacSTRow( - String(localized: "spoken_word_smart_speed"), - hint: String(localized: "spoken_word_smart_speed_desc"), - hintLineLimit: 3 - ) { + MacSTRow(String(localized: "spoken_word_smart_speed"), hint: String(localized: "spoken_word_smart_speed_desc"), hintLineLimit: 3) { MacSTToggle(isOn: $s.spokenWordSmartSpeedEnabled) } .settingsAnchor("playback.spokenWordSmartSpeed") if s.spokenWordSmartSpeedEnabled { + MacSTRow(String(localized: "smart_speed_level_title")) { + MacSTPicker(selection: $s.spokenWordSmartSpeedLevel, options: SmartSpeedLevel.enabledLevels.map { ($0, $0.localizedTitle) }, width: 140) + } MacSTRow(String(localized: "spoken_word_smart_speed_saved")) { - Text(verbatim: SpokenWordSmartSpeedSavings.shared.formattedTotal) - .foregroundStyle(.secondary) - .monospacedDigit() + Text(verbatim: SpokenWordSmartSpeedSavings.shared.formattedTotal).foregroundStyle(.secondary).monospacedDigit() } } - MacSTRow( - String(localized: "spoken_word_voice_boost"), - hint: String(localized: "spoken_word_voice_boost_desc"), - hintLineLimit: 3 - ) { + MacSTRow(String(localized: "spoken_word_voice_boost"), hint: String(localized: "spoken_word_voice_boost_desc"), hintLineLimit: 3) { MacSTToggle(isOn: $s.spokenWordVoiceBoostEnabled) } .settingsAnchor("playback.spokenWordVoiceBoost") + MacSTRow(String(localized: "radio_voice_boost"), hint: String(localized: "radio_voice_boost_desc"), hintLineLimit: 2) { + MacSTToggle(isOn: $s.radioVoiceBoostEnabled) + } } } diff --git a/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift b/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift new file mode 100644 index 000000000..f54e87897 --- /dev/null +++ b/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift @@ -0,0 +1,372 @@ +import PrimuseKit +import SwiftUI + +extension SmartSpeedLevel { + var localizedTitle: String { + switch self { + case .off: return String(localized: "smart_speed_level_off") + case .mild: return String(localized: "smart_speed_level_mild") + case .standard: return String(localized: "smart_speed_level_standard") + case .strong: return String(localized: "smart_speed_level_strong") + } + } +} + +/// 统一的有声内容音频效果面板(参考 Overcast 的智能倍速调节模式)。 +/// 播客与有声书、iOS 与 macOS、播放页与书籍/节目详情页共用同一套视图: +/// - 作用域切换:当前节目/书籍 vs 全局默认,支持一键恢复默认; +/// - 0.5×–3.0× 非线性智能刻度滑块(0.8×–1.5× 为 0.05× 精细步进)、微调 −/+ 键、常用倍速预设与实时剩余时长估算; +/// - 多档智能速度(关闭 / 轻柔 / 标准 / 强力)+ 实时等效倍速与累计已节省时间; +/// - 语音增强开关;有声书同时保留片头/片尾跳过入口。 +struct SpokenWordAudioEffectsSheet: View { + enum Scope: String, CaseIterable, Identifiable { + case item + case global + + var id: String { rawValue } + } + + /// 指定某本书或节目时直接编辑该条目;为 nil 时跟随当前正在播放的条目。 + var targetBookID: String? = nil + var isPodcastContext: Bool? = nil + var introOutroSong: Song? = nil + + @Environment(AudioPlayerService.self) private var player + @Environment(\.dismiss) private var dismiss + @State private var scope: Scope = .item + + private static let quickPresets: [Float] = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0] + + private var activeScopeID: String? { + targetBookID ?? player.currentBookID + } + + private var effectiveScope: Scope { + activeScopeID == nil ? .global : scope + } + + private var isPodcast: Bool { + if let isPodcastContext { return isPodcastContext } + return player.currentListeningSpace == .podcast + } + + private var isEditingCurrentPlayingItem: Bool { + guard let scopeID = activeScopeID, let currentID = player.currentBookID else { return false } + return scopeID == currentID + } + + private var supportsLocalDSP: Bool { + if targetBookID != nil, !isEditingCurrentPlayingItem { return true } + return !player.isSystemMediaPlaybackActive + } + + private var displayedRate: Float { + _ = SpokenWordStore.shared.revision + if effectiveScope == .item, let scopeID = activeScopeID { + return player.spokenWordRate(forBookID: scopeID) + } + return SpokenWordPlaybackRatePolicy.clamped(player.playbackSettings.spokenWordPlaybackRate) + } + + private var displayedSmartSpeedLevel: SmartSpeedLevel { + _ = SpokenWordAudioEffectsPreferences.shared.revision + let global = player.globalSmartSpeedLevel + if effectiveScope == .item, let scopeID = activeScopeID { + return SpokenWordAudioEffectsPreferences.shared.override(forScopeID: scopeID)?.smartSpeedLevel ?? global + } + return global + } + + private var displayedVoiceBoost: Bool { + _ = SpokenWordAudioEffectsPreferences.shared.revision + let global = player.playbackSettings.spokenWordVoiceBoostEnabled + if effectiveScope == .item, let scopeID = activeScopeID { + return SpokenWordAudioEffectsPreferences.shared.override(forScopeID: scopeID)?.voiceBoostEnabled ?? global + } + return global + } + + private var hasCustomOverrideForItem: Bool { + _ = SpokenWordStore.shared.revision + _ = SpokenWordAudioEffectsPreferences.shared.revision + guard let scopeID = activeScopeID else { return false } + return SpokenWordStore.shared.playbackRate(forBookID: scopeID) != nil + || SpokenWordAudioEffectsPreferences.shared.hasOverride(forScopeID: scopeID) + } + + private var liveAdjustedRemainingText: String? { + guard isEditingCurrentPlayingItem, + let contentRemaining = player.spokenWordPartRemaining else { return nil } + let isWholeEpisode = player.currentListeningSpace == .podcast && player.spokenWordChapters.isEmpty + switch SpokenWordNowPlayingPolicy.remainingTimeDisplay(forContent: contentRemaining, rate: displayedRate) { + case .underAMinute: + let key: String.LocalizationValue = isWholeEpisode + ? "podcast_remaining_under_minute" : "spoken_word_part_remaining_under_minute" + return String(localized: key) + case .roundedMinutes(let rounded): + let key: String.LocalizationValue = isWholeEpisode + ? "podcast_remaining_format" : "spoken_word_part_remaining_format" + return String(format: String(localized: key), SpokenWordPlayerText.approximateDuration(rounded)) + } + } + + private var liveEffectiveRate: Float? { + guard isEditingCurrentPlayingItem, effectiveScope == .item || !hasCustomOverrideForItem else { return nil } + return player.currentSmartSpeedEffectiveRate + } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + headerRow + if activeScopeID != nil { scopeRow } + speedSection + if supportsLocalDSP { + smartSpeedSection + voiceBoostSection + } + if let song = introOutroSong ?? (isEditingCurrentPlayingItem && player.currentItemIsAudiobook ? player.currentSong : nil), + let scopeID = activeScopeID { + introOutroSection(bookID: scopeID, song: song) + } + } + .padding(20) + } + #if os(iOS) + .sensoryFeedback(.selection, trigger: displayedRate) + #endif + } + + private var headerRow: some View { + HStack { + Text("spoken_word_speed_short") + .font(.headline) + Spacer() + if effectiveScope == .item, hasCustomOverrideForItem, let scopeID = activeScopeID { + Button("audio_effects_reset_custom") { + resetCustomOverrides(forScopeID: scopeID) + } + .font(.subheadline) + .buttonStyle(.borderless) + } + #if os(iOS) + Button("done") { dismiss() } + .font(.subheadline.weight(.semibold)) + #endif + } + } + + private var scopeRow: some View { + Picker(selection: $scope) { + Text(isPodcast ? "audio_effects_scope_this_show" : "audio_effects_scope_this_book") + .tag(Scope.item) + Text("audio_effects_scope_all") + .tag(Scope.global) + } label: { + EmptyView() + } + .pickerStyle(.segmented) + .labelsHidden() + } + + private var speedSection: some View { + let rate = displayedRate + let slower = SpokenWordPlaybackRatePolicy.adjacentSliderStop(to: rate, faster: false) + let faster = SpokenWordPlaybackRatePolicy.adjacentSliderStop(to: rate, faster: true) + let maxIndex = Double(max(0, SpokenWordPlaybackRatePolicy.sliderStops.count - 1)) + let sliderBinding = Binding( + get: { Double(SpokenWordPlaybackRatePolicy.nearestSliderIndex(for: rate)) }, + set: { applyRate(SpokenWordPlaybackRatePolicy.rate(forSliderIndex: Int($0.rounded()))) } + ) + + return VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: rate)) + .font(.system(.title, design: .rounded).weight(.bold).monospacedDigit()) + .contentTransition(.numericText(value: Double(rate))) + .animation(.snappy(duration: 0.18), value: rate) + + if let effective = liveEffectiveRate { + HStack(spacing: 3) { + Image(systemName: "bolt.fill") + .font(.caption2) + Text(verbatim: String( + format: String(localized: "audio_effects_effective_rate_format"), + SpokenWordPlaybackRatePolicy.label(for: effective) + )) + .font(.caption.weight(.semibold).monospacedDigit()) + } + .foregroundStyle(Color.accentColor) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Color.accentColor.opacity(0.14), in: Capsule()) + } + + Spacer(minLength: 4) + + if let remaining = liveAdjustedRemainingText { + Text(verbatim: remaining) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + + HStack(spacing: 10) { + Button { + if let slower { applyRate(slower) } + } label: { + Image(systemName: "minus.circle.fill") + .font(.title3) + .foregroundStyle(slower == nil ? Color.secondary.opacity(0.35) : Color.primary) + } + .buttonStyle(.plain) + .disabled(slower == nil) + .accessibilityLabel(Text("transcript_reader_speed_slower")) + + Slider(value: sliderBinding, in: 0...maxIndex, step: 1) + .accessibilityLabel(Text("spoken_word_speed_short")) + .accessibilityValue(Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: rate))) + + Button { + if let faster { applyRate(faster) } + } label: { + Image(systemName: "plus.circle.fill") + .font(.title3) + .foregroundStyle(faster == nil ? Color.secondary.opacity(0.35) : Color.primary) + } + .buttonStyle(.plain) + .disabled(faster == nil) + .accessibilityLabel(Text("transcript_reader_speed_faster")) + } + + HStack(spacing: 6) { + ForEach(Self.quickPresets, id: \.self) { preset in + let isSelected = abs(rate - preset) < 0.005 + Button { + applyRate(preset) + } label: { + Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: preset)) + .font(.caption.weight(.semibold).monospacedDigit()) + .frame(maxWidth: .infinity) + .padding(.vertical, 6) + .foregroundStyle(isSelected ? Color.white : Color.primary) + .background( + isSelected ? Color.accentColor : Color.primary.opacity(0.08), + in: RoundedRectangle(cornerRadius: 8, style: .continuous) + ) + } + .buttonStyle(.plain) + } + } + } + .padding(14) + .background(Color.primary.opacity(0.05), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } + + private var smartSpeedSection: some View { + let levelBinding = Binding( + get: { displayedSmartSpeedLevel }, + set: { applySmartSpeedLevel($0) } + ) + let savedSeconds = SpokenWordSmartSpeedSavings.shared.totalSeconds + + return VStack(alignment: .leading, spacing: 10) { + HStack { + Label("spoken_word_smart_speed", systemImage: "hare") + .font(.subheadline.weight(.semibold)) + Spacer() + if savedSeconds >= 1 { + Text(verbatim: "\(String(localized: "spoken_word_smart_speed_saved")) \(SpokenWordSmartSpeedSavings.shared.formattedTotal)") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + + Picker(selection: levelBinding) { + ForEach(SmartSpeedLevel.allCases) { level in + Text(level.localizedTitle).tag(level) + } + } label: { + EmptyView() + } + .pickerStyle(.segmented) + .labelsHidden() + + Text("spoken_word_smart_speed_desc") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(14) + .background(Color.primary.opacity(0.05), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } + + private var voiceBoostSection: some View { + let boostBinding = Binding( + get: { displayedVoiceBoost }, + set: { applyVoiceBoost($0) } + ) + return VStack(alignment: .leading, spacing: 6) { + Toggle(isOn: boostBinding) { + Label("spoken_word_voice_boost", systemImage: "waveform") + .font(.subheadline.weight(.semibold)) + } + Text("spoken_word_voice_boost_desc") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(14) + .background(Color.primary.opacity(0.05), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } + + private func introOutroSection(bookID: String, song: Song) -> some View { + HStack { + SpokenWordIntroOutroMenu(bookID: bookID, song: song) + Spacer() + } + .padding(14) + .background(Color.primary.opacity(0.05), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } + + // MARK: - Actions + + private func applyRate(_ rate: Float) { + let clamped = SpokenWordPlaybackRatePolicy.clamped(rate) + if effectiveScope == .item, let scopeID = activeScopeID { + player.setSpokenWordRate(clamped, forBookID: scopeID) + } else { + player.playbackSettings.spokenWordPlaybackRate = clamped + } + } + + private func applySmartSpeedLevel(_ level: SmartSpeedLevel) { + if effectiveScope == .item, let scopeID = activeScopeID { + let stored = SpokenWordAudioEffectsPolicy.storedSmartSpeedOverride( + for: level, + global: player.globalSmartSpeedLevel + ) + SpokenWordAudioEffectsPreferences.shared.setSmartSpeedLevel(stored, forScopeID: scopeID) + } else { + player.setGlobalSmartSpeedLevel(level) + } + } + + private func applyVoiceBoost(_ enabled: Bool) { + if effectiveScope == .item, let scopeID = activeScopeID { + let stored = SpokenWordAudioEffectsPolicy.storedVoiceBoostOverride( + for: enabled, + global: player.playbackSettings.spokenWordVoiceBoostEnabled + ) + SpokenWordAudioEffectsPreferences.shared.setVoiceBoostEnabled(stored, forScopeID: scopeID) + } else { + player.playbackSettings.spokenWordVoiceBoostEnabled = enabled + } + } + + private func resetCustomOverrides(forScopeID scopeID: String) { + player.setSpokenWordRate(nil, forBookID: scopeID) + SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: scopeID) + } +} diff --git a/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift b/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift index 8cff3b680..1caf07a37 100644 --- a/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift +++ b/Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift @@ -464,6 +464,7 @@ struct SpokenWordActionTiles: View { @Environment(AudioPlayerService.self) private var player @State private var bookmarkFeedbackToken = 0 + @State private var showsAudioEffects = false private var isPodcast: Bool { player.currentListeningSpace == .podcast } @@ -574,35 +575,37 @@ struct SpokenWordActionTiles: View { } private var rateTile: some View { - Menu { - Picker(selection: Binding( - get: { player.currentSpokenWordRate }, - set: { player.setSpokenWordRateForCurrentBook($0) } - )) { - ForEach(SpokenWordPlaybackRatePolicy.presets, id: \.self) { rate in - Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: rate)).tag(rate) - } - } label: { - Text(SpokenWordPlayerText.rateTitleKey(player)) - } - SpokenWordListeningAidMenuToggles() - if player.currentItemIsAudiobook, - let bookID = player.currentBookID, let song = player.currentSong { - Divider() - SpokenWordIntroOutroMenu(bookID: bookID, song: song) - } + let smartSpeedActive = !player.isSystemMediaPlaybackActive && player.currentEffectiveSmartSpeedLevel.isEnabled + return Button { + showsAudioEffects = true } label: { tile { - Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: player.currentSpokenWordRate)) - .font(rateFont) - // 方块里语速用强调色;不垫底的两套设计里它和旁边的图标同色。 - .foregroundStyle(layout == .tiles ? palette.accent : palette.primary) + HStack(spacing: 3) { + Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: player.currentSpokenWordRate)) + .font(rateFont) + if smartSpeedActive { + Image(systemName: "hare.fill") + .font(.caption2) + } + } + .foregroundStyle((layout == .tiles || smartSpeedActive) ? palette.accent : palette.primary) } caption: { Text("spoken_word_speed_short") } } - .menuStyle(.button) .buttonStyle(.plain) + #if os(iOS) + .sheet(isPresented: $showsAudioEffects) { + SpokenWordAudioEffectsSheet() + .presentationDetents([.medium, .large]) + .presentationDragIndicator(.visible) + } + #else + .popover(isPresented: $showsAudioEffects, arrowEdge: .top) { + SpokenWordAudioEffectsSheet() + .frame(width: 340) + } + #endif .accessibilityLabel(Text(SpokenWordPlayerText.rateTitleKey(player))) .accessibilityValue(Text(verbatim: SpokenWordPlaybackRatePolicy.label(for: player.currentSpokenWordRate))) } @@ -679,25 +682,6 @@ struct SpokenWordActionTiles: View { } } -/// 速度菜单里的智能速度、语音增强(REQ-174),和设置里是同一对开关。视频播客、走系统播放器的条目 -/// 用不上这两项,那时不列。 -struct SpokenWordListeningAidMenuToggles: View { - @Environment(AudioPlayerService.self) private var player - - var body: some View { - @Bindable var settings = player.playbackSettings - if !player.isSystemMediaPlaybackActive { - Divider() - Toggle(isOn: $settings.spokenWordSmartSpeedEnabled) { - Label("spoken_word_smart_speed", systemImage: "hare") - } - Toggle(isOn: $settings.spokenWordVoiceBoostEnabled) { - Label("spoken_word_voice_boost", systemImage: "waveform") - } - } - } -} - /// 功能块一块的样子:图标加一行说明(只放图标时不写)。`SpokenWordActionTiles` 与播放页自己画的 /// 几块(挪进这一排的文字稿、喜欢、「更多」)共用,同一排里大小、字号一样。 struct SpokenWordTileFace: View { @@ -2219,8 +2203,8 @@ struct SpokenWordTranscriptReader: View { /// 不再从菜单卡上再弹一层下拉菜单(弹出、收回时这一行整个放大缩回,卡片跟着闪)。 private var playbackRateRow: some View { let rate = player.currentSpokenWordRate - let slower = SpokenWordPlaybackRatePolicy.adjacentPreset(to: rate, faster: false) - let faster = SpokenWordPlaybackRatePolicy.adjacentPreset(to: rate, faster: true) + let slower = SpokenWordPlaybackRatePolicy.adjacentSliderStop(to: rate, faster: false) + let faster = SpokenWordPlaybackRatePolicy.adjacentSliderStop(to: rate, faster: true) return HStack(spacing: 2) { Text("spoken_word_speed_short") Spacer(minLength: 8) diff --git a/Primuse/Views/Settings/SettingsView.swift b/Primuse/Views/Settings/SettingsView.swift index 473bf1967..72f43b4db 100644 --- a/Primuse/Views/Settings/SettingsView.swift +++ b/Primuse/Views/Settings/SettingsView.swift @@ -2465,6 +2465,11 @@ private struct SpokenWordListeningAidSettingsRows: View { } .settingsAnchor("playback.spokenWordSmartSpeed") if settings.spokenWordSmartSpeedEnabled { + Picker("smart_speed_level_title", selection: $settings.spokenWordSmartSpeedLevel) { + ForEach(SmartSpeedLevel.enabledLevels) { level in + Text(level.localizedTitle).tag(level) + } + } SpokenWordSmartSpeedSavedRow() } Toggle(isOn: $settings.spokenWordVoiceBoostEnabled) { @@ -2473,6 +2478,11 @@ private struct SpokenWordListeningAidSettingsRows: View { } } .settingsAnchor("playback.spokenWordVoiceBoost") + Toggle(isOn: $settings.radioVoiceBoostEnabled) { + SettingsInfoLabel("radio_voice_boost") { + Text("radio_voice_boost_desc") + } + } } } diff --git a/PrimuseKit/Sources/PrimuseKit/Audio/PlaybackTimePitchProcessor.swift b/PrimuseKit/Sources/PrimuseKit/Audio/PlaybackTimePitchProcessor.swift index a44179163..23504655e 100644 --- a/PrimuseKit/Sources/PrimuseKit/Audio/PlaybackTimePitchProcessor.swift +++ b/PrimuseKit/Sources/PrimuseKit/Audio/PlaybackTimePitchProcessor.swift @@ -46,7 +46,7 @@ public final class PlaybackTimePitchProcessor: @unchecked Sendable { /// slowdown and key shifts retain spectral processing; only one unit stretches time. public func apply(rate: Float, pitchCents: Float = 0, isSpokenWord: Bool = false) { let next = Configuration( - rate: rate.isFinite ? min(2, max(0.5, rate)) : 1, + rate: SpokenWordPlaybackRatePolicy.clampedEngineRate(rate, isSpokenWord: isSpokenWord), pitch: pitchCents.isFinite ? min(2400, max(-2400, pitchCents)) : 0, isSpokenWord: isSpokenWord ) diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordAudioEffectsPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordAudioEffectsPolicy.swift new file mode 100644 index 000000000..2ef8e9b5c --- /dev/null +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordAudioEffectsPolicy.swift @@ -0,0 +1,162 @@ +import Foundation +import Observation + +/// 单个节目、单本书或单个电台的音频辅助覆盖项;字段为 nil 表示跟随全局设置。 +public struct SpokenWordAudioEffectsOverride: Codable, Equatable, Hashable, Sendable { + public var smartSpeedLevel: SmartSpeedLevel? + public var voiceBoostEnabled: Bool? + + public init(smartSpeedLevel: SmartSpeedLevel? = nil, voiceBoostEnabled: Bool? = nil) { + self.smartSpeedLevel = smartSpeedLevel + self.voiceBoostEnabled = voiceBoostEnabled + } + + public var isEmpty: Bool { + smartSpeedLevel == nil && voiceBoostEnabled == nil + } +} + +/// 跨收听空间(播客、有声书、电台)共用的音频辅助(智能速度 + 语音增强)解析策略。 +public enum SpokenWordAudioEffectsPolicy { + public static func globalSmartSpeedLevel( + enabled: Bool, + preferredLevel: SmartSpeedLevel + ) -> SmartSpeedLevel { + guard enabled else { return .off } + return preferredLevel == .off ? .standard : preferredLevel + } + + public static func effectiveSmartSpeedLevel( + space: ListeningSpace?, + override: SpokenWordAudioEffectsOverride?, + globalLevel: SmartSpeedLevel + ) -> SmartSpeedLevel { + switch space { + case .podcast, .spokenWord: + return override?.smartSpeedLevel ?? globalLevel + case .radio, .music, .ambient, nil: + return .off + } + } + + public static func effectiveVoiceBoost( + space: ListeningSpace?, + override: SpokenWordAudioEffectsOverride?, + globalSpokenWordEnabled: Bool, + globalRadioEnabled: Bool = false + ) -> Bool { + let fallback = VoiceBoostActivationPolicy.isActive( + space: space, + spokenWordEnabled: globalSpokenWordEnabled, + radioEnabled: globalRadioEnabled + ) + switch space { + case .podcast, .spokenWord, .radio: + return override?.voiceBoostEnabled ?? fallback + case .music, .ambient, nil: + return false + } + } + + public static func storedSmartSpeedOverride( + for level: SmartSpeedLevel, + global: SmartSpeedLevel + ) -> SmartSpeedLevel? { + level == global ? nil : level + } + + public static func storedVoiceBoostOverride( + for enabled: Bool, + global: Bool + ) -> Bool? { + enabled == global ? nil : enabled + } + + public static func radioScopeID(forStationID stationID: String) -> String { + "radio:\(stationID)" + } +} + +/// 按节目/按书/按电台保存音频辅助覆盖项,持久化在 UserDefaults。 +@MainActor +@Observable +public final class SpokenWordAudioEffectsPreferences { + public private(set) var revision = 0 + private var overrides: [String: SpokenWordAudioEffectsOverride] + @ObservationIgnored private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + if let data = defaults.data(forKey: Self.storageKey), + let decoded = try? JSONDecoder().decode([String: SpokenWordAudioEffectsOverride].self, from: data) { + overrides = decoded.filter { !$0.value.isEmpty } + } else { + overrides = [:] + } + } +} + +extension SpokenWordAudioEffectsPreferences { + public static let shared = SpokenWordAudioEffectsPreferences() + public static let didChange = Notification.Name("primuse.spokenWordAudioEffectsDidChange") + public static let storageKey = "primuse.spokenWord.audioEffectsOverrides.v1" + + public func override(forScopeID scopeID: String) -> SpokenWordAudioEffectsOverride? { + guard !scopeID.isEmpty else { return nil } + return overrides[scopeID] + } + + public func hasOverride(forScopeID scopeID: String) -> Bool { + override(forScopeID: scopeID) != nil + } + + public func setSmartSpeedLevel(_ level: SmartSpeedLevel?, forScopeID scopeID: String) { + guard !scopeID.isEmpty else { return } + var entry = overrides[scopeID] ?? SpokenWordAudioEffectsOverride() + guard entry.smartSpeedLevel != level else { return } + entry.smartSpeedLevel = level + store(entry, forScopeID: scopeID) + } + + public func setVoiceBoostEnabled(_ enabled: Bool?, forScopeID scopeID: String) { + guard !scopeID.isEmpty else { return } + var entry = overrides[scopeID] ?? SpokenWordAudioEffectsOverride() + guard entry.voiceBoostEnabled != enabled else { return } + entry.voiceBoostEnabled = enabled + store(entry, forScopeID: scopeID) + } + + public func clear(forScopeID scopeID: String) { + guard !scopeID.isEmpty, overrides.removeValue(forKey: scopeID) != nil else { return } + persist() + } + + public func carryBookState(renames: [String: String]) { + let original = overrides + for oldID in renames.keys.sorted() { + guard let newID = renames[oldID], !newID.isEmpty, + overrides[newID] == nil, let value = original[oldID] else { continue } + overrides[newID] = value + } + if overrides != original { persist() } + } + + private func store(_ entry: SpokenWordAudioEffectsOverride, forScopeID scopeID: String) { + if entry.isEmpty { + overrides.removeValue(forKey: scopeID) + } else { + overrides[scopeID] = entry + } + persist() + } + + private func persist() { + revision &+= 1 + if overrides.isEmpty { + defaults.removeObject(forKey: Self.storageKey) + } else if let data = try? JSONEncoder().encode(overrides) { + defaults.set(data, forKey: Self.storageKey) + } + NotificationCenter.default.post(name: Self.didChange, object: self) + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordListeningPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordListeningPolicy.swift index c593a42a1..344d2266b 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordListeningPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordListeningPolicy.swift @@ -68,14 +68,56 @@ public enum SpokenWordBookmarkPolicy { /// runs at follows the item that is playing. public enum SpokenWordPlaybackRatePolicy { public static let minimumRate: Float = 0.5 - public static let maximumRate: Float = 2.0 - public static let presets: [Float] = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0] + public static let maximumRate: Float = 3.0 + public static let presets: [Float] = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0] + + /// Overcast 风格非线性滑块刻度:在人耳最敏感的 0.8×–1.5× 区间提供 0.05× 精细步进, + /// 1.5×–2.0× 提供 0.1× 步进,2.0×–3.0× 提供 0.25× 步进。 + public static let sliderStops: [Float] = [ + 0.5, 0.6, 0.7, 0.75, + 0.8, 0.85, 0.9, 0.95, 1.0, + 1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45, 1.5, + 1.6, 1.7, 1.8, 1.9, 2.0, + 2.25, 2.5, 2.75, 3.0, + ] public static func clamped(_ rate: Float) -> Float { guard rate.isFinite else { return 1 } return min(maximumRate, max(minimumRate, rate)) } + /// 音频引擎通用的倍速限幅:有声内容支持 0.5×–3.0×,音乐保持 0.5×–2.0×。 + public static func clampedEngineRate(_ rate: Float, isSpokenWord: Bool) -> Float { + isSpokenWord ? clamped(rate) : VarispeedPolicy.clampedRate(rate) + } + + public static func nearestSliderIndex(for rate: Float) -> Int { + let clampedRate = clamped(rate) + var bestIndex = 0 + var bestDistance = Float.greatestFiniteMagnitude + for (index, stop) in sliderStops.enumerated() { + let distance = abs(stop - clampedRate) + if distance < bestDistance { + bestDistance = distance + bestIndex = index + } + } + return bestIndex + } + + public static func rate(forSliderIndex index: Int) -> Float { + guard !sliderStops.isEmpty else { return 1 } + return sliderStops[min(max(index, 0), sliderStops.count - 1)] + } + + public static func adjacentSliderStop(to rate: Float, faster: Bool) -> Float? { + let current = clamped(rate) + let tolerance: Float = 0.001 + return faster + ? sliderStops.first { $0 > current + tolerance } + : sliderStops.last { $0 < current - tolerance } + } + /// The rate the engine should run at right now. /// - Parameter rateAllowed: false when the output path cannot time-stretch /// (high-fidelity passthrough), where everything plays at 1×. @@ -86,7 +128,7 @@ public enum SpokenWordPlaybackRatePolicy { rateAllowed: Bool ) -> Float { guard rateAllowed else { return 1 } - return clamped(isSpokenWord ? spokenWordRate : musicRate) + return isSpokenWord ? clamped(spokenWordRate) : VarispeedPolicy.clampedRate(musicRate) } /// 一档一档地调(全屏文稿菜单里的减、加):往快取比当前快的第一档,往慢取比当前慢的最后一档。 diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift index 4c727b92e..b77609e88 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift @@ -48,6 +48,18 @@ public struct SmartSpeedPolicy: Sendable, Equatable { self.fadeDuration = fadeDuration } + /// 轻柔:保留更自然的语调停顿,适合演播节奏强、低语较多的有声书。 + public static let mild = SmartSpeedPolicy( + silenceThresholdDB: -45, + windowDuration: 0.01, + keptLeadingSilence: 0.30, + keptTrailingSilence: 0.14, + minimumCut: 0.15, + retainedRatio: 0.20, + maximumRetainedExtra: 0.50, + fadeDuration: 0.006 + ) + /// 默认:-42 dBFS 以下算静音,一段停顿最短剩约 0.35 秒,长停顿再按一成多留、最多多留 0.4 秒。 public static let standard = SmartSpeedPolicy( silenceThresholdDB: -42, @@ -60,6 +72,18 @@ public struct SmartSpeedPolicy: Sendable, Equatable { fadeDuration: 0.005 ) + /// 强力:更紧凑地压缩停顿,适合访谈播客、讲座与带轻微环境底噪的录音。 + public static let strong = SmartSpeedPolicy( + silenceThresholdDB: -38, + windowDuration: 0.01, + keptLeadingSilence: 0.15, + keptTrailingSilence: 0.07, + minimumCut: 0.06, + retainedRatio: 0.05, + maximumRetainedExtra: 0.20, + fadeDuration: 0.004 + ) + /// 换算到某个采样率下的帧数。 public struct Frames: Sendable, Equatable { public let window: Int @@ -492,3 +516,48 @@ public struct SmartSpeedSavingsMeter: Sendable, Equatable { lastSkipped = 0 } } + +/// 智能速度强度档位(参考 Overcast / Pocket Casts 分级缩短停顿体验)。 +public enum SmartSpeedLevel: String, Codable, CaseIterable, Hashable, Sendable, Identifiable { + case off + case mild + case standard + case strong + + public var id: String { rawValue } + public var isEnabled: Bool { self != .off } + public static let enabledLevels: [SmartSpeedLevel] = [.mild, .standard, .strong] + + public var policy: SmartSpeedPolicy? { + switch self { + case .off: return nil + case .mild: return .mild + case .standard: return .standard + case .strong: return .strong + } + } +} + +/// 实时估算开启智能速度后的等效倍速(例如基准 1.5× 且已跳过 12% 停顿 → 等效约 1.7×)。 +public enum SmartSpeedEffectiveRateEstimator { + public static let minimumObservedSourceSeconds: TimeInterval = 8 + public static let minimumSkippedSourceSeconds: TimeInterval = 0.25 + public static let maximumBoostFactor: Double = 1.6 + + public static func effectiveRate( + baseRate: Float, + elapsedSourceSeconds: TimeInterval, + skippedSourceSeconds: TimeInterval + ) -> Float? { + guard elapsedSourceSeconds.isFinite, skippedSourceSeconds.isFinite, + elapsedSourceSeconds >= minimumObservedSourceSeconds, + skippedSourceSeconds >= minimumSkippedSourceSeconds else { return nil } + let heard = elapsedSourceSeconds - skippedSourceSeconds + guard heard > 1 else { return nil } + let safeBase = Double(SpokenWordPlaybackRatePolicy.clamped(baseRate)) + let factor = min(maximumBoostFactor, elapsedSourceSeconds / heard) + let effective = safeBase * factor + guard effective - safeBase >= 0.03 else { return nil } + return Float((effective * 100).rounded() / 100) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Audio/PlaybackTimePitchProcessorTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Audio/PlaybackTimePitchProcessorTests.swift index 991c8046b..d3e95244c 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Audio/PlaybackTimePitchProcessorTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Audio/PlaybackTimePitchProcessorTests.swift @@ -41,10 +41,12 @@ struct PlaybackTimePitchProcessorTests { processor.apply(rate: 10, pitchCents: -3000) #expect(processor.spectralNode.rate == 2) #expect(processor.spectralNode.pitch == -2400) + processor.apply(rate: 10, pitchCents: 0, isSpokenWord: true) + #expect(processor.spectralNode.rate == 3) } @Test("Rendered speech-speed output has the requested duration and retains pitch", - arguments: [Float(0.5), 1.25, 1.5, 2]) + arguments: [Float(0.5), 1.25, 1.5, 2, 2.5, 3]) func renderedRate(_ rate: Float) throws { let fixture = try Fixture() defer { fixture.stop() } @@ -55,7 +57,8 @@ struct PlaybackTimePitchProcessorTests { let last = try #require(audible.last) let duration = Double(last - first) / fixture.sampleRate #expect(abs(duration - 2 / Double(rate)) < 0.12) - let middle = Array(output[Int(fixture.sampleRate * 0.3).. 0) + #expect(mildRemoved < standardRemoved) + #expect(standardRemoved < strongRemoved) + + // 轻度环境底噪(-40 dBFS):强力档能剪,标准档与轻柔档保留。 + let noisyPause = concat([speech(0.8), silence(2.0, levelDB: -40), speech(0.8)]) + #expect(run(noisyPause, policy: .mild).cuts.isEmpty) + #expect(run(noisyPause, policy: .standard).cuts.isEmpty) + #expect(!run(noisyPause, policy: .strong).cuts.isEmpty) + } + + @Test func effectiveRateEstimatorReportsAcceleratedSpeedAndGuardsEdgeCases() { + #expect(SmartSpeedEffectiveRateEstimator.effectiveRate(baseRate: 1.5, elapsedSourceSeconds: 5, skippedSourceSeconds: 1) == nil) + #expect(SmartSpeedEffectiveRateEstimator.effectiveRate(baseRate: 1.5, elapsedSourceSeconds: 60, skippedSourceSeconds: 0.1) == nil) + #expect(SmartSpeedEffectiveRateEstimator.effectiveRate(baseRate: 1.5, elapsedSourceSeconds: 60, skippedSourceSeconds: 60) == nil) + + let effective = SmartSpeedEffectiveRateEstimator.effectiveRate( + baseRate: 1.5, + elapsedSourceSeconds: 100, + skippedSourceSeconds: 15 + ) + #expect(effective == 1.76) + + let capped = SmartSpeedEffectiveRateEstimator.effectiveRate( + baseRate: 2.0, + elapsedSourceSeconds: 100, + skippedSourceSeconds: 90 + ) + #expect(capped == 3.2) + } + @Test func nonFiniteSamplesCountAsAudible() { var noisy = silence(2) noisy[0][1_000] = .nan diff --git a/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordSyncPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordSyncPolicyTests.swift index 4c8da4bb5..b1d00cf2c 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordSyncPolicyTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordSyncPolicyTests.swift @@ -421,14 +421,14 @@ struct SpokenWordBookPlaybackPolicyTests { @Test func bookRateFallsBackToGlobal() { #expect(SpokenWordPlaybackRatePolicy.bookRate(stored: nil, globalSpokenWordRate: 1.25) == 1.25) #expect(SpokenWordPlaybackRatePolicy.bookRate(stored: 1.75, globalSpokenWordRate: 1.25) == 1.75) - #expect(SpokenWordPlaybackRatePolicy.bookRate(stored: 9, globalSpokenWordRate: 1) == 2) + #expect(SpokenWordPlaybackRatePolicy.bookRate(stored: 9, globalSpokenWordRate: 1) == 3) #expect(SpokenWordPlaybackRatePolicy.bookRate(stored: .nan, globalSpokenWordRate: 1.5) == 1.5) } @Test func storedBookRateIsNilWhenEqualToGlobal() { #expect(SpokenWordPlaybackRatePolicy.storedBookRate(for: 1.25, globalSpokenWordRate: 1.25) == nil) #expect(SpokenWordPlaybackRatePolicy.storedBookRate(for: 1.5, globalSpokenWordRate: 1.25) == 1.5) - #expect(SpokenWordPlaybackRatePolicy.storedBookRate(for: 5, globalSpokenWordRate: 1) == 2) + #expect(SpokenWordPlaybackRatePolicy.storedBookRate(for: 5, globalSpokenWordRate: 1) == 3) } @Test func adjacentItems() { diff --git a/PrimuseTV/Audio/TVAudioEngine.swift b/PrimuseTV/Audio/TVAudioEngine.swift index d74e751cf..9d821a72f 100644 --- a/PrimuseTV/Audio/TVAudioEngine.swift +++ b/PrimuseTV/Audio/TVAudioEngine.swift @@ -392,7 +392,7 @@ extension TVAudioEngine { } func setSpokenWordRate(_ rate: Double) { - let clamped = rate.isFinite ? min(2, max(0.5, rate)) : 1 + let clamped = Double(SpokenWordPlaybackRatePolicy.clamped(Float(rate))) guard clamped != spokenWordRate else { return } currentTime = interpolatedTime() spokenWordRate = clamped diff --git a/PrimuseTV/Audio/TVSFBEngine.swift b/PrimuseTV/Audio/TVSFBEngine.swift index 28b88a61c..ff2169d93 100644 --- a/PrimuseTV/Audio/TVSFBEngine.swift +++ b/PrimuseTV/Audio/TVSFBEngine.swift @@ -23,7 +23,7 @@ final class TVSFBEngine: NSObject, @unchecked Sendable { private var timePitch: PlaybackTimePitchProcessor? func setPlaybackRate(_ rate: Float) { - let clamped = rate.isFinite ? min(2, max(0.5, rate)) : 1 + let clamped = SpokenWordPlaybackRatePolicy.clamped(rate) playbackRate = clamped guard let timePitch else { return } player.modifyProcessingGraph { _ in diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index 731de3d96..822fc007d 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -158,4 +158,87 @@ final class ListeningSpacesReliabilityTests: XCTestCase { let label = SpokenWordPlayerText.sleepTileLabel(player) XCTAssertTrue(label.contains("Chapter 7"), "Expected selected chapter title in '\(label)'") } + + func testPerShowSmartSpeedAndVoiceBoostOverridesAndRadioVoiceBoostReuse() { + let player = AudioPlayerService() + let prevSmart = player.playbackSettings.spokenWordSmartSpeedEnabled + let prevLevel = player.playbackSettings.spokenWordSmartSpeedLevel + let prevVoice = player.playbackSettings.spokenWordVoiceBoostEnabled + let prevRadioVoice = player.playbackSettings.radioVoiceBoostEnabled + cleanups.append { + player.playbackSettings.spokenWordSmartSpeedEnabled = prevSmart + player.playbackSettings.spokenWordSmartSpeedLevel = prevLevel + player.playbackSettings.spokenWordVoiceBoostEnabled = prevVoice + player.playbackSettings.radioVoiceBoostEnabled = prevRadioVoice + } + + player.playbackSettings.spokenWordSmartSpeedEnabled = true + player.playbackSettings.spokenWordSmartSpeedLevel = .standard + player.playbackSettings.spokenWordVoiceBoostEnabled = false + player.playbackSettings.radioVoiceBoostEnabled = false + + let bookSong = Song( + id: "override-book-\(UUID().uuidString)", + title: "Chapter 1", + artistName: "Author", + duration: 1_800, + fileFormat: .m4a, + filePath: "/books/override-ch1.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + let bookScope = player.spokenWordBookID(for: bookSong) + cleanups.append { SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: bookScope) } + + XCTAssertEqual(player.effectiveSmartSpeedLevel(for: bookSong), .standard) + XCTAssertFalse(player.effectiveVoiceBoostActive(for: bookSong)) + + SpokenWordAudioEffectsPreferences.shared.setSmartSpeedLevel(.strong, forScopeID: bookScope) + SpokenWordAudioEffectsPreferences.shared.setVoiceBoostEnabled(true, forScopeID: bookScope) + XCTAssertEqual(player.effectiveSmartSpeedLevel(for: bookSong), .strong) + XCTAssertTrue(player.effectiveVoiceBoostActive(for: bookSong)) + + let station = RadioStation( + id: "talk-radio-\(UUID().uuidString)", + name: "NPR", + streamURL: "https://radio.example.com/talk.flac" + ) + let radioSong = station.playbackSong + let radioScope = SpokenWordAudioEffectsPolicy.radioScopeID(forStationID: station.id) + cleanups.append { SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: radioScope) } + + XCTAssertFalse(player.effectiveVoiceBoostActive(for: radioSong)) + SpokenWordAudioEffectsPreferences.shared.setVoiceBoostEnabled(true, forScopeID: radioScope) + XCTAssertTrue(player.effectiveVoiceBoostActive(for: radioSong)) + XCTAssertEqual(player.effectiveSmartSpeedLevel(for: radioSong), .off) + + SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: radioScope) + player.playbackSettings.radioVoiceBoostEnabled = true + XCTAssertTrue(player.effectiveVoiceBoostActive(for: radioSong)) + } + + func testSpokenWordRateUpToThreeXPropagatesToAudioEngineWhileMusicCapsAtTwoX() { + let player = AudioPlayerService() + let bookSong = Song( + id: "fast-book-\(UUID().uuidString)", + title: "Fast Chapter", + artistName: "Author", + duration: 1_200, + fileFormat: .m4a, + filePath: "/books/fast.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + let bookID = player.spokenWordBookID(for: bookSong) + cleanups.append { SpokenWordStore.shared.setPlaybackRate(nil, forBookID: bookID) } + + player.currentSong = bookSong + player.handleSpokenWordItemChange(to: bookSong) + player.setSpokenWordRate(2.75, forBookID: bookID) + XCTAssertEqual(player.currentSpokenWordRate, 2.75, accuracy: 0.001) + XCTAssertEqual(player.audioEngine.playbackRate, 2.75, accuracy: 0.001) + + player.audioEngine.applyPlaybackRate(2.75, isSpokenWord: false) + XCTAssertEqual(player.audioEngine.playbackRate, 2.0, accuracy: 0.001) + } } From 38de8d4b601bd356e042c8d5571b5df2a7a01fb5 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 17:11:10 -0500 Subject: [PATCH 04/15] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=92=AD=E5=AE=A2?= =?UTF-8?q?=E4=B8=8E=E6=9C=89=E5=A3=B0=E4=B9=A6=E5=AF=8C=E7=AB=A0=E8=8A=82?= =?UTF-8?q?=E5=B0=81=E9=9D=A2/=E5=A4=96=E9=93=BE=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E4=B8=BA=E5=90=84=E6=94=B6=E5=90=AC=E7=A9=BA=E9=97=B4=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E7=9D=A1=E7=9C=A0=E5=AE=9A=E6=97=B6=E6=91=87=E4=B8=80?= =?UTF-8?q?=E6=91=87=E5=BB=B6=E9=95=BF=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 6 ++ .../Resources/ar.lproj/Localizable.strings | 3 + .../Resources/de.lproj/Localizable.strings | 3 + .../Resources/en.lproj/Localizable.strings | 3 + .../Resources/es-MX.lproj/Localizable.strings | 3 + .../Resources/fr.lproj/Localizable.strings | 3 + .../Resources/hi.lproj/Localizable.strings | 3 + .../Resources/ja.lproj/Localizable.strings | 3 + .../Resources/ko.lproj/Localizable.strings | 3 + .../Resources/pl.lproj/Localizable.strings | 3 + .../Resources/pt-BR.lproj/Localizable.strings | 3 + .../Resources/ru.lproj/Localizable.strings | 3 + .../Resources/th.lproj/Localizable.strings | 3 + .../Resources/tr.lproj/Localizable.strings | 3 + .../Resources/uk.lproj/Localizable.strings | 3 + .../zh-Hans.lproj/Localizable.strings | 3 + .../zh-Hant.lproj/Localizable.strings | 3 + .../Audio/AudioPlayerService+Podcast.swift | 2 +- .../AudioPlayerService+RemoteCommands.swift | 33 ++++++++ .../Audio/SleepTimerShakeExtender.swift | 82 +++++++++++++++++++ Primuse/Services/Podcast/PodcastNetwork.swift | 4 +- .../Views/NowPlaying/ChapterListView.swift | 50 ++++++++++- .../Views/NowPlaying/SleepTimerSheet.swift | 33 ++++++++ .../Metadata/ISOBaseMediaChapterParser.swift | 24 +++++- .../Playback/SleepTimerSchedule.swift | 29 +++++++ .../PrimuseKit/Podcast/PodcastModels.swift | 4 + .../SpokenWordNowPlayingPolicy.swift | 13 ++- .../SleepTimerShakeExtendPolicyTests.swift | 27 ++++++ .../Podcast/PodcastReliabilityTests.swift | 28 +++++++ PrimuseTV/Model/TVStore.swift | 2 +- .../ListeningSpacesReliabilityTests.swift | 24 ++++++ 31 files changed, 397 insertions(+), 12 deletions(-) create mode 100644 Primuse/Services/Audio/SleepTimerShakeExtender.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/Playback/SleepTimerShakeExtendPolicyTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index 757696698..1e63b56ca 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -2065,6 +2065,7 @@ 97A4BBA0025C73BAFEF38681 /* AudioPlayerService+RemoteCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5331651FCE7FBFE2A8CC03EC /* AudioPlayerService+RemoteCommands.swift */; }; 97E47882C10CAE731A79B5AE /* CarPlayReleasedListsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91DAAE4B0282E5F455CF4C4B /* CarPlayReleasedListsTests.swift */; }; 97E7A64A6FCD423FD26D5088 /* TopShelfProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D90034644AC0D8B867E2DB2 /* TopShelfProvider.swift */; }; + 97F223F598778FD638AD1E8B /* SleepTimerShakeExtender.swift in Sources */ = {isa = PBXBuildFile; fileRef = A02F61FEA45FDA5A15D550BB /* SleepTimerShakeExtender.swift */; }; 97FDC1287DB3CE7142AD3890 /* NativeAudioDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B638BB94F0E6542668978B3 /* NativeAudioDecoder.swift */; }; 983084B9EA621EC0D7E43351 /* MacSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C45DBC29426E786513B5CFA0 /* MacSettingsView.swift */; }; 9834D723F057514A45BAE813 /* MacPageReadiness.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5ECBEBE5FDE73D84F8554EF9 /* MacPageReadiness.swift */; }; @@ -2994,6 +2995,7 @@ E0E9ED4D1BFEB7CFD9E4B8FF /* DiagnosticReportMailer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AC69BCA4BB413F1DFDC58E5 /* DiagnosticReportMailer.swift */; }; E0F04D0EF9B20A9B33046401 /* CarPlayEditorCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7563332EFAE1A5E1F571491 /* CarPlayEditorCatalog.swift */; }; E0F81CCC4D4D80C022C98A59 /* OpenAICompatibleProviderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EB9BD8B836299C30B3A1296 /* OpenAICompatibleProviderTests.swift */; }; + E0F87F4AE8F38C1409CD5CCC /* SleepTimerShakeExtender.swift in Sources */ = {isa = PBXBuildFile; fileRef = A02F61FEA45FDA5A15D550BB /* SleepTimerShakeExtender.swift */; }; E0FB25D757DF8B8F69B9C8EB /* Citadel in Frameworks */ = {isa = PBXBuildFile; productRef = 9A175C9BD099798C235AC4B9 /* Citadel */; }; E0FC351BD5B65B68ADE990C9 /* AudioPlayerService+Varispeed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9717E7D0E27F1D531E0784A5 /* AudioPlayerService+Varispeed.swift */; }; E10622B7A91B305F630982A8 /* ListeningShare.strings in Resources */ = {isa = PBXBuildFile; fileRef = CFB47B562941745BC59E3FB0 /* ListeningShare.strings */; }; @@ -5266,6 +5268,7 @@ 9F9CC8CDA08186C484006077 /* TopLevelJSONArrayReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TopLevelJSONArrayReader.swift; sourceTree = ""; }; 9FE14B295320AA20C02A9BB3 /* WatchPlayerStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchPlayerStore.swift; sourceTree = ""; }; 9FE71018EB3E9DD202E86AEC /* LibraryCatalogMirror.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryCatalogMirror.swift; sourceTree = ""; }; + A02F61FEA45FDA5A15D550BB /* SleepTimerShakeExtender.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SleepTimerShakeExtender.swift; sourceTree = ""; }; A030D8AD71D4A5246B0645C8 /* SpokenChapterImport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenChapterImport.swift; sourceTree = ""; }; A035EED5644BB3267E81E1CF /* SongsPageFolderReleasedTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SongsPageFolderReleasedTests.swift; sourceTree = ""; }; A099F9B1472D4ABEA9E86039 /* AppleMusicLibraryIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleMusicLibraryIdentity.swift; sourceTree = ""; }; @@ -6305,6 +6308,7 @@ 80BF155F8BD6EBFBBAA9B83A /* PlaybackSettingsStore.swift */, 020308EF5DA7D67F5FF52ADE /* PlaybackSettingsStore+VarispeedAndHaptics.swift */, DE4D2439290BE1D613770C9E /* ReplayGainAnalysisService.swift */, + A02F61FEA45FDA5A15D550BB /* SleepTimerShakeExtender.swift */, FF7F66F30F1802BA29DEB696 /* StreamingDownloadDecoder.swift */, 47045D142911DBCEDDECED31 /* TransitionEnvelopeProbe.swift */, ); @@ -11998,6 +12002,7 @@ 4DAD8EC05A5F9510CE5999B3 /* SiriMediaInteractionDonor.swift in Sources */, 2397DE1952ABED43B577663D /* SiriSettingsView.swift in Sources */, 84BFE398306533A2FDC82BC4 /* SiriSpokenNamesGuideView.swift in Sources */, + 97F223F598778FD638AD1E8B /* SleepTimerShakeExtender.swift in Sources */, 1C46E6DFCE3EB4A753078E3A /* SleepTimerSheet.swift in Sources */, 51788D2CE6B14D8AEC96F19F /* SmartNudgeCenter.swift in Sources */, 1195F4C685A15098540F4A80 /* SmartNudgeOverlay.swift in Sources */, @@ -13216,6 +13221,7 @@ 574E4DCF2EB829BCC4E2D9F8 /* SiriMediaInteractionDonor.swift in Sources */, 086F04A798AC70AC16E0B9D4 /* SiriSettingsView.swift in Sources */, 7033B713D39A8C0E1605A1A9 /* SiriSpokenNamesGuideView.swift in Sources */, + E0F87F4AE8F38C1409CD5CCC /* SleepTimerShakeExtender.swift in Sources */, 7D0C759614CAB0E41E588E71 /* SleepTimerSheet.swift in Sources */, AC8C2032CECB70E36A882108 /* SmartNudgeCenter.swift in Sources */, 6F5899A91CEA7698A1F8C916 /* SmartNudgeOverlay.swift in Sources */, diff --git a/Primuse/Resources/ar.lproj/Localizable.strings b/Primuse/Resources/ar.lproj/Localizable.strings index b7893f44c..3dd36ac76 100644 --- a/Primuse/Resources/ar.lproj/Localizable.strings +++ b/Primuse/Resources/ar.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ فعليًا"; "radio_voice_boost" = "تعزيز الصوت للراديو"; "radio_voice_boost_desc" = "يعيد استخدام تعزيز الصوت لبث الراديو المفكك محليًا، مثالي لمحطات الأخبار والحوار."; +"sleep_timer_shake_to_extend" = "الهز للتمديد"; +"sleep_timer_shake_to_extend_desc" = "خلال آخر 5 دقائق أو أثناء خفت الصوت، هزّ iPhone برفق لإضافة 15 دقيقة."; +"chapter_open_link" = "فتح رابط الفصل"; diff --git a/Primuse/Resources/de.lproj/Localizable.strings b/Primuse/Resources/de.lproj/Localizable.strings index 3c8b64061..3e3154399 100644 --- a/Primuse/Resources/de.lproj/Localizable.strings +++ b/Primuse/Resources/de.lproj/Localizable.strings @@ -8464,3 +8464,6 @@ "audio_effects_effective_rate_format" = "≈ %@ effektiv"; "radio_voice_boost" = "Radio-Stimmverstärkung"; "radio_voice_boost_desc" = "Nutzt die Stimmverstärkung auch für lokal dekodierte Radiosender, ideal für Nachrichten und Talk-Radio."; +"sleep_timer_shake_to_extend" = "Schütteln zum Verlängern"; +"sleep_timer_shake_to_extend_desc" = "In den letzten 5 Minuten oder beim Ausblenden kurz schütteln, um um 15 Minuten zu verlängern."; +"chapter_open_link" = "Kapitellink öffnen"; diff --git a/Primuse/Resources/en.lproj/Localizable.strings b/Primuse/Resources/en.lproj/Localizable.strings index 9b9770561..19b0b3718 100644 --- a/Primuse/Resources/en.lproj/Localizable.strings +++ b/Primuse/Resources/en.lproj/Localizable.strings @@ -8226,3 +8226,6 @@ "audio_effects_effective_rate_format" = "≈ %@ effective"; "radio_voice_boost" = "Radio Voice Boost"; "radio_voice_boost_desc" = "Reuses Voice Boost for locally decoded radio streams, ideal for news and talk stations."; +"sleep_timer_shake_to_extend" = "Shake to Extend"; +"sleep_timer_shake_to_extend_desc" = "During the final 5 minutes or fade-out, gently shake your iPhone to add 15 minutes."; +"chapter_open_link" = "Open Chapter Link"; diff --git a/Primuse/Resources/es-MX.lproj/Localizable.strings b/Primuse/Resources/es-MX.lproj/Localizable.strings index e6d2d1b14..8737ff36b 100644 --- a/Primuse/Resources/es-MX.lproj/Localizable.strings +++ b/Primuse/Resources/es-MX.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ efectivo"; "radio_voice_boost" = "Realce de voz en radio"; "radio_voice_boost_desc" = "Reutiliza el realce de voz en estaciones decodificadas localmente, ideal para noticias y programas hablados."; +"sleep_timer_shake_to_extend" = "Agitar para extender"; +"sleep_timer_shake_to_extend_desc" = "Durante los últimos 5 minutos o el desvanecimiento, agita suavemente el iPhone para sumar 15 minutos."; +"chapter_open_link" = "Abrir enlace del capítulo"; diff --git a/Primuse/Resources/fr.lproj/Localizable.strings b/Primuse/Resources/fr.lproj/Localizable.strings index 0e2b8af08..8685c34c8 100644 --- a/Primuse/Resources/fr.lproj/Localizable.strings +++ b/Primuse/Resources/fr.lproj/Localizable.strings @@ -8464,3 +8464,6 @@ "audio_effects_effective_rate_format" = "≈ %@ effectif"; "radio_voice_boost" = "Amplification vocale radio"; "radio_voice_boost_desc" = "Réutilise l’amplification vocale sur les flux radio décodés localement, idéal pour l’info et les débats."; +"sleep_timer_shake_to_extend" = "Secouer pour prolonger"; +"sleep_timer_shake_to_extend_desc" = "Durant les 5 dernières minutes ou le fondu, secouez doucement l’iPhone pour ajouter 15 minutes."; +"chapter_open_link" = "Ouvrir le lien du chapitre"; diff --git a/Primuse/Resources/hi.lproj/Localizable.strings b/Primuse/Resources/hi.lproj/Localizable.strings index 1d65cbfcf..8f4423ab3 100644 --- a/Primuse/Resources/hi.lproj/Localizable.strings +++ b/Primuse/Resources/hi.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ प्रभावी"; "radio_voice_boost" = "रेडियो वॉइस बूस्ट"; "radio_voice_boost_desc" = "स्थानीय रूप से डिकोड की गई रेडियो स्ट्रीम के लिए वॉइस बूस्ट का उपयोग करता है, समाचार और टॉक स्टेशनों के लिए उपयुक्त।"; +"sleep_timer_shake_to_extend" = "बढ़ाने के लिए हिलाएँ"; +"sleep_timer_shake_to_extend_desc" = "अंतिम 5 मिनट या फ़ेड-आउट के दौरान 15 मिनट जोड़ने के लिए iPhone को हल्का हिलाएँ।"; +"chapter_open_link" = "अध्याय लिंक खोलें"; diff --git a/Primuse/Resources/ja.lproj/Localizable.strings b/Primuse/Resources/ja.lproj/Localizable.strings index b431decd6..86af3b8ec 100644 --- a/Primuse/Resources/ja.lproj/Localizable.strings +++ b/Primuse/Resources/ja.lproj/Localizable.strings @@ -8465,3 +8465,6 @@ "audio_effects_effective_rate_format" = "実効 約%@"; "radio_voice_boost" = "ラジオ音声強調"; "radio_voice_boost_desc" = "ローカルデコードされるラジオ放送で音声強調を再利用します。ニュースやトーク番組に最適です。"; +"sleep_timer_shake_to_extend" = "シェイクで延長"; +"sleep_timer_shake_to_extend_desc" = "残り5分以内またはフェードアウト中にiPhoneを軽く振ると15分延長されます。"; +"chapter_open_link" = "チャプターリンクを開く"; diff --git a/Primuse/Resources/ko.lproj/Localizable.strings b/Primuse/Resources/ko.lproj/Localizable.strings index a03c2dd4e..a524d0c7e 100644 --- a/Primuse/Resources/ko.lproj/Localizable.strings +++ b/Primuse/Resources/ko.lproj/Localizable.strings @@ -8464,3 +8464,6 @@ "audio_effects_effective_rate_format" = "체감 약 %@"; "radio_voice_boost" = "라디오 음성 강조"; "radio_voice_boost_desc" = "로컬 디코딩 라디오 스트림에서 음성 강조를 함께 사용합니다. 뉴스와 토크 방송에 적합합니다."; +"sleep_timer_shake_to_extend" = "흔들어서 연장"; +"sleep_timer_shake_to_extend_desc" = "종료 5분 전 또는 페이드아웃 중에 iPhone을 가볍게 흔들면 15분 연장됩니다."; +"chapter_open_link" = "챕터 링크 열기"; diff --git a/Primuse/Resources/pl.lproj/Localizable.strings b/Primuse/Resources/pl.lproj/Localizable.strings index 5355c5de7..370afeb43 100644 --- a/Primuse/Resources/pl.lproj/Localizable.strings +++ b/Primuse/Resources/pl.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ efektywnie"; "radio_voice_boost" = "Wzmocnienie głosu w radiu"; "radio_voice_boost_desc" = "Wykorzystuje wzmocnienie głosu dla lokalnie dekodowanych stacji radiowych, idealne do wiadomości i audycji mówionych."; +"sleep_timer_shake_to_extend" = "Potrząśnij, aby przedłużyć"; +"sleep_timer_shake_to_extend_desc" = "W ciągu ostatnich 5 minut lub wyciszania lekko potrząśnij iPhonem, aby dodać 15 minut."; +"chapter_open_link" = "Otwórz link rozdziału"; diff --git a/Primuse/Resources/pt-BR.lproj/Localizable.strings b/Primuse/Resources/pt-BR.lproj/Localizable.strings index e59f7d341..582aba6b3 100644 --- a/Primuse/Resources/pt-BR.lproj/Localizable.strings +++ b/Primuse/Resources/pt-BR.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ efetivo"; "radio_voice_boost" = "Realce de voz no rádio"; "radio_voice_boost_desc" = "Reaproveita o realce de voz em transmissões de rádio decodificadas localmente, ideal para notícias e entrevistas."; +"sleep_timer_shake_to_extend" = "Agitar para estender"; +"sleep_timer_shake_to_extend_desc" = "Nos últimos 5 minutos ou durante o fade-out, agite suavemente o iPhone para adicionar 15 minutos."; +"chapter_open_link" = "Abrir link do capítulo"; diff --git a/Primuse/Resources/ru.lproj/Localizable.strings b/Primuse/Resources/ru.lproj/Localizable.strings index c7d481fd3..b1477c6f6 100644 --- a/Primuse/Resources/ru.lproj/Localizable.strings +++ b/Primuse/Resources/ru.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ факт."; "radio_voice_boost" = "Усиление голоса для радио"; "radio_voice_boost_desc" = "Применяет усиление голоса к локально декодируемым радиопотокам — удобно для новостей и разговорных станций."; +"sleep_timer_shake_to_extend" = "Встряхнуть для продления"; +"sleep_timer_shake_to_extend_desc" = "В последние 5 минут или при затухании слегка встряхните iPhone, чтобы добавить 15 минут."; +"chapter_open_link" = "Открыть ссылку главы"; diff --git a/Primuse/Resources/th.lproj/Localizable.strings b/Primuse/Resources/th.lproj/Localizable.strings index f266f4748..a8f4ea40e 100644 --- a/Primuse/Resources/th.lproj/Localizable.strings +++ b/Primuse/Resources/th.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ โดยประมาณ"; "radio_voice_boost" = "เร่งเสียงพูดวิทยุ"; "radio_voice_boost_desc" = "ใช้การเร่งเสียงพูดร่วมกับสตรีมวิทยุที่ถอดรหัสในเครื่อง เหมาะสำหรับสถานีข่าวและรายการสนทนา"; +"sleep_timer_shake_to_extend" = "เขย่าเพื่อต่อเวลา"; +"sleep_timer_shake_to_extend_desc" = "ในช่วง 5 นาทีสุดท้ายหรือขณะค่อยๆ ลดเสียง เขย่า iPhone เบาๆ เพื่อเพิ่มอีก 15 นาที"; +"chapter_open_link" = "เปิดลิงก์บท"; diff --git a/Primuse/Resources/tr.lproj/Localizable.strings b/Primuse/Resources/tr.lproj/Localizable.strings index 3351d5c8f..41b467bdd 100644 --- a/Primuse/Resources/tr.lproj/Localizable.strings +++ b/Primuse/Resources/tr.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ etkin"; "radio_voice_boost" = "Radyo Ses Güçlendirme"; "radio_voice_boost_desc" = "Yerel olarak çözülen radyo yayınlarında ses güçlendirmeyi kullanır; haber ve sohbet istasyonları için idealdir."; +"sleep_timer_shake_to_extend" = "Uzatmak İçin Salla"; +"sleep_timer_shake_to_extend_desc" = "Son 5 dakikada veya ses kısılırken 15 dakika eklemek için iPhone'u hafifçe sallayın."; +"chapter_open_link" = "Bölüm Bağlantısını Aç"; diff --git a/Primuse/Resources/uk.lproj/Localizable.strings b/Primuse/Resources/uk.lproj/Localizable.strings index e287e0de8..ad8988495 100644 --- a/Primuse/Resources/uk.lproj/Localizable.strings +++ b/Primuse/Resources/uk.lproj/Localizable.strings @@ -8370,3 +8370,6 @@ "audio_effects_effective_rate_format" = "≈ %@ факт."; "radio_voice_boost" = "Підсилення голосу для радіо"; "radio_voice_boost_desc" = "Застосовує підсилення голосу до локально декодованих радіопотоків — ідеально для новин і розмовних станцій."; +"sleep_timer_shake_to_extend" = "Струсити для продовження"; +"sleep_timer_shake_to_extend_desc" = "Протягом останніх 5 хвилин або затухання злегка струсіть iPhone, щоб додати 15 хвилин."; +"chapter_open_link" = "Відкрити посилання розділу"; diff --git a/Primuse/Resources/zh-Hans.lproj/Localizable.strings b/Primuse/Resources/zh-Hans.lproj/Localizable.strings index 9ae96495a..6a591e9cc 100644 --- a/Primuse/Resources/zh-Hans.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hans.lproj/Localizable.strings @@ -8557,3 +8557,6 @@ "audio_effects_effective_rate_format" = "等效约 %@"; "radio_voice_boost" = "电台人声增强"; "radio_voice_boost_desc" = "收听走本地解码的广播电台时复用语音增强,适合新闻与谈话台。"; +"sleep_timer_shake_to_extend" = "摇一摇延长定时"; +"sleep_timer_shake_to_extend_desc" = "在倒计时最后 5 分钟或渐弱期间轻摇手机,自动延长 15 分钟。"; +"chapter_open_link" = "打开章节链接"; diff --git a/Primuse/Resources/zh-Hant.lproj/Localizable.strings b/Primuse/Resources/zh-Hant.lproj/Localizable.strings index 51166e7f0..e143da7d3 100644 --- a/Primuse/Resources/zh-Hant.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hant.lproj/Localizable.strings @@ -8441,3 +8441,6 @@ "audio_effects_effective_rate_format" = "等效約 %@"; "radio_voice_boost" = "電台人聲增強"; "radio_voice_boost_desc" = "收聽本機解碼的廣播電台時共用語音增強,適合新聞與談話台。"; +"sleep_timer_shake_to_extend" = "搖一搖延長定時"; +"sleep_timer_shake_to_extend_desc" = "在倒數最後 5 分鐘或淡出期間輕搖手機,自動延長 15 分鐘。"; +"chapter_open_link" = "開啟章節連結"; diff --git a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift index 7b44be665..361020015 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift @@ -227,7 +227,7 @@ extension AudioPlayerService { } } if !found.episode.chapters.isEmpty { - spokenWordChapters = found.episode.chapters.map { MediaChapter(startTime: $0.start, title: $0.title) } + spokenWordChapters = found.episode.chapters.map(\.mediaChapter) refreshCurrentChapter() } else { // feed 指的 JSON,没有就读音频文件里的 ID3 章节(MP3 单集多半只写在那里)。 diff --git a/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift b/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift index 05a7f6200..e6be2f740 100644 --- a/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift +++ b/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift @@ -330,8 +330,37 @@ extension AudioPlayerService { set { UserDefaults.standard.set(newValue, forKey: SleepTimerSchedulePolicy.finishesTrackPreferenceKey) } } + var sleepTimerShakeToExtend: Bool { + get { UserDefaults.standard.bool(forKey: SleepTimerShakeExtendPolicy.preferenceKey) } + set { + UserDefaults.standard.set(newValue, forKey: SleepTimerShakeExtendPolicy.preferenceKey) + syncSleepTimerShakeExtender() + } + } + + func syncSleepTimerShakeExtender() { + SleepTimerShakeExtender.shared.sync( + activeEndDate: sleepTimerEndDate, + enabled: sleepTimerShakeToExtend + ) { [weak self] in + self?.handleSleepTimerShakeExtension() + } + } + + @discardableResult + func handleSleepTimerShakeExtension(now: Date = Date()) -> Bool { + guard sleepTimerShakeToExtend, + SleepTimerShakeExtender.shared.consumeShakeIfEligible(endDate: sleepTimerEndDate, now: now) else { + return false + } + plog("🌙 Sleep timer extended by \(SleepTimerShakeExtendPolicy.defaultExtensionMinutes)m via shake") + extendSleep(minutes: SleepTimerShakeExtendPolicy.defaultExtensionMinutes) + return true + } + private func startSleepCountdown(until endDate: Date) { sleepTimerEndDate = endDate + syncSleepTimerShakeExtender() sleepTimerTask = Task { // Wait until the fade begins, then bring the level down over the // last half minute so falling asleep does not end on a hard cut. @@ -356,11 +385,13 @@ extension AudioPlayerService { self.sleepTimerEndDate = nil self.sleepTimerStartDate = nil self.sleepStopAfterSongID = songID + SleepTimerShakeExtender.shared.stop() return } self.pause() self.sleepTimerEndDate = nil self.sleepTimerStartDate = nil + SleepTimerShakeExtender.shared.stop() return } let restoreVolume = self.audioEngine.userVolume @@ -383,6 +414,7 @@ extension AudioPlayerService { self.setPlaybackVolume(restoreVolume, persist: false) self.sleepTimerEndDate = nil self.sleepTimerStartDate = nil + SleepTimerShakeExtender.shared.stop() } } @@ -414,6 +446,7 @@ extension AudioPlayerService { sleepStopAfterSongID = nil sleepStopAfterChapter = nil sleepStopAfterBook = nil + SleepTimerShakeExtender.shared.stop() } // MARK: - DLNA Casting Media Resolution, Gapless Preload & Runtime Keep-Alive diff --git a/Primuse/Services/Audio/SleepTimerShakeExtender.swift b/Primuse/Services/Audio/SleepTimerShakeExtender.swift new file mode 100644 index 000000000..455f4659a --- /dev/null +++ b/Primuse/Services/Audio/SleepTimerShakeExtender.swift @@ -0,0 +1,82 @@ +import Foundation +import PrimuseKit +#if os(iOS) +import CoreMotion +import UIKit +#endif + +/// 睡眠定时运行时的轻量化摇一摇监听器(仅 iOS 在睡眠倒计时启用且用户打开开关时运行,空闲 0 耗电)。 +/// 播客、有声书、电台、音乐与环境音共用同一套延长逻辑。 +@MainActor +final class SleepTimerShakeExtender { + static let shared = SleepTimerShakeExtender() + + private var lastExtendedAt: Date? + #if os(iOS) + private let motionManager = CMMotionManager() + private let motionQueue: OperationQueue = { + let queue = OperationQueue() + queue.name = "com.welape.yuanyin.sleep-shake" + queue.maxConcurrentOperationCount = 1 + return queue + }() + #endif + + private init() {} + + func sync( + activeEndDate: Date?, + enabled: Bool, + onExtend: @escaping @MainActor () -> Void + ) { + #if os(iOS) + guard enabled, activeEndDate != nil, motionManager.isDeviceMotionAvailable else { + stop() + return + } + if motionManager.isDeviceMotionActive { return } + motionManager.deviceMotionUpdateInterval = 0.1 + motionManager.startDeviceMotionUpdates(to: motionQueue) { motion, _ in + guard let acc = motion?.userAcceleration else { return } + guard SleepTimerShakeExtendPolicy.exceedsThreshold( + userAccelerationX: acc.x, + y: acc.y, + z: acc.z + ) else { return } + Task { @MainActor in + onExtend() + } + } + #else + _ = (activeEndDate, enabled, onExtend) + #endif + } + + func stop() { + #if os(iOS) + if motionManager.isDeviceMotionActive { + motionManager.stopDeviceMotionUpdates() + } + #endif + } + + /// 根据策略判断是否应延长并记录防抖时间戳;返回 true 表示已放行延长。 + func consumeShakeIfEligible(endDate: Date?, now: Date = Date()) -> Bool { + guard let endDate else { return false } + let remaining = endDate.timeIntervalSince(now) + guard SleepTimerShakeExtendPolicy.shouldExtend( + remaining: remaining, + lastExtendedAt: lastExtendedAt, + now: now + ) else { return false } + lastExtendedAt = now + #if os(iOS) + UINotificationFeedbackGenerator().notificationOccurred(.success) + #endif + return true + } + + func resetCooldownForTesting() { + lastExtendedAt = nil + } +} diff --git a/Primuse/Services/Podcast/PodcastNetwork.swift b/Primuse/Services/Podcast/PodcastNetwork.swift index dcd5fcfbe..ad93b578a 100644 --- a/Primuse/Services/Podcast/PodcastNetwork.swift +++ b/Primuse/Services/Podcast/PodcastNetwork.swift @@ -362,12 +362,12 @@ enum PodcastChapterLoader { /// 下载过的单集照样读本机文件。 static func chapters(for episode: PodcastEpisode, readsRemoteFile: Bool = true) async -> [MediaChapter] { if !episode.chapters.isEmpty { - return episode.chapters.map { MediaChapter(startTime: $0.start, title: $0.title) } + return episode.chapters.map(\.mediaChapter) } if let found = known[episode.id] { return found } if let chaptersURL = episode.chaptersURL { let listed = await PodcastNetwork.chapters(from: chaptersURL) - .map { MediaChapter(startTime: $0.start, title: $0.title) } + .map(\.mediaChapter) if !listed.isEmpty { remember(listed, for: episode.id) return listed diff --git a/Primuse/Views/NowPlaying/ChapterListView.swift b/Primuse/Views/NowPlaying/ChapterListView.swift index 4ec45387d..2f05eaeb8 100644 --- a/Primuse/Views/NowPlaying/ChapterListView.swift +++ b/Primuse/Views/NowPlaying/ChapterListView.swift @@ -496,6 +496,11 @@ private struct SpokenWordContentsList: View, Equatable { @ViewBuilder private func rowMenu(_ row: SpokenWordContentsRow) -> some View { + if let url = row.url { + Link(destination: url) { + Label("chapter_open_link", systemImage: "safari") + } + } if player.currentItemIsAudiobook { let repeating = player.isRepeatingSpokenWordRow(row) Button { @@ -538,6 +543,8 @@ struct SpokenWordContentsRowView: View { var palette: SpokenWordPlayerPalette? var isRepeating = false + @Environment(\.openURL) private var openURL + private var primary: Color { palette?.primary ?? .primary } private var secondary: Color { palette?.secondary ?? .secondary } private var tertiary: Color { palette?.tertiary ?? Color.secondary.opacity(0.75) } @@ -547,10 +554,31 @@ struct SpokenWordContentsRowView: View { var body: some View { HStack(spacing: 12) { - Text(verbatim: "\(row.number)") - .font(.footnote.monospacedDigit().weight(.semibold)) - .foregroundStyle(row.isCurrent ? accent : (isFinished ? tertiary : secondary)) - .frame(minWidth: 28, alignment: .leading) + if let imageURL = row.imageURL { + AsyncImage(url: imageURL) { phase in + switch phase { + case .success(let image): + image + .resizable() + .scaledToFill() + default: + ZStack { + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(tertiary.opacity(0.16)) + Text(verbatim: "\(row.number)") + .font(.caption.monospacedDigit().weight(.semibold)) + .foregroundStyle(row.isCurrent ? accent : secondary) + } + } + } + .frame(width: 36, height: 36) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } else { + Text(verbatim: "\(row.number)") + .font(.footnote.monospacedDigit().weight(.semibold)) + .foregroundStyle(row.isCurrent ? accent : (isFinished ? tertiary : secondary)) + .frame(minWidth: 28, alignment: .leading) + } VStack(alignment: .leading, spacing: 3) { Text(verbatim: row.title.isEmpty ? " " : row.title) @@ -567,6 +595,20 @@ struct SpokenWordContentsRowView: View { Spacer(minLength: 0) + if let linkURL = row.url { + Button { + openURL(linkURL) + } label: { + Image(systemName: "safari") + .font(.subheadline) + .foregroundStyle(secondary) + .frame(width: 30, height: 30) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text("chapter_open_link")) + } + if isRepeating { Image(systemName: "repeat.1") .font(.footnote.weight(.semibold)) diff --git a/Primuse/Views/NowPlaying/SleepTimerSheet.swift b/Primuse/Views/NowPlaying/SleepTimerSheet.swift index 4513a4956..77bdc5f02 100644 --- a/Primuse/Views/NowPlaying/SleepTimerSheet.swift +++ b/Primuse/Views/NowPlaying/SleepTimerSheet.swift @@ -83,6 +83,7 @@ struct SleepTimerSheet: View { @Environment(\.dismiss) private var dismiss @Environment(\.dynamicTypeSize) private var dynamicTypeSize @AppStorage(SleepTimerSchedulePolicy.finishesTrackPreferenceKey) private var finishesTrack = false + @AppStorage(SleepTimerShakeExtendPolicy.preferenceKey) private var shakeToExtend = false /// 上一次自定义的时长与时刻,下次打开接着用。 @AppStorage("primuse.sleepTimer.customMinutes") private var customMinutes = 20 @AppStorage("primuse.sleepTimer.clockMinuteOfDay") private var clockMinuteOfDay = 23 * 60 @@ -158,6 +159,12 @@ struct SleepTimerSheet: View { VStack(alignment: .leading, spacing: 18) { if showsRunningTimer { statusCard + #if os(iOS) + if player.sleepTimerEndDate != nil { + Divider() + shakeToExtendSection + } + #endif } else { modeEditor .frame(minHeight: 202) @@ -165,6 +172,12 @@ struct SleepTimerSheet: View { Divider() finishTrackSection } + #if os(iOS) + if customMode != .end { + Divider() + shakeToExtendSection + } + #endif } } .padding(.horizontal, 20) @@ -684,6 +697,26 @@ struct SleepTimerSheet: View { .fixedSize(horizontal: false, vertical: true) } } + + #if os(iOS) + private var shakeToExtendSection: some View { + VStack(alignment: .leading, spacing: 8) { + Toggle(isOn: $shakeToExtend) { + Text("sleep_timer_shake_to_extend") + .font(.subheadline) + } + .toggleStyle(.switch) + .onChange(of: shakeToExtend) { _, _ in + player.syncSleepTimerShakeExtender() + } + .accessibilityIdentifier("sleepTimer.shakeToExtend") + Text("sleep_timer_shake_to_extend_desc") + .font(.footnote) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + #endif } #if os(iOS) diff --git a/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift b/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift index aa0719a7f..ed4c55ade 100644 --- a/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift +++ b/PrimuseKit/Sources/PrimuseKit/Metadata/ISOBaseMediaChapterParser.swift @@ -1,18 +1,38 @@ import Foundation -/// One chapter mark recovered from a media file. +/// One chapter mark recovered from a media file or podcast feed. public struct MediaChapter: Equatable, Sendable, Codable, Identifiable { /// Start of the chapter on the decoded timeline, in seconds. public var startTime: TimeInterval public var endTime: TimeInterval? public var title: String + /// Optional external reference link (e.g. Podlove / Podcasting 2.0 chapter URL). + public var url: URL? + /// Optional per-chapter artwork URL (e.g. Podlove / Podcasting 2.0 chapter img). + public var imageURL: URL? public var id: String { "\(startTime)-\(title)" } - public init(startTime: TimeInterval, title: String, endTime: TimeInterval? = nil) { + /// Only http/https URLs with a host are safe to open externally. + public var webURL: URL? { + guard let url, let scheme = url.scheme?.lowercased(), + scheme == "http" || scheme == "https", + url.host?.isEmpty == false else { return nil } + return url + } + + public init( + startTime: TimeInterval, + title: String, + endTime: TimeInterval? = nil, + url: URL? = nil, + imageURL: URL? = nil + ) { self.startTime = startTime self.title = title self.endTime = endTime + self.url = url + self.imageURL = imageURL } } diff --git a/PrimuseKit/Sources/PrimuseKit/Playback/SleepTimerSchedule.swift b/PrimuseKit/Sources/PrimuseKit/Playback/SleepTimerSchedule.swift index 8da5802a4..39176ef27 100644 --- a/PrimuseKit/Sources/PrimuseKit/Playback/SleepTimerSchedule.swift +++ b/PrimuseKit/Sources/PrimuseKit/Playback/SleepTimerSchedule.swift @@ -110,3 +110,32 @@ public enum SleepTimerSchedulePolicy { return remaining > 0 && remaining <= maximumTrackFinishWait } } + +/// 摇一摇延长睡眠定时策略(播客、有声书、电台、音乐共用): +/// 仅在倒计时最后窗口内(含 30 秒渐弱)接受有效晃动,避免白天放口袋误触,并防抖限频。 +public enum SleepTimerShakeExtendPolicy { + public static let preferenceKey = "primuse.sleepTimer.shakeToExtend" + public static let defaultExtensionMinutes = 15 + public static let activeWindowBeforeEnd: TimeInterval = 5 * 60 + public static let cooldownSeconds: TimeInterval = 5 + /// 线性加速度矢量模长阈值(单位 g,去除了重力分量)。 + public static let accelerationThresholdG: Double = 1.65 + + public static func exceedsThreshold(userAccelerationX x: Double, y: Double, z: Double) -> Bool { + guard x.isFinite, y.isFinite, z.isFinite else { return false } + let magnitude = (x * x + y * y + z * z).squareRoot() + return magnitude >= accelerationThresholdG + } + + public static func shouldExtend( + remaining: TimeInterval, + lastExtendedAt: Date?, + now: Date + ) -> Bool { + guard remaining.isFinite, remaining > 0, remaining <= activeWindowBeforeEnd else { return false } + if let lastExtendedAt, now.timeIntervalSince(lastExtendedAt) < cooldownSeconds { + return false + } + return true + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift index 4694a22ff..e4b9c626f 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift @@ -379,6 +379,10 @@ public struct PodcastChapter: Codable, Hashable, Sendable { self.url = url self.imageURL = imageURL } + + public var mediaChapter: MediaChapter { + MediaChapter(startTime: start, title: title, url: url, imageURL: imageURL) + } } /// 一集。`id` 同时也是播放时那首 `Song` 的 id(带 `podcast:` 前缀),进度、听完、下载都按它记。 diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift index 9f513a54e..3d062d367 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordNowPlayingPolicy.swift @@ -232,6 +232,9 @@ public struct SpokenWordContentsRow: Identifiable, Equatable, Sendable { public var state: State /// Drawn indented under its item. public var isNested: Bool + /// Optional external chapter link and artwork URL (Podlove / Podcasting 2.0). + public var url: URL? + public var imageURL: URL? public var id: String { switch kind { @@ -252,7 +255,9 @@ public struct SpokenWordContentsRow: Identifiable, Equatable, Sendable { title: String, duration: TimeInterval?, state: State, - isNested: Bool + isNested: Bool, + url: URL? = nil, + imageURL: URL? = nil ) { self.kind = kind self.itemID = itemID @@ -261,6 +266,8 @@ public struct SpokenWordContentsRow: Identifiable, Equatable, Sendable { self.duration = duration self.state = state self.isNested = isNested + self.url = url + self.imageURL = imageURL } } @@ -375,7 +382,9 @@ public enum SpokenWordContentsPolicy { title: chapter.title, duration: length, state: state, - isNested: nested + isNested: nested, + url: chapter.webURL, + imageURL: chapter.imageURL ) } } diff --git a/PrimuseKit/Tests/PrimuseKitTests/Playback/SleepTimerShakeExtendPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Playback/SleepTimerShakeExtendPolicyTests.swift new file mode 100644 index 000000000..db5d3634e --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Playback/SleepTimerShakeExtendPolicyTests.swift @@ -0,0 +1,27 @@ +import Foundation +import Testing +@testable import PrimuseKit + +@Suite("SleepTimerShakeExtendPolicy") +struct SleepTimerShakeExtendPolicyTests { + @Test func accelerationThresholdRejectsGentleMovementAndAcceptsShake() { + #expect(SleepTimerShakeExtendPolicy.exceedsThreshold(userAccelerationX: 0.3, y: 0.2, z: 0.1) == false) + #expect(SleepTimerShakeExtendPolicy.exceedsThreshold(userAccelerationX: 1.0, y: 1.0, z: 0.5) == false) + #expect(SleepTimerShakeExtendPolicy.exceedsThreshold(userAccelerationX: 1.4, y: 1.0, z: 0.2) == true) + #expect(SleepTimerShakeExtendPolicy.exceedsThreshold(userAccelerationX: .nan, y: 2.0, z: 0) == false) + } + + @Test func shouldExtendAppliesOnlyInsideClosingWindowAndRespectsCooldown() { + let t0 = Date(timeIntervalSince1970: 1_750_000_000) + + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: 600, lastExtendedAt: nil, now: t0) == false) + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: 0, lastExtendedAt: nil, now: t0) == false) + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: -5, lastExtendedAt: nil, now: t0) == false) + + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: 300, lastExtendedAt: nil, now: t0) == true) + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: 20, lastExtendedAt: nil, now: t0) == true) + + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: 25, lastExtendedAt: t0, now: t0.addingTimeInterval(2)) == false) + #expect(SleepTimerShakeExtendPolicy.shouldExtend(remaining: 25, lastExtendedAt: t0, now: t0.addingTimeInterval(5)) == true) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift index 2b800bedd..27edc49db 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastReliabilityTests.swift @@ -137,4 +137,32 @@ struct PodcastReliabilityTests { ) #expect(inProgress.map(\.id) == [olderInProgress.id]) } + + @Test func richChaptersPreserveArtworkAndSafeWebLinksThroughContentsPolicy() throws { + let artURL = try #require(URL(string: "https://cdn.example.com/ch1.jpg")) + let webURL = try #require(URL(string: "https://example.com/topic")) + let unsafeURL = try #require(URL(string: "javascript:alert(1)")) + + let ch1 = PodcastChapter(start: 0, title: "Intro", url: webURL, imageURL: artURL).mediaChapter + let ch2 = PodcastChapter(start: 120, title: "Unsafe Link", url: unsafeURL, imageURL: nil).mediaChapter + + #expect(ch1.webURL == webURL) + #expect(ch1.imageURL == artURL) + #expect(ch2.webURL == nil) + + let rows = SpokenWordContentsPolicy.rows( + book: nil, + currentItemID: "ep-1", + currentItemTitle: "Episode 1", + position: 10, + duration: 600, + chapters: [ch1, ch2], + currentChapterIndex: 0 + ) + #expect(rows.count == 2) + #expect(rows[0].url == webURL) + #expect(rows[0].imageURL == artURL) + #expect(rows[1].url == nil) + #expect(rows[1].imageURL == nil) + } } diff --git a/PrimuseTV/Model/TVStore.swift b/PrimuseTV/Model/TVStore.swift index 315cae8e6..b701332a4 100644 --- a/PrimuseTV/Model/TVStore.swift +++ b/PrimuseTV/Model/TVStore.swift @@ -8756,7 +8756,7 @@ extension TVStore { /// 换到一集时找它的章节:feed 里直接写的立刻有,JSON 和音频文件里的取回来再换上。 private func loadPodcastChapters(for episode: PodcastEpisode) { sourceChapterTask?.cancel() - sourceChapters = episode.chapters.map { MediaChapter(startTime: $0.start, title: $0.title) } + sourceChapters = episode.chapters.map(\.mediaChapter) guard sourceChapters.isEmpty else { return } let episodeID = episode.id sourceChapterTask = Task { @MainActor [weak self] in diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index 822fc007d..e6fb103cc 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -241,4 +241,28 @@ final class ListeningSpacesReliabilityTests: XCTestCase { player.audioEngine.applyPlaybackRate(2.75, isSpokenWord: false) XCTAssertEqual(player.audioEngine.playbackRate, 2.0, accuracy: 0.001) } + + func testSleepTimerShakeExtensionExtendsActiveTimerInClosingWindowAndRespectsCooldown() throws { + let player = AudioPlayerService() + let prevPref = player.sleepTimerShakeToExtend + cleanups.append { + player.cancelSleep() + player.sleepTimerShakeToExtend = prevPref + SleepTimerShakeExtender.shared.resetCooldownForTesting() + } + SleepTimerShakeExtender.shared.resetCooldownForTesting() + + let now = Date() + player.sleepTimerShakeToExtend = true + player.scheduleSleep(until: now.addingTimeInterval(20 * 60)) + XCTAssertFalse(player.handleSleepTimerShakeExtension(now: now)) + + player.scheduleSleep(until: now.addingTimeInterval(45)) + XCTAssertTrue(player.handleSleepTimerShakeExtension(now: now)) + let extendedEnd = try XCTUnwrap(player.sleepTimerEndDate) + XCTAssertGreaterThan(extendedEnd.timeIntervalSince(now), 14 * 60) + + player.scheduleSleep(until: now.addingTimeInterval(45)) + XCTAssertFalse(player.handleSleepTimerShakeExtension(now: now.addingTimeInterval(1))) + } } From 36521b84800352fd2209289dc68557b3089e0c67 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 17:31:43 -0500 Subject: [PATCH 05/15] =?UTF-8?q?=E6=89=93=E9=80=9A=E7=9B=B4=E6=92=AD?= =?UTF-8?q?=E7=94=B5=E5=8F=B0=E6=9C=AC=E5=9C=B0=20PCM=20=E8=A7=A3=E7=A0=81?= =?UTF-8?q?=E7=AE=A1=E7=BA=BF=EF=BC=8C=E5=B9=B6=E5=9C=A8=20iOS/macOS=20?= =?UTF-8?q?=E6=92=AD=E6=94=BE=E9=A1=B5=E6=8F=90=E4=BE=9B=E4=B8=80=E9=94=AE?= =?UTF-8?q?=E7=94=B5=E5=8F=B0=E4=BA=BA=E5=A3=B0=E5=A2=9E=E5=BC=BA=20refs?= =?UTF-8?q?=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Audio/AudioPlayerService+Radio.swift | 62 ++++++- .../Audio/AudioPlayerService+SmartSpeed.swift | 1 + .../Audio/AudioPlayerService+Varispeed.swift | 1 + Primuse/Services/Audio/FFmpegDecoderBridge.h | 13 ++ Primuse/Services/Audio/FFmpegDecoderBridge.m | 170 ++++++++++++++++++ .../Radio/RadioFLACAudioDecoder.swift | 35 +++- .../Radio/RadioLiveStreamSource.swift | 121 +++++++++++-- Primuse/Views/Mac/MacNowPlayingView.swift | 1 + Primuse/Views/NowPlaying/NowPlayingView.swift | 24 +-- .../SpokenWordAudioEffectsSheet.swift | 51 ++++++ .../Radio/RadioPlaybackPolicy.swift | 26 +++ .../Radio/RadioPlaybackPolicyTests.swift | 30 ++++ .../ListeningSpacesReliabilityTests.swift | 112 ++++++++++++ 13 files changed, 604 insertions(+), 43 deletions(-) diff --git a/Primuse/Services/Audio/AudioPlayerService+Radio.swift b/Primuse/Services/Audio/AudioPlayerService+Radio.swift index 9838a2132..5c3cc056e 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Radio.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Radio.swift @@ -88,9 +88,15 @@ extension AudioPlayerService { radioReconnectTask = nil radioReconnectAttempt = 0 radioResolvedStreamURL = url - let inferredFormat = RadioStreamFormat.inferred(from: url) - radioPrefersDecodedTransport = station.streamFormat == .flac || inferredFormat == .flac - radioDidAttemptDecodedFallback = radioPrefersDecodedTransport + let needsDecoded = RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: station.streamFormat, + resolvedURL: url, + voiceBoostActive: effectiveVoiceBoostActive(for: station.playbackSong), + equalizerEnabled: equalizerService.isEnabled, + outputAllowsEffects: playbackSettings.outputMode == .effects + ) + radioPrefersDecodedTransport = needsDecoded + radioDidAttemptDecodedFallback = needsDecoded radioDecodedFallbackNeedsValidation = false if let controller = castingController { @@ -253,7 +259,7 @@ extension AudioPlayerService { playID id: UUID ) { radioUsesDecodedTransport = true - let source = RadioLiveStreamSource(url: url) { [weak self] metadata in + let source = RadioLiveStreamSource(url: url, allowsAnyFormat: true) { [weak self] metadata in Task { @MainActor [weak self] in guard let self, self.playID == id, @@ -497,6 +503,15 @@ extension AudioPlayerService { radioSubtitleText = text return case .failed(let message, let shouldReconnect): + if radioUsesDecodedTransport, + radioPlaybackStartedAt == nil, + station.streamFormat != .flac, + radioResolvedStreamURL.map({ RadioStreamFormat.inferred(from: $0) != .flac }) == true { + radioPrefersDecodedTransport = false + radioDidAttemptDecodedFallback = true + startRadioTransport(station: station, playID: id) + return + } if !radioUsesDecodedTransport, !radioDidAttemptDecodedFallback, station.streamFormat == .automatic, @@ -673,6 +688,45 @@ extension AudioPlayerService { startRadioTransport(station: station, playID: id) } + /// 只有非 HLS 电台在音效模式下支持本地解码与人声增强。 + var canToggleCurrentRadioVoiceBoost: Bool { + guard isLiveRadio, let station = currentRadioStation else { return false } + let inferred = radioResolvedStreamURL.map { RadioStreamFormat.inferred(from: $0) } + return station.streamFormat != .hls && inferred != .hls && radioStreamFormat != .hls + } + + func toggleCurrentRadioVoiceBoost() { + guard let station = currentRadioStation else { return } + let scopeID = SpokenWordAudioEffectsPolicy.radioScopeID(forStationID: station.id) + let target = !currentEffectiveVoiceBoostEnabled + let stored = SpokenWordAudioEffectsPolicy.storedVoiceBoostOverride( + for: target, + global: playbackSettings.radioVoiceBoostEnabled + ) + SpokenWordAudioEffectsPreferences.shared.setVoiceBoostEnabled(stored, forScopeID: scopeID) + } + + func reconcileRadioTransportForAudioEffects() { + guard isLiveRadio, + let station = currentRadioStation, + let url = radioResolvedStreamURL, + let id = playID, + isPlaying || isLoading else { return } + applySpokenWordVoiceBoost() + let desiredDecoded = RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: station.streamFormat, + resolvedURL: url, + voiceBoostActive: effectiveVoiceBoostActive(for: station.playbackSong), + equalizerEnabled: equalizerService.isEnabled, + outputAllowsEffects: playbackSettings.outputMode == .effects + ) + guard desiredDecoded != radioUsesDecodedTransport else { return } + radioPrefersDecodedTransport = desiredDecoded + radioDidAttemptDecodedFallback = desiredDecoded + plog("📻 Switching live radio transport decoded=\(desiredDecoded) for audio effects") + startRadioTransport(station: station, playID: id) + } + private func resolveRadioStreamURL( for station: RadioStation, forceRefresh: Bool diff --git a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift index 9b0fa59be..e050d9139 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift @@ -319,6 +319,7 @@ extension AudioPlayerService { Task { @MainActor [weak self] in guard let self else { return } self.applySpokenWordVoiceBoost() + self.reconcileRadioTransportForAudioEffects() if self.currentEffectiveSmartSpeedLevel != activeSmartSpeedLevel, self.currentItemIsSpokenWord, !self.isCastingMode, diff --git a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift index 6f96c07ad..bb0cfc05d 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Varispeed.swift @@ -186,6 +186,7 @@ extension AudioPlayerService { Task { @MainActor [weak self] in guard let self else { return } self.reconcileAirPlaySampleBufferBackend() + self.reconcileRadioTransportForAudioEffects() self.observeAirPlayBufferedCompatibility() } } diff --git a/Primuse/Services/Audio/FFmpegDecoderBridge.h b/Primuse/Services/Audio/FFmpegDecoderBridge.h index 0fabeadb1..86c74e1f4 100644 --- a/Primuse/Services/Audio/FFmpegDecoderBridge.h +++ b/Primuse/Services/Audio/FFmpegDecoderBridge.h @@ -27,6 +27,13 @@ NS_ASSUME_NONNULL_BEGIN @property(nonatomic) BOOL hasPresentationTime; @end +/// Sequential input callback for non-seekable live HTTP radio streams. +typedef NSData * _Nullable (^FFmpegStreamReadBlock)( + NSInteger maximumLength, + BOOL *atEOF, + NSError **error +); + /// Objective-C ownership layer over FFmpeg. The bridge exposes only Foundation /// and AVFoundation values to Swift, keeping all AVFormat/AVCodec/Swr lifetime /// rules and pointer arithmetic on one serial decoder task. @@ -46,6 +53,12 @@ NS_ASSUME_NONNULL_BEGIN - (nullable instancetype)initWithURL:(NSURL *)url ioTimeout:(NSTimeInterval)ioTimeout error:(NSError **)error; +/// Opens a non-seekable live stream fed by `readBlock` (e.g. HTTP radio MP3/AAC/Ogg/Opus) +/// so live radio can reuse AudioEngine DSP (Voice Boost, EQ, compressor). +- (nullable instancetype)initWithStreamReadBlock:(FFmpegStreamReadBlock)readBlock + formatHint:(nullable NSString *)formatHint + ioTimeout:(NSTimeInterval)ioTimeout + error:(NSError **)error; - (nullable FFmpegAudioReadResult *)readNextBufferWithError:(NSError **)error; - (BOOL)seekToTime:(NSTimeInterval)time error:(NSError **)error; /// Interrupts an in-flight open/read/seek operation. Safe to call from a diff --git a/Primuse/Services/Audio/FFmpegDecoderBridge.m b/Primuse/Services/Audio/FFmpegDecoderBridge.m index 92b613679..9f8d627cc 100644 --- a/Primuse/Services/Audio/FFmpegDecoderBridge.m +++ b/Primuse/Services/Audio/FFmpegDecoderBridge.m @@ -442,6 +442,9 @@ @implementation FFmpegDecoderBridge { const AVInputFormat *_forcedInputFormat; BOOL _containsDTSSync; AVFormatContext *_formatContext; + AVIOContext *_customIOContext; + FFmpegStreamReadBlock _streamReadBlock; + NSError *_streamReadError; AVCodecContext *_codecContext; AVPacket *_packet; AVFrame *_frame; @@ -826,6 +829,163 @@ - (instancetype)initWithURL:(NSURL *)url return self; } +static int FFmpegStreamAVIORead(void *opaque, uint8_t *buf, int buf_size) { + FFmpegDecoderBridge *bridge = (__bridge FFmpegDecoderBridge *)opaque; + if (!bridge || buf_size <= 0) return AVERROR_EOF; + return [bridge readLiveStreamBytes:buf maxLength:buf_size]; +} + +- (int)readLiveStreamBytes:(uint8_t *)buffer maxLength:(int)maxLength { + if (atomic_load_explicit(&_interruptState.cancelled, memory_order_acquire)) { + return AVERROR_EXIT; + } + if (!_streamReadBlock) return AVERROR_EOF; + BOOL atEOF = NO; + NSError *readError = nil; + NSData *chunk = _streamReadBlock(maxLength, &atEOF, &readError); + if (atomic_load_explicit(&_interruptState.cancelled, memory_order_acquire)) { + return AVERROR_EXIT; + } + if (readError) { + _streamReadError = readError; + return AVERROR(EIO); + } + if (chunk.length > 0) { + NSUInteger count = MIN(chunk.length, (NSUInteger)maxLength); + memcpy(buffer, chunk.bytes, count); + return (int)count; + } + return atEOF ? AVERROR_EOF : AVERROR(EAGAIN); +} + +- (nullable instancetype)initWithStreamReadBlock:(FFmpegStreamReadBlock)readBlock + formatHint:(nullable NSString *)formatHint + ioTimeout:(NSTimeInterval)ioTimeout + error:(NSError **)error { + self = [super init]; + if (!self) return nil; + + NSTimeInterval boundedTimeout = isfinite(ioTimeout) + ? MIN(MAX(ioTimeout, 0.1), 3600.0) + : FFmpegDefaultIOTimeout; + _ioTimeoutNanos = (uint64_t)llround(boundedTimeout * 1000000000.0); + atomic_init(&_interruptState.cancelled, false); + atomic_init(&_interruptState.timedOut, false); + atomic_init(&_interruptState.deadlineNanos, 0); + _audioStreamIndex = -1; + _resamplerInputFormat = AV_SAMPLE_FMT_NONE; + av_channel_layout_uninit(&_resamplerInputLayout); + _streamReadBlock = [readBlock copy]; + + static const int kLiveIOBufferSize = 32768; + uint8_t *ioBuffer = av_malloc(kLiveIOBufferSize); + if (!ioBuffer) { + if (error) *error = FFmpegError(AVERROR(ENOMEM), @"Unable to allocate live stream buffer"); + [self closeDecoder]; + return nil; + } + _customIOContext = avio_alloc_context( + ioBuffer, + kLiveIOBufferSize, + 0, + (__bridge void *)self, + FFmpegStreamAVIORead, + NULL, + NULL + ); + if (!_customIOContext) { + av_free(ioBuffer); + if (error) *error = FFmpegError(AVERROR(ENOMEM), @"Unable to create live stream IO context"); + [self closeDecoder]; + return nil; + } + _customIOContext->seekable = 0; + + _formatContext = avformat_alloc_context(); + if (!_formatContext) { + if (error) *error = FFmpegError(AVERROR(ENOMEM), @"Unable to allocate input context"); + [self closeDecoder]; + return nil; + } + _formatContext->pb = _customIOContext; + _formatContext->flags |= AVFMT_FLAG_CUSTOM_IO; + _formatContext->probesize = 65536; + _formatContext->max_analyze_duration = (int64_t)(1.5 * AV_TIME_BASE); + _formatContext->interrupt_callback.callback = FFmpegInterruptCallback; + _formatContext->interrupt_callback.opaque = &_interruptState; + + const AVInputFormat *forcedFormat = formatHint.length > 0 + ? av_find_input_format(formatHint.UTF8String) + : NULL; + FFmpegBeginInterruptibleOperation(&_interruptState, _ioTimeoutNanos); + int result = avformat_open_input(&_formatContext, "", forcedFormat, NULL); + if (result < 0) { + if (error) *error = _streamReadError ?: FFmpegOperationError(result, @"Opening live radio stream", &_interruptState); + [self closeDecoder]; + return nil; + } + FFmpegBeginInterruptibleOperation(&_interruptState, _ioTimeoutNanos); + result = avformat_find_stream_info(_formatContext, NULL); + if (result < 0) { + if (error) *error = _streamReadError ?: FFmpegOperationError(result, @"Reading live radio stream info", &_interruptState); + [self closeDecoder]; + return nil; + } + const AVCodec *codec = NULL; + result = av_find_best_stream(_formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); + if (result < 0 || !codec) { + if (error) *error = FFmpegError(result < 0 ? result : AVERROR_DECODER_NOT_FOUND, @"No supported radio audio stream"); + [self closeDecoder]; + return nil; + } + _audioStreamIndex = result; + AVStream *stream = _formatContext->streams[_audioStreamIndex]; + _codecContext = avcodec_alloc_context3(codec); + if (!_codecContext) { + if (error) *error = FFmpegError(AVERROR(ENOMEM), @"Unable to allocate radio decoder"); + [self closeDecoder]; + return nil; + } + result = avcodec_parameters_to_context(_codecContext, stream->codecpar); + if (result < 0) { + if (error) *error = FFmpegError(result, @"Unable to configure radio decoder"); + [self closeDecoder]; + return nil; + } + _codecContext->request_sample_fmt = AV_SAMPLE_FMT_FLTP; + result = avcodec_open2(_codecContext, codec, NULL); + if (result < 0) { + if (error) *error = FFmpegError(result, @"Unable to start radio decoder"); + [self closeDecoder]; + return nil; + } + _packet = av_packet_alloc(); + _frame = av_frame_alloc(); + if (!_packet || !_frame) { + if (error) *error = FFmpegError(AVERROR(ENOMEM), @"Unable to allocate radio decode buffers"); + [self closeDecoder]; + return nil; + } + + _fileInfo = [[FFmpegAudioFileInfo alloc] init]; + _fileInfo.sampleRate = _codecContext->sample_rate > 0 + ? _codecContext->sample_rate : stream->codecpar->sample_rate; + _fileInfo.channelCount = _codecContext->ch_layout.nb_channels > 0 + ? _codecContext->ch_layout.nb_channels : stream->codecpar->ch_layout.nb_channels; + int64_t bitRate = _codecContext->bit_rate > 0 + ? _codecContext->bit_rate : stream->codecpar->bit_rate; + if (bitRate <= 0) bitRate = _formatContext->bit_rate; + _fileInfo.bitRateKbps = bitRate > 0 ? (NSInteger)(bitRate / 1000) : 0; + const AVCodecDescriptor *descriptor = avcodec_descriptor_get(_codecContext->codec_id); + const char *codecName = descriptor ? descriptor->name : codec->name; + _fileInfo.codecName = codecName ? [NSString stringWithUTF8String:codecName] : @"unknown"; + const char *formatName = _formatContext->iformat ? _formatContext->iformat->name : NULL; + _fileInfo.formatName = formatName ? [NSString stringWithUTF8String:formatName] : @"unknown"; + _fileInfo.lossless = descriptor && (descriptor->props & AV_CODEC_PROP_LOSSLESS); + _fileInfo.DSD = NO; + return self; +} + - (void)dealloc { [self closeDecoder]; } - (FFmpegAudioFileInfo *)fileInfo { return _fileInfo; } @@ -1204,6 +1364,10 @@ - (BOOL)seekByScanningPacketsToTime:(NSTimeInterval)time error:(NSError **)error } - (BOOL)seekToTime:(NSTimeInterval)time error:(NSError **)error { + if (_customIOContext) { + if (error) *error = FFmpegError(AVERROR(ESPIPE), @"Live stream does not support seeking"); + return NO; + } if (!_formatContext || _audioStreamIndex < 0 || !isfinite(time)) return NO; AVStream *stream = _formatContext->streams[_audioStreamIndex]; if (!FFmpegFormatRequiresPacketScanSeek(_formatContext->iformat, @@ -1246,6 +1410,12 @@ - (void)closeDecoder { av_packet_free(&_packet); avcodec_free_context(&_codecContext); avformat_close_input(&_formatContext); + if (_customIOContext) { + av_freep(&_customIOContext->buffer); + avio_context_free(&_customIOContext); + } + _streamReadBlock = nil; + _streamReadError = nil; } @end diff --git a/Primuse/Services/Radio/RadioFLACAudioDecoder.swift b/Primuse/Services/Radio/RadioFLACAudioDecoder.swift index 0819b09ee..e89e093b8 100644 --- a/Primuse/Services/Radio/RadioFLACAudioDecoder.swift +++ b/Primuse/Services/Radio/RadioFLACAudioDecoder.swift @@ -38,21 +38,38 @@ final class RadioFLACAudioDecoder: Sendable { RadioFLACBufferStream(capacity: Self.bufferingLimit) { continuation in let task = Task.detached(priority: .userInitiated) { do { - let bridge = try RadioFLACDecoderBridge( - oggContainer: prepared.container == .oggFLAC - ) { maximumLength, atEOF, errorOut in - source.read( - maximumLength: maximumLength, - atEOF: atEOF, - errorOut: errorOut + let readNext: () throws -> AVAudioPCMBuffer? + switch prepared.container { + case .flac, .oggFLAC: + let bridge = try RadioFLACDecoderBridge( + oggContainer: prepared.container == .oggFLAC + ) { maximumLength, atEOF, errorOut in + source.read( + maximumLength: maximumLength, + atEOF: atEOF, + errorOut: errorOut + ) + } + readNext = { try bridge.readNextBuffer().buffer } + case .mp3, .aac, .oggAudio, .genericFFmpeg: + let bridge = try FFmpegDecoderBridge( + streamRead: { maximumLength, atEOF, errorOut in + source.read( + maximumLength: maximumLength, + atEOF: atEOF, + errorOut: errorOut + ) + }, + formatHint: prepared.container.ffmpegFormatHint, + ioTimeout: 15 ) + readNext = { try bridge.readNextBuffer().buffer } } var converter: AVAudioConverter? var converterSourceFormat: AVAudioFormat? while !Task.isCancelled { - let result = try bridge.readNextBuffer() - guard let sourceBuffer = result.buffer else { break } + guard let sourceBuffer = try readNext() else { break } guard sourceBuffer.frameLength > 0 else { continue } let outputBuffer: AVAudioPCMBuffer diff --git a/Primuse/Services/Radio/RadioLiveStreamSource.swift b/Primuse/Services/Radio/RadioLiveStreamSource.swift index 14aad8211..3bd54e4bd 100644 --- a/Primuse/Services/Radio/RadioLiveStreamSource.swift +++ b/Primuse/Services/Radio/RadioLiveStreamSource.swift @@ -6,9 +6,31 @@ import PrimuseKit /// requiring a content length or seek support. ICY metadata is removed before /// audio bytes enter the decoder. final class RadioLiveStreamSource: NSObject, URLSessionDataDelegate, @unchecked Sendable { - enum Container: Sendable { + enum Container: Sendable, Equatable { case flac case oggFLAC + case mp3 + case aac + case oggAudio + case genericFFmpeg + + var ffmpegFormatHint: String? { + switch self { + case .mp3: return "mp3" + case .aac: return "aac" + case .oggAudio: return "ogg" + case .flac, .oggFLAC, .genericFFmpeg: return nil + } + } + + var radioStreamFormat: RadioStreamFormat { + switch self { + case .flac, .oggFLAC: return .flac + case .mp3: return .mp3 + case .aac: return .aac + case .oggAudio, .genericFFmpeg: return .automatic + } + } } struct Prepared: @unchecked Sendable { @@ -50,6 +72,7 @@ final class RadioLiveStreamSource: NSObject, URLSessionDataDelegate, @unchecked private let url: URL private let headers: [String: String] + private let allowsAnyFormat: Bool private let metadataHandler: MetadataHandler? private let condition = NSCondition() @@ -80,10 +103,12 @@ final class RadioLiveStreamSource: NSObject, URLSessionDataDelegate, @unchecked init( url: URL, headers: [String: String] = [:], + allowsAnyFormat: Bool = false, metadataHandler: MetadataHandler? = nil ) { self.url = url self.headers = headers + self.allowsAnyFormat = allowsAnyFormat self.metadataHandler = metadataHandler super.init() } @@ -453,17 +478,24 @@ final class RadioLiveStreamSource: NSObject, URLSessionDataDelegate, @unchecked if sniffData.count < Self.maximumSniffBytes { sniffData.append(data.prefix(Self.maximumSniffBytes - sniffData.count)) } - if preparationResult == nil, - let container = Self.sniffContainer(from: sniffData) { - let prepared = Prepared( - container: container, - format: .flac, - bitRate: bitRate - ) - completion = setPreparationResultLocked(.success(prepared)) - } else if preparationResult == nil, - sniffData.count >= Self.maximumSniffBytes { - completion = setPreparationResultLocked(.failure(StreamError.unsupportedFormat)) + if preparationResult == nil { + if Self.looksLikeHLSPlaylist(sniffData, contentType: contentType) { + completion = setPreparationResultLocked(.failure(StreamError.unsupportedFormat)) + } else if let container = Self.sniffContainer( + from: sniffData, + contentType: contentType, + url: url, + allowsAnyFormat: allowsAnyFormat + ) { + let prepared = Prepared( + container: container, + format: container.radioStreamFormat, + bitRate: bitRate + ) + completion = setPreparationResultLocked(.success(prepared)) + } else if sniffData.count >= Self.maximumSniffBytes { + completion = setPreparationResultLocked(.failure(StreamError.unsupportedFormat)) + } } condition.broadcast() condition.unlock() @@ -566,16 +598,69 @@ final class RadioLiveStreamSource: NSObject, URLSessionDataDelegate, @unchecked completion.0.resume(with: completion.1) } - private static func sniffContainer(from data: Data) -> Container? { + private static func looksLikeHLSPlaylist(_ data: Data, contentType: String?) -> Bool { + let mime = contentType?.lowercased() ?? "" + if mime.contains("mpegurl") || mime.contains("x-mpegurl") { + return true + } + if data.count >= 7, + let prefix = String(data: data.prefix(16), encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines), + prefix.hasPrefix("#EXTM3U") { + return true + } + return false + } + + private static func sniffContainer( + from data: Data, + contentType: String?, + url: URL, + allowsAnyFormat: Bool + ) -> Container? { if data.starts(with: Data("fLaC".utf8)) { return .flac } - guard data.starts(with: Data("OggS".utf8)) else { return nil } - if data.range(of: Data([0x7f, 0x46, 0x4c, 0x41, 0x43])) != nil - || data.range(of: Data("fLaC".utf8)) != nil { - return .oggFLAC + if data.starts(with: Data("OggS".utf8)) { + if data.range(of: Data([0x7f, 0x46, 0x4c, 0x41, 0x43])) != nil + || data.range(of: Data("fLaC".utf8)) != nil { + return .oggFLAC + } + if allowsAnyFormat, data.count >= 64 { + return .oggAudio + } + return nil + } + guard allowsAnyFormat else { return nil } + let mime = contentType?.lowercased() ?? "" + if mime.contains("aac") || mime.contains("aacp") { + return .aac + } + if mime.contains("mpeg") || mime.contains("mp3") { + return .mp3 + } + if mime.contains("ogg") || mime.contains("opus") { + return .oggAudio + } + if data.starts(with: Data("ID3".utf8)) { + return .mp3 + } + if data.count >= 4 { + let b0 = data[data.startIndex] + let b1 = data[data.index(after: data.startIndex)] + if b0 == 0xFF, (b1 & 0xF6) == 0xF0 { + return .aac + } + if b0 == 0xFF, (b1 & 0xE0) == 0xE0 { + return .mp3 + } + } + switch RadioStreamFormat.inferred(from: url, mimeType: contentType) { + case .aac: return .aac + case .mp3: return .mp3 + case .flac, .hls, .automatic: break } - return nil + return data.count >= 4_096 ? .genericFFmpeg : nil } private static func parseBitRate(_ value: String?) -> Int? { diff --git a/Primuse/Views/Mac/MacNowPlayingView.swift b/Primuse/Views/Mac/MacNowPlayingView.swift index 86219c420..beae90d05 100644 --- a/Primuse/Views/Mac/MacNowPlayingView.swift +++ b/Primuse/Views/Mac/MacNowPlayingView.swift @@ -787,6 +787,7 @@ struct MacNowPlayingView: View { .frame(minWidth: 420, minHeight: 540) } } + RadioVoiceBoostToggleButton(style: .circle(primary: playerPrimaryColor, onAccent: theme.onAccent, accent: theme.accentColor)) // 电台没有「更多」菜单, 睡眠定时直接放在这排。 Button { showsRadioSleepTimer.toggle() } label: { circleIcon(player.isSleepTimerActive ? "moon.zzz.fill" : "moon.zzz", diff --git a/Primuse/Views/NowPlaying/NowPlayingView.swift b/Primuse/Views/NowPlaying/NowPlayingView.swift index ca2479fa8..f9a0d3e87 100644 --- a/Primuse/Views/NowPlaying/NowPlayingView.swift +++ b/Primuse/Views/NowPlaying/NowPlayingView.swift @@ -6076,19 +6076,19 @@ struct NowPlayingView: View { .lineLimit(2) .multilineTextAlignment(.center) - HStack(spacing: 7) { - Circle() - .fill(.red) - .frame(width: 8, height: 8) - Text("live_badge") - .font(.caption.weight(.bold)) - LiveRadioElapsedTime() + HStack(spacing: 8) { + HStack(spacing: 7) { + Circle().fill(.red).frame(width: 8, height: 8) + Text("live_badge").font(.caption.weight(.bold)) + LiveRadioElapsedTime() + } + .foregroundStyle(appearance.primary) + .padding(.horizontal, 12) + .frame(height: 30) + .background(.ultraThinMaterial, in: Capsule()) + .accessibilityLabel(Text("radio_live")) + RadioVoiceBoostToggleButton(style: .capsule(primary: appearance.primary, accent: themedControlAccent)) } - .foregroundStyle(appearance.primary) - .padding(.horizontal, 12) - .frame(height: 30) - .background(.ultraThinMaterial, in: Capsule()) - .accessibilityLabel(Text("radio_live")) } .padding(.horizontal, 32) // 台标先分高度,文字按自己的完整高度留位,不被挤成一行。 diff --git a/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift b/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift index f54e87897..a16e7b60b 100644 --- a/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift +++ b/Primuse/Views/NowPlaying/SpokenWordAudioEffectsSheet.swift @@ -370,3 +370,54 @@ struct SpokenWordAudioEffectsSheet: View { SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: scopeID) } } + +/// 直播电台播放页快捷人声增强键(iOS 与 macOS 共用,按电台保存覆盖并复用统一 Voice Boost DSP)。 +struct RadioVoiceBoostToggleButton: View { + enum Style { + case capsule(primary: Color, accent: Color) + case circle(primary: Color, onAccent: Color, accent: Color) + } + + let style: Style + @Environment(AudioPlayerService.self) private var player + + var body: some View { + if player.canToggleCurrentRadioVoiceBoost { + let active = player.currentEffectiveVoiceBoostEnabled + Button { + player.toggleCurrentRadioVoiceBoost() + } label: { + switch style { + case let .capsule(primary, accent): + HStack(spacing: 5) { + Image(systemName: "waveform") + .font(.caption.weight(.semibold)) + Text("spoken_word_voice_boost") + .font(.caption.weight(.semibold)) + .lineLimit(1) + } + .foregroundStyle(active ? Color.white : primary) + .padding(.horizontal, 11) + .frame(height: 30) + .background(active ? AnyShapeStyle(accent) : AnyShapeStyle(.ultraThinMaterial), in: Capsule()) + case let .circle(primary, onAccent, accent): + Image(systemName: "waveform") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(active ? onAccent : primary) + .frame(width: 34, height: 34) + .background(active ? accent.opacity(0.9) : Color.clear, in: Circle()) + .contentShape(Circle()) + } + } + .buttonStyle(.plain) + #if os(iOS) + .sensoryFeedback(.selection, trigger: active) + #else + .pmGlassControl(Circle()) + .help(Text("radio_voice_boost")) + #endif + .accessibilityLabel(Text("radio_voice_boost")) + .accessibilityAddTraits(active ? .isSelected : []) + } + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift index e18daaae7..78e0e6fb2 100644 --- a/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift @@ -82,3 +82,29 @@ public enum RadioLiveMetadataPolicy { : nil } } + +/// 直播电台链路路由策略:决定走本地 PCM 解码(经 AudioEngine 复用语音增强与均衡器)还是原生 AVPlayer。 +/// HLS 清单始终走 AVPlayer;FLAC / Ogg / Opus 始终走本地解码;普通 MP3/AAC HTTP 流在开启 +/// 电台人声增强或均衡器(且处于音效模式)时切入本地解码,其余时候沿用低功耗 AVPlayer。 +public enum RadioTransportRoutingPolicy { + public static func prefersDecodedTransport( + stationFormat: RadioStreamFormat, + resolvedURL: URL, + voiceBoostActive: Bool, + equalizerEnabled: Bool, + outputAllowsEffects: Bool + ) -> Bool { + let inferred = RadioStreamFormat.inferred(from: resolvedURL) + if stationFormat == .hls || inferred == .hls { + return false + } + if stationFormat == .flac || inferred == .flac { + return true + } + let ext = resolvedURL.pathExtension.lowercased() + if ext == "ogg" || ext == "oga" || ext == "opus" { + return true + } + return outputAllowsEffects && (voiceBoostActive || equalizerEnabled) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift index ff9c90251..5f92af4e6 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift @@ -104,4 +104,34 @@ struct RadioPlaybackPolicyTests { ) == "https://img.example.com/a.jpg" ) } + + @Test func transportRoutingRoutesNonHLSToDecodedPipelineWhenDSPActiveOrNativeUnsupported() throws { + let mp3URL = try #require(URL(string: "https://radio.example.com/news.mp3")) + let aacURL = try #require(URL(string: "https://radio.example.com/talk.aac")) + let flacURL = try #require(URL(string: "https://radio.example.com/hifi.flac")) + let oggURL = try #require(URL(string: "https://radio.example.com/stream.ogg")) + let hlsURL = try #require(URL(string: "https://radio.example.com/live.m3u8")) + + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .mp3, resolvedURL: mp3URL, voiceBoostActive: false, equalizerEnabled: false, outputAllowsEffects: true + ) == false) + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .mp3, resolvedURL: mp3URL, voiceBoostActive: true, equalizerEnabled: false, outputAllowsEffects: true + ) == true) + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .aac, resolvedURL: aacURL, voiceBoostActive: false, equalizerEnabled: true, outputAllowsEffects: true + ) == true) + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .mp3, resolvedURL: mp3URL, voiceBoostActive: true, equalizerEnabled: true, outputAllowsEffects: false + ) == false) + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .flac, resolvedURL: flacURL, voiceBoostActive: false, equalizerEnabled: false, outputAllowsEffects: false + ) == true) + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .automatic, resolvedURL: oggURL, voiceBoostActive: false, equalizerEnabled: false, outputAllowsEffects: false + ) == true) + #expect(RadioTransportRoutingPolicy.prefersDecodedTransport( + stationFormat: .hls, resolvedURL: hlsURL, voiceBoostActive: true, equalizerEnabled: true, outputAllowsEffects: true + ) == false) + } } diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index e6fb103cc..ea6cb19d7 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -1,3 +1,4 @@ +import AVFoundation import Foundation import PrimuseKit import XCTest @@ -265,4 +266,115 @@ final class ListeningSpacesReliabilityTests: XCTestCase { player.scheduleSleep(until: now.addingTimeInterval(45)) XCTAssertFalse(player.handleSleepTimerShakeExtension(now: now.addingTimeInterval(1))) } + + func testToggleCurrentRadioVoiceBoostStoresPerStationOverrideAndRespectsHLS() throws { + let player = AudioPlayerService() + let prevRadioVoice = player.playbackSettings.radioVoiceBoostEnabled + cleanups.append { player.playbackSettings.radioVoiceBoostEnabled = prevRadioVoice } + player.playbackSettings.radioVoiceBoostEnabled = false + + let talkStation = RadioStation( + id: "toggle-talk-\(UUID().uuidString)", + name: "Talk FM", + streamURL: "https://radio.example.com/talk.aac", + streamFormat: .aac + ) + let scopeID = SpokenWordAudioEffectsPolicy.radioScopeID(forStationID: talkStation.id) + cleanups.append { SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: scopeID) } + + player.playbackKind = .liveRadio + player.currentRadioStation = talkStation + player.currentSong = talkStation.playbackSong + player.radioStreamFormat = .aac + player.radioResolvedStreamURL = URL(string: talkStation.streamURL) + + XCTAssertTrue(player.canToggleCurrentRadioVoiceBoost) + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + + player.toggleCurrentRadioVoiceBoost() + XCTAssertTrue(player.currentEffectiveVoiceBoostEnabled) + + player.toggleCurrentRadioVoiceBoost() + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + XCTAssertFalse(SpokenWordAudioEffectsPreferences.shared.hasOverride(forScopeID: scopeID)) + + let hlsStation = RadioStation( + id: "hls-\(UUID().uuidString)", + name: "HLS FM", + streamURL: "https://radio.example.com/live.m3u8", + streamFormat: .hls + ) + player.currentRadioStation = hlsStation + player.radioStreamFormat = .hls + player.radioResolvedStreamURL = URL(string: hlsStation.streamURL) + XCTAssertFalse(player.canToggleCurrentRadioVoiceBoost) + } + + func testFFmpegStreamDecoderDecodesChunkedAudioAndRejectsSeeking() throws { + let sampleRate = 44_100 + let channels = 2 + let frameCount = 4_410 + let pcmByteCount = frameCount * channels * MemoryLayout.size + var wav = Data(capacity: 44 + pcmByteCount) + func appendLE16(_ value: UInt16) { + var le = value.littleEndian + withUnsafeBytes(of: &le) { wav.append(contentsOf: $0) } + } + func appendLE32(_ value: UInt32) { + var le = value.littleEndian + withUnsafeBytes(of: &le) { wav.append(contentsOf: $0) } + } + wav.append(contentsOf: "RIFF".utf8) + appendLE32(UInt32(36 + pcmByteCount)) + wav.append(contentsOf: "WAVEfmt ".utf8) + appendLE32(16) + appendLE16(1) + appendLE16(UInt16(channels)) + appendLE32(UInt32(sampleRate)) + appendLE32(UInt32(sampleRate * channels * 2)) + appendLE16(UInt16(channels * 2)) + appendLE16(16) + wav.append(contentsOf: "data".utf8) + appendLE32(UInt32(pcmByteCount)) + for frame in 0..= wav.count { + atEOF.pointee = true + return Data() + } + let step = min(min(maximumLength, 1024), wav.count - cursor) + let slice = wav[cursor..<(cursor + step)] + cursor += step + atEOF.pointee = false + return Data(slice) + }, + formatHint: nil, + ioTimeout: 5 + ) + + XCTAssertEqual(bridge.fileInfo.sampleRate, Double(sampleRate)) + XCTAssertEqual(bridge.fileInfo.channelCount, channels) + XCTAssertThrowsError(try bridge.seek(toTime: 0.05)) + + var decodedFrames: AVAudioFrameCount = 0 + var peakAmplitude: Float = 0 + while let buffer = try bridge.readNextBuffer().buffer { + decodedFrames += buffer.frameLength + if let channelData = buffer.floatChannelData { + for i in 0.. Date: Tue, 1 Dec 2026 18:00:36 -0500 Subject: [PATCH 06/15] =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=8A=82=E7=9B=AE?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=E6=97=B6=E9=97=B4=E6=88=B3=E5=90=88=E6=88=90?= =?UTF-8?q?=E7=AB=A0=E8=8A=82=E3=80=81=E7=9D=A1=E7=9C=A0=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E9=86=92=E6=9D=A5=E5=9B=9E=E9=80=80=E3=80=81=E9=94=81=E5=B1=8F?= =?UTF-8?q?=E7=AB=A0=E8=8A=82=E8=BF=9B=E5=BA=A6=E4=B8=8E=E6=92=AD=E5=AE=A2?= =?UTF-8?q?=E9=98=9F=E5=88=97=E6=8B=96=E6=8B=BD=E7=AE=A1=E7=90=86=20refs?= =?UTF-8?q?=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 4 + .../AudioPlayerService+NowPlayingInfo.swift | 16 ++- .../Audio/AudioPlayerService+Podcast.swift | 2 + .../AudioPlayerService+RemoteCommands.swift | 6 + .../Audio/AudioPlayerService+SpokenWord.swift | 20 ++- Primuse/Services/Podcast/PodcastNetwork.swift | 31 +++-- .../NowPlaying/PodcastPlayerComponents.swift | 128 +++++++++++++++--- .../Playback/QueueUpcomingReorderPolicy.swift | 38 ++++++ .../PrimuseKit/Podcast/PodcastShowNotes.swift | 116 ++++++++++++++++ .../SpokenWord/SpokenWordContentPolicy.swift | 56 -------- .../SpokenWordSmartRewindPolicy.swift | 68 ++++++++++ .../Playback/QueueRowIdentityTests.swift | 42 ++++++ .../Podcast/PodcastShowNotesTests.swift | 47 +++++++ .../SpokenWordContentPolicyTests.swift | 20 +++ .../ListeningSpacesReliabilityTests.swift | 55 ++++++++ 15 files changed, 560 insertions(+), 89 deletions(-) create mode 100644 PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartRewindPolicy.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index 1e63b56ca..f176e4805 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -2329,6 +2329,7 @@ AD1A43CD8A35FB28FAB7E781 /* SynologyAudioStationErrorText.swift in Sources */ = {isa = PBXBuildFile; fileRef = F60CEED3AD7295532D6B1833 /* SynologyAudioStationErrorText.swift */; }; AD1C6CF075A71F4A51ECF842 /* CloudDeviceAuthService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7636930F6BD3D872DEA692AF /* CloudDeviceAuthService.swift */; }; AD2E0BAD17702DAEDC49EE31 /* ServerCatalogMetadataInspectionPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2650E897644F3365C533BBA4 /* ServerCatalogMetadataInspectionPolicy.swift */; }; + AD475F09F1B75490AECBF0E1 /* SpokenWordSmartRewindPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0E9911D80216D0A87EDA876 /* SpokenWordSmartRewindPolicy.swift */; }; AD4E66E2DCDDA13E782457A4 /* AppleMusicSystemQueuePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E97B1EB2BFFD617A5FD6308 /* AppleMusicSystemQueuePolicy.swift */; }; AD5D327D76859376F6EFC34E /* HTTPChunkedBodyDecodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C271778C5DE77B04EB337C67 /* HTTPChunkedBodyDecodingTests.swift */; }; AD675AE2312AF7C41C011A20 /* SemanticAlbumResultCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69918F7E72B36379DC66865F /* SemanticAlbumResultCard.swift */; }; @@ -5967,6 +5968,7 @@ F00E9F2C7113E6B319AEDB10 /* EQRealtimeProcessor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EQRealtimeProcessor.swift; sourceTree = ""; }; F032004B023B2AE64349E763 /* TVArtistArtworkView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TVArtistArtworkView.swift; sourceTree = ""; }; F032CBAB9B9A24AA008CB772 /* PeerScanSeedStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerScanSeedStore.swift; sourceTree = ""; }; + F0E9911D80216D0A87EDA876 /* SpokenWordSmartRewindPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordSmartRewindPolicy.swift; sourceTree = ""; }; F0F0C6E95AB8E336F7DB9EB4 /* PinnedWidgetLinkHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PinnedWidgetLinkHandler.swift; sourceTree = ""; }; F10291362C83153950BFA661 /* Artist.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Artist.swift; sourceTree = ""; }; F11F8874E486A4FC4E629861 /* LibraryDisplayConfigurationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryDisplayConfigurationTests.swift; sourceTree = ""; }; @@ -7602,6 +7604,7 @@ 13618BBC1AAAA6A08A1BC763 /* SpokenWordPartTitleLabel.swift */, DACADA741E90A21335AE63D1 /* SpokenWordShelfStartupSnapshot.swift */, F239A5B925B9F1E8568F8995 /* SpokenWordSleepSelection.swift */, + F0E9911D80216D0A87EDA876 /* SpokenWordSmartRewindPolicy.swift */, 3083CF554D03CED591BA67DD /* SpokenWordSmartSpeed.swift */, C93CDA3A6ADEDD5824F772B0 /* SpokenWordSyncPolicy.swift */, FD259BE505F6EC50343F66EF /* SpokenWordVoiceBoostPolicy.swift */, @@ -11095,6 +11098,7 @@ 02EF505F84B9837C24BE6AB7 /* SpokenWordPartTitleLabel.swift in Sources */, 847C73CBCB90E184FD0DD8B2 /* SpokenWordShelfStartupSnapshot.swift in Sources */, FC0AE9797AAAD098FD564643 /* SpokenWordSleepSelection.swift in Sources */, + AD475F09F1B75490AECBF0E1 /* SpokenWordSmartRewindPolicy.swift in Sources */, 37CFE328598B6AC26BF1A444 /* SpokenWordSmartSpeed.swift in Sources */, 51BDFFC177BFEE8FEE1206A6 /* SpokenWordSyncPolicy.swift in Sources */, 938624305BD18171BF55FF38 /* SpokenWordVideoPolicy.swift in Sources */, diff --git a/Primuse/Services/Audio/AudioPlayerService+NowPlayingInfo.swift b/Primuse/Services/Audio/AudioPlayerService+NowPlayingInfo.swift index e57e8f561..2339e7c48 100644 --- a/Primuse/Services/Audio/AudioPlayerService+NowPlayingInfo.swift +++ b/Primuse/Services/Audio/AudioPlayerService+NowPlayingInfo.swift @@ -69,6 +69,8 @@ extension AudioPlayerService { let isMusicVideo: Bool let queueCount: Int let queueIndex: Int + let chapterCount: Int + let chapterIndex: Int? } func updateNowPlayingInfo( @@ -176,6 +178,12 @@ extension AudioPlayerService { info[MPNowPlayingInfoPropertyPlaybackQueueCount] = queueEntries.count info[MPNowPlayingInfoPropertyPlaybackQueueIndex] = currentIndex } + if !isLiveRadio, !spokenWordChapters.isEmpty { + info[MPNowPlayingInfoPropertyChapterCount] = spokenWordChapters.count + if let chapterIndex = currentChapterIndex, spokenWordChapters.indices.contains(chapterIndex) { + info[MPNowPlayingInfoPropertyChapterNumber] = chapterIndex + } + } // Publish asynchronously resolved artwork together with the complete // current-track snapshot. Ordinary progress/state refreshes may reuse @@ -274,6 +282,10 @@ extension AudioPlayerService { private func currentNowPlayingInfoSnapshotKey(publishedDuration: TimeInterval? = nil) -> NowPlayingInfoSnapshotKey? { guard let songID = currentSong?.id else { return nil } let hasQueuePosition = !isLiveRadio && queueEntries.indices.contains(currentIndex) + let chapterCount = isLiveRadio ? 0 : spokenWordChapters.count + let chapterIndex = (!isLiveRadio && currentChapterIndex.map { spokenWordChapters.indices.contains($0) } == true) + ? currentChapterIndex + : nil return NowPlayingInfoSnapshotKey( songID: songID, artworkRevision: nowPlayingArtworkRevision, @@ -282,7 +294,9 @@ extension AudioPlayerService { isLiveStream: isLiveRadio, isMusicVideo: isMusicVideoPlaybackActive, queueCount: hasQueuePosition ? queueEntries.count : 0, - queueIndex: hasQueuePosition ? currentIndex : -1 + queueIndex: hasQueuePosition ? currentIndex : -1, + chapterCount: chapterCount, + chapterIndex: chapterIndex ) } diff --git a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift index 361020015..a26f69be5 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift @@ -299,6 +299,8 @@ final class PodcastPlaybackState { /// 这一条刚标成听完、正在换下一条(或续播时换去了别的设备听到的那条):换走时别再给它记位置 /// (记位置会把听完重新打开,或把它变成最新的一条)。换到别的条目时清掉。 var positionSaveSuppressedEpisodeID: String? + /// 最近一次因睡眠定时到点而暂停的有声条目 ID:下次继续播放时多回退一段,补回淡出入睡前的片段。 + var sleepTimerPausedSongID: String? } /// Reads episode metadata saved by older versions before it was included in diff --git a/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift b/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift index e6be2f740..f013f9ff9 100644 --- a/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift +++ b/Primuse/Services/Audio/AudioPlayerService+RemoteCommands.swift @@ -388,6 +388,9 @@ extension AudioPlayerService { SleepTimerShakeExtender.shared.stop() return } + if self.currentItemIsSpokenWord { + PodcastPlaybackState.shared.sleepTimerPausedSongID = self.currentSong?.id + } self.pause() self.sleepTimerEndDate = nil self.sleepTimerStartDate = nil @@ -410,6 +413,9 @@ extension AudioPlayerService { return } } + if self.currentItemIsSpokenWord { + PodcastPlaybackState.shared.sleepTimerPausedSongID = self.currentSong?.id + } self.pause() self.setPlaybackVolume(restoreVolume, persist: false) self.sleepTimerEndDate = nil diff --git a/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift b/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift index 50f461787..a56c0e137 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift @@ -42,6 +42,7 @@ extension AudioPlayerService { let playbackState = PodcastPlaybackState.shared if playbackState.outroHandledEpisodeID != song?.id { playbackState.outroHandledEpisodeID = nil } if playbackState.positionSaveSuppressedEpisodeID != song?.id { playbackState.positionSaveSuppressedEpisodeID = nil } + if playbackState.sleepTimerPausedSongID != song?.id { playbackState.sleepTimerPausedSongID = nil } let wasSpokenWord = currentItemIsSpokenWord smartSpeedSavingsMeter.reset() @@ -706,6 +707,7 @@ extension AudioPlayerService { if isPlaying { spokenWordStoppedAt = nil spokenWordRepositionedWhilePaused = false + PodcastPlaybackState.shared.sleepTimerPausedSongID = nil } else if currentItemIsSpokenWord, let songID = currentSong?.id { spokenWordStoppedAt = (songID, Date()) } @@ -717,6 +719,7 @@ extension AudioPlayerService { guard !isRecovery, !isPlaying, currentItemIsSpokenWord, time.isFinite, abs(time - currentTime) > 0.5 else { return } spokenWordRepositionedWhilePaused = true + PodcastPlaybackState.shared.sleepTimerPausedSongID = nil } /// 继续播放有声内容时从哪里接着放:停得越久往回退得越多。nil 表示原地接着放 —— 没开智能回退、 @@ -728,16 +731,23 @@ extension AudioPlayerService { guard currentItemIsSpokenWord, !isPlaying, !isAtTrackEnd, !spokenWordRepositionedWhilePaused, let limit = spokenWordSmartRewindLimit, position.isFinite, position > 0 else { return nil } if seeksInPlace, activeDecoderKind == .streaming, completedFullDownloadURL(for: song) == nil { return nil } + let triggeredBySleepTimer = PodcastPlaybackState.shared.sleepTimerPausedSongID == song.id let stoppedAt = spokenWordStoppedAt.flatMap { $0.songID == song.id ? $0.at : nil } let storedAt = SpokenWordStore.shared.position(forSongID: song.id)?.updatedAt - guard let lastHeard = [stoppedAt, storedAt].compactMap({ $0 }).max() else { return nil } - let away = Date().timeIntervalSince(lastHeard) - let rewound = SpokenWordSmartRewindPolicy.resumePosition(from: position, away: away, limit: limit) + let lastHeard = [stoppedAt, storedAt].compactMap({ $0 }).max() + if !triggeredBySleepTimer, lastHeard == nil { return nil } + let away = lastHeard.map { Date().timeIntervalSince($0) } ?? 0 + let rewound = SpokenWordSmartRewindPolicy.resumePosition( + from: position, + away: away, + limit: limit, + triggeredBySleepTimer: triggeredBySleepTimer + ) let target = spokenWordIntroOutro(for: song).flatMap { SpokenWordIntroOutroPolicy.startPosition(resume: rewound, duration: song.duration, skip: $0) } ?? rewound guard position - target >= 1 else { return nil } - plog("🎧 Spoken word: smart rewind \(Int(position - target))s after \(Int(away))s away on '\(song.title)'") + plog("🎧 Spoken word: smart rewind \(Int(position - target))s after \(Int(away))s away\(triggeredBySleepTimer ? " (sleep-wake)" : "") on '\(song.title)'") return target } @@ -1522,7 +1532,7 @@ extension AudioPlayerService { let index = spokenWordChapters.chapterIndex(at: currentTime) guard index != currentChapterIndex else { return } currentChapterIndex = index - if currentItemIsAudiobook { updateNowPlayingInfo() } + if currentItemIsSpokenWord { updateNowPlayingInfo() } } func seekToChapter(at index: Int) { diff --git a/Primuse/Services/Podcast/PodcastNetwork.swift b/Primuse/Services/Podcast/PodcastNetwork.swift index ad93b578a..1bde2d5b1 100644 --- a/Primuse/Services/Podcast/PodcastNetwork.swift +++ b/Primuse/Services/Podcast/PodcastNetwork.swift @@ -381,20 +381,33 @@ enum PodcastChapterLoader { } else if readsRemoteFile { // 探过、明确不认 Range 的地址,要文件头就等于把整集下下来。 let probe = PodcastEnclosureProbeCache.shared.probe(forEpisodeID: episode.id) - guard probe?.supportsRange != false else { return [] } - embedded = await PodcastNetwork.embeddedChapters(from: probe?.finalURL ?? episode.enclosureURL) + if probe?.supportsRange == false { + embedded = [] + } else { + embedded = await PodcastNetwork.embeddedChapters(from: probe?.finalURL ?? episode.enclosureURL) + } } else { - return [] + embedded = nil } - guard let embedded else { return [] } - // feed 指了 JSON 却拿回空的,可能只是这次没取到:文件里也没有时不记,下次两样都再试。 - if !embedded.isEmpty || episode.chaptersURL == nil { + if let embedded, !embedded.isEmpty { remember(embedded, for: episode.id) - } - if !embedded.isEmpty { plog("🎙️ Chapters: \(embedded.count) marks in the audio file of '\(episode.title)'") + return embedded + } + let synthesized = PodcastShowNotes.chapters(from: episode.showNotes, duration: episode.duration) + if !synthesized.isEmpty { + // 仅在已完成音频内嵌章节检查且无待重试 JSON 时缓存合成章节,避免遮蔽真正的内嵌章节。 + if embedded != nil && episode.chaptersURL == nil { + remember(synthesized, for: episode.id) + } + plog("🎙️ Chapters: \(synthesized.count) synthesized from show notes of '\(episode.title)'") + return synthesized + } + // feed 指了 JSON 却拿回空的,可能只是这次没取到:文件里也没有时不记,下次两样都再试。 + if embedded != nil, episode.chaptersURL == nil { + remember([], for: episode.id) } - return embedded + return [] } private static func remember(_ chapters: [MediaChapter], for episodeID: String) { diff --git a/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift b/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift index ea1ba38ab..835324809 100644 --- a/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift +++ b/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift @@ -139,6 +139,9 @@ struct PodcastUpNextList: View { ForEach(upcoming) { item in row(item) } + .onMove { source, destination in + move(upcoming, fromOffsets: source, toOffset: destination) + } } header: { header(upcoming) } @@ -149,35 +152,115 @@ struct PodcastUpNextList: View { } private func header(_ upcoming: [QueuePresentationEntry]) -> some View { - HStack { - Text("up_next") - .font(.footnote.weight(.semibold)) - .foregroundStyle(secondary) - Spacer() - if player.canRemoveUpcomingQueueEntries { - Button("clear") { - pmWithAnimation(.list) { - // 从后往前删,每删一项队列里前面的位置都不变。 - for item in upcoming.reversed() { - _ = player.removeUpcomingQueueEntry(occurrence(item)) + let stopAfterCurrent = player.currentSong != nil + && player.sleepStopAfterSongID == player.currentSong?.id + && player.selectedChapterSleep == nil + let totalDuration = totalAdjustedDuration(for: upcoming) + return VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 8) { + Text(headerTitle(count: upcoming.count, totalDuration: totalDuration)) + .font(.footnote.weight(.semibold).monospacedDigit()) + .foregroundStyle(secondary) + .lineLimit(1) + Spacer() + if player.currentSong != nil { + Button { + pmWithAnimation(.control) { + if stopAfterCurrent { + player.cancelSleep() + } else { + player.scheduleSleepAtTrackEnd() + } + } + } label: { + Label( + String(localized: "sleep_at_item_end"), + systemImage: stopAfterCurrent ? "stop.circle.fill" : "stop.circle" + ) + .font(.caption.weight(.semibold)) + .foregroundStyle(stopAfterCurrent ? accent : secondary) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background( + (stopAfterCurrent ? accent.opacity(0.16) : secondary.opacity(0.12)), + in: Capsule() + ) + } + .buttonStyle(.plain) + } + if player.canRemoveUpcomingQueueEntries { + Button("clear") { + pmWithAnimation(.list) { + // 从后往前删,每删一项队列里前面的位置都不变。 + for item in upcoming.reversed() { + _ = player.removeUpcomingQueueEntry(occurrence(item)) + } } } + .font(.footnote.weight(.semibold)) + .buttonStyle(.plain) + .foregroundStyle(accent) } - .font(.footnote.weight(.semibold)) - .buttonStyle(.plain) - .foregroundStyle(accent) } } .textCase(nil) } + private func headerTitle(count: Int, totalDuration: TimeInterval) -> String { + var parts = [String(localized: "up_next"), "\(count)"] + if totalDuration >= 60, let formatted = PodcastFormat.duration(totalDuration) { + parts.append(formatted) + } + return parts.joined(separator: " · ") + } + + private func totalAdjustedDuration(for upcoming: [QueuePresentationEntry]) -> TimeInterval { + let store = SpokenWordStore.shared + return upcoming.reduce(0) { total, item in + let song = item.entry.song + guard !store.isFinished(songID: song.id) else { return total } + let rawRemaining: TimeInterval + if let stored = store.position(forSongID: song.id), stored.duration > stored.position { + rawRemaining = stored.duration - stored.position + } else { + rawRemaining = max(0, song.duration) + } + let rate = player.requestedPlaybackRate(for: song) + return total + SpokenWordNowPlayingPolicy.listeningTime(forContent: rawRemaining, rate: rate) + } + } + + private func move( + _ upcoming: [QueuePresentationEntry], + fromOffsets source: IndexSet, + toOffset destination: Int + ) { + guard player.canRemoveUpcomingQueueEntries else { return } + let occurrences = upcoming.map(occurrence) + let steps = QueueUpcomingReorderPolicy.moveSteps( + fromOffsets: source, + toOffset: destination, + in: occurrences + ) + guard !steps.isEmpty else { return } + pmWithAnimation(.list) { + for step in steps { + _ = player.moveUpcomingQueueEntry(step.dragged, over: step.over) + } + } + } + private func row(_ item: QueuePresentationEntry) -> some View { Button { guard let index = player.queueEntries.firstIndex(where: { $0.id == item.entry.id }) else { return } Task { await player.playFromQueue(at: index) } onOpen?() } label: { - PodcastUpNextRow(song: item.entry.song, palette: palette) + PodcastUpNextRow( + song: item.entry.song, + playbackRate: player.requestedPlaybackRate(for: item.entry.song), + palette: palette + ) } .buttonStyle(.plain) .listRowBackground(Color.clear) @@ -236,6 +319,7 @@ struct PodcastUpNextList: View { /// 「接下来」里的一行:方形封面、单集名、节目名与还剩多少。 private struct PodcastUpNextRow: View { let song: Song + var playbackRate: Float = 1 var palette: SpokenWordPlayerPalette? private var primary: Color { palette?.primary ?? .primary } @@ -282,14 +366,22 @@ private struct PodcastUpNextRow: View { return parts.isEmpty ? nil : parts.joined(separator: " · ") } - /// 听完的说「已播放」,听到一半的说还剩多久,没听过的说多长。 + /// 听完的说「已播放」,听到一半的说还剩多久,没听过的说多长(按该节目有效倍速折算)。 private var progress: String? { let store = SpokenWordStore.shared if store.isFinished(songID: song.id) { return String(localized: "podcast_played") } if let stored = store.position(forSongID: song.id), stored.duration > stored.position { - return PodcastFormat.remaining(stored.duration - stored.position) + let adjusted = SpokenWordNowPlayingPolicy.listeningTime( + forContent: stored.duration - stored.position, + rate: playbackRate + ) + return PodcastFormat.remaining(adjusted) } - return PodcastFormat.duration(song.duration) + let adjusted = SpokenWordNowPlayingPolicy.listeningTime( + forContent: song.duration, + rate: playbackRate + ) + return PodcastFormat.duration(adjusted) } } diff --git a/PrimuseKit/Sources/PrimuseKit/Playback/QueueUpcomingReorderPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Playback/QueueUpcomingReorderPolicy.swift index f93f59744..c2d9ddb51 100644 --- a/PrimuseKit/Sources/PrimuseKit/Playback/QueueUpcomingReorderPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Playback/QueueUpcomingReorderPolicy.swift @@ -60,6 +60,44 @@ public enum QueueUpcomingReorderPolicy { return reordered == upcomingOccurrences ? nil : reordered } + /// Translates SwiftUI `List`/`ForEach` `.onMove(fromOffsets:toOffset:)` into + /// ordered `moveUpcomingQueueEntry(_:over:)` pairs. + public static func moveSteps( + fromOffsets source: IndexSet, + toOffset destination: Int, + in occurrences: [QueueReorderOccurrenceID] + ) -> [(dragged: QueueReorderOccurrenceID, over: QueueReorderOccurrenceID)] { + let validSource = source.filter { occurrences.indices.contains($0) }.sorted() + guard !validSource.isEmpty, destination >= 0, destination <= occurrences.count else { return [] } + let movedItems = validSource.map { occurrences[$0] } + let removedBeforeDestination = validSource.count(where: { $0 < destination }) + var desired = occurrences + for index in validSource.reversed() { + desired.remove(at: index) + } + let insertAt = min(max(0, destination - removedBeforeDestination), desired.count) + desired.insert(contentsOf: movedItems, at: insertAt) + guard desired != occurrences else { return [] } + + if validSource.count == 1 { + let dragged = occurrences[validSource[0]] + let target = occurrences[insertAt] + return dragged == target ? [] : [(dragged: dragged, over: target)] + } + + var working = occurrences + var steps: [(dragged: QueueReorderOccurrenceID, over: QueueReorderOccurrenceID)] = [] + for targetIndex in desired.indices { + let item = desired[targetIndex] + guard let currentIndex = working.firstIndex(of: item), currentIndex != targetIndex else { continue } + let targetOccurrence = working[targetIndex] + steps.append((dragged: item, over: targetOccurrence)) + let moved = working.remove(at: currentIndex) + working.insert(moved, at: targetIndex) + } + return steps + } + /// Gapless and crossfade preparation only owns the first upcoming /// occurrence. Reordering later rows can keep that work intact; replacing /// the first occurrence must discard it without touching the current diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastShowNotes.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastShowNotes.swift index 3608246c1..4803a9bbf 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastShowNotes.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastShowNotes.swift @@ -30,6 +30,113 @@ public enum PodcastShowNotes { return TimeInterval(value) } + // MARK: - Synthesized Chapters + + /// Extracts chapter markers from show-note timestamp lists (e.g. `00:00 Intro`, + /// `(12:34) - Deep Dive`, `00:00 - 05:30 Opening`, or `Topic Name 12:34`) when + /// an episode does not carry feed, JSON, or embedded audio chapters. Requires at + /// least two strictly ascending entries so isolated timestamps in prose are ignored. + public static func chapters(from raw: String?, duration: TimeInterval? = nil) -> [MediaChapter] { + guard let raw, !raw.isEmpty else { return [] } + let maxDuration: TimeInterval? = duration.flatMap { $0.isFinite && $0 > 0 ? $0 : nil } + var candidates: [(title: String, startTime: TimeInterval, webURL: URL?)] = [] + for block in blocks(from: raw) { + guard let entry = chapterEntry(from: block.runs) else { continue } + if let maxDuration, entry.startTime >= maxDuration { continue } + if let last = candidates.last { + guard entry.startTime > last.startTime else { continue } + } + candidates.append(entry) + } + guard candidates.count >= 2 else { return [] } + return candidates.enumerated().map { index, item in + let endTime: TimeInterval? + if index + 1 < candidates.count { + endTime = candidates[index + 1].startTime + } else if let maxDuration, maxDuration > item.startTime { + endTime = maxDuration + } else { + endTime = nil + } + return MediaChapter( + startTime: item.startTime, + title: item.title, + endTime: endTime, + url: item.webURL + ) + } + } + + private static func chapterEntry(from runs: [Run]) -> (title: String, startTime: TimeInterval, webURL: URL?)? { + let timestamps: [(index: Int, seconds: TimeInterval)] = runs.enumerated().compactMap { index, run in + guard case .timestamp(_, let seconds) = run else { return nil } + return (index, seconds) + } + guard !timestamps.isEmpty, timestamps.count <= 2 else { return nil } + + let startTime = timestamps[0].seconds + let firstIndex = timestamps[0].index + let lastIndex: Int + if timestamps.count == 2 { + let between = runs[(firstIndex + 1).. URL? in + guard case .link(_, let url) = run, + let scheme = url.scheme?.lowercased(), + scheme == "http" || scheme == "https" else { return nil } + return url + }.first + return (title, startTime, webURL) + } + + private static func isRangeSeparator(_ text: String) -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return trimmed.isEmpty || ["-", "–", "—", "~", "to", "->"].contains(trimmed) + } + + private static func isTimestampWrapperOnly(_ text: String) -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return true } + let wrappers = CharacterSet(charactersIn: "()[]{}()【】-–—:|•·., ") + if trimmed.unicodeScalars.allSatisfy({ wrappers.contains($0) }) { return true } + // Accept short leading chapter numbering such as "1." or "02)" before the timestamp. + let stripped = trimmed.trimmingCharacters(in: wrappers) + return stripped.count <= 3 && stripped.allSatisfy(\.isNumber) + } + + private static func cleanedChapterTitle(_ text: String) -> String { + let separators = CharacterSet.whitespacesAndNewlines.union( + CharacterSet(charactersIn: "-–—:|•·()[]()【】") + ) + var result = text.trimmingCharacters(in: .whitespacesAndNewlines) + while let first = result.unicodeScalars.first, separators.contains(first) { + result.unicodeScalars.removeFirst() + } + while let last = result.unicodeScalars.last, + CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: "-–—:|•·([(【")).contains(last) { + result.unicodeScalars.removeLast() + } + return PodcastText.collapsingWhitespace(result) + } + // MARK: - Plain text /// 列表行里那一两行摘要:去标签、解实体、合并空白。单遍扫描,读够 `limit` 个字就停 —— @@ -419,3 +526,12 @@ public extension PodcastShowNotes.Run { } } } + +public extension PodcastShowNotes.Block { + var runs: [PodcastShowNotes.Run] { + switch self { + case .paragraph(let runs), .heading(let runs), .listItem(let runs, _), .quote(let runs): + return runs + } + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordContentPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordContentPolicy.swift index 4fc06c121..4ff3ad483 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordContentPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordContentPolicy.swift @@ -248,62 +248,6 @@ public enum SpokenWordProgressPolicy { } } -/// 智能回退(#363):有声内容停下来越久,继续时往回退得越多 —— 短暂停一下只退几秒,隔夜退得多, -/// 最多退到用户选的上限。 -/// -/// 回退量按离开的时长在几个锚点之间按对数插值:离开时长翻一倍多退的秒数差不多,不会因为离开 -/// 十倍久就退十倍。几秒内的停顿(碰了一下暂停、接了句话)不退。关掉时续播照旧固定回退 -/// `SpokenWordProgressPolicy.resumeRewind`,播放中暂停再继续不退。 -public enum SpokenWordSmartRewindPolicy { - /// 「回退上限」的可选值(秒)。 - public static let limitChoices: [Int] = [15, 30, 60, 120, 300] - public static let defaultLimit = 30 - public static let enabledByDefault = true - - /// (离开的秒数, 回退的秒数),离开时长递增。第一个锚点以内不退,最后一个以外按最后一个算。 - static let anchors: [(away: TimeInterval, rewind: TimeInterval)] = [ - (5, 0), - (15, 2), - (60, 5), - (10 * 60, 15), - (60 * 60, 30), - (8 * 60 * 60, 120), - (3 * 24 * 60 * 60, 300), - ] - - /// 存下来的上限不在可选值里时取最接近的一档。 - public static func clampedLimit(_ seconds: Int) -> Int { - limitChoices.min { abs($0 - seconds) < abs($1 - seconds) } ?? defaultLimit - } - - /// 离开 `away` 秒后继续,往回退多少秒:整秒,不超过 `limit`。 - public static func rewind(afterAway away: TimeInterval, limit: TimeInterval) -> TimeInterval { - guard away.isFinite, limit.isFinite, limit > 0, - let first = anchors.first, let last = anchors.last, - away > first.away else { return 0 } - var amount = last.rewind - for (lower, upper) in zip(anchors, anchors.dropFirst()) where away < upper.away { - let fraction = log(away / lower.away) / log(upper.away / lower.away) - amount = lower.rewind + (upper.rewind - lower.rewind) * fraction - break - } - return min(limit, amount.rounded()) - } - - /// 停在 `position`、离开 `away` 秒后,从哪里接着放。不早于 `floor`(这一条的开头)。 - public static func resumePosition( - from position: TimeInterval, - away: TimeInterval, - limit: TimeInterval, - floor: TimeInterval = 0 - ) -> TimeInterval { - guard position.isFinite else { return position } - let rewind = rewind(afterAway: away, limit: limit) - guard rewind > 0, position > floor else { return position } - return max(floor, position - rewind) - } -} - /// Skip intervals for spoken word, matching what listeners expect from an /// audiobook or podcast app: a short step back to re-hear a sentence, a longer /// one forward to get past a passage. diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartRewindPolicy.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartRewindPolicy.swift new file mode 100644 index 000000000..f1cab8037 --- /dev/null +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartRewindPolicy.swift @@ -0,0 +1,68 @@ +import Foundation + +/// 智能回退(#363):有声内容停下来越久,继续时往回退得越多 —— 短暂停一下只退几秒,隔夜退得多, +/// 最多退到用户选的上限。 +/// +/// 回退量按离开的时长在几个锚点之间按对数插值:离开时长翻一倍多退的秒数差不多,不会因为离开 +/// 十倍久就退十倍。几秒内的停顿(碰了一下暂停、接了句话)不退。关掉时续播照旧固定回退 +/// `SpokenWordProgressPolicy.resumeRewind`,播放中暂停再继续不退。 +public enum SpokenWordSmartRewindPolicy { + /// 「回退上限」的可选值(秒)。 + public static let limitChoices: [Int] = [15, 30, 60, 120, 300] + public static let defaultLimit = 30 + public static let enabledByDefault = true + /// Minimum rewind applied when resuming spoken word paused by a sleep timer, + /// compensating for drifting off during the fade-out even on short naps. + public static let sleepWakeMinimumRewind: TimeInterval = 30 + + /// (离开的秒数, 回退的秒数),离开时长递增。第一个锚点以内不退,最后一个以外按最后一个算。 + static let anchors: [(away: TimeInterval, rewind: TimeInterval)] = [ + (5, 0), + (15, 2), + (60, 5), + (10 * 60, 15), + (60 * 60, 30), + (8 * 60 * 60, 120), + (3 * 24 * 60 * 60, 300), + ] + + /// 存下来的上限不在可选值里时取最接近的一档。 + public static func clampedLimit(_ seconds: Int) -> Int { + limitChoices.min { abs($0 - seconds) < abs($1 - seconds) } ?? defaultLimit + } + + /// 离开 `away` 秒后继续,往回退多少秒:整秒,不超过 `limit`。 + /// 睡眠定时到点暂停后再继续时,至少回退 `min(limit, sleepWakeMinimumRewind)`,补回淡出入睡前的片段。 + public static func rewind( + afterAway away: TimeInterval, + limit: TimeInterval, + triggeredBySleepTimer: Bool = false + ) -> TimeInterval { + guard limit.isFinite, limit > 0 else { return 0 } + let sleepFloor = triggeredBySleepTimer ? min(limit, sleepWakeMinimumRewind) : 0 + guard away.isFinite, + let first = anchors.first, let last = anchors.last, + away > first.away else { return sleepFloor } + var amount = last.rewind + for (lower, upper) in zip(anchors, anchors.dropFirst()) where away < upper.away { + let fraction = log(away / lower.away) / log(upper.away / lower.away) + amount = lower.rewind + (upper.rewind - lower.rewind) * fraction + break + } + return max(sleepFloor, min(limit, amount.rounded())) + } + + /// 停在 `position`、离开 `away` 秒后,从哪里接着放。不早于 `floor`(这一条的开头)。 + public static func resumePosition( + from position: TimeInterval, + away: TimeInterval, + limit: TimeInterval, + floor: TimeInterval = 0, + triggeredBySleepTimer: Bool = false + ) -> TimeInterval { + guard position.isFinite else { return position } + let rewind = rewind(afterAway: away, limit: limit, triggeredBySleepTimer: triggeredBySleepTimer) + guard rewind > 0, position > floor else { return position } + return max(floor, position - rewind) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Playback/QueueRowIdentityTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Playback/QueueRowIdentityTests.swift index 12c5a3a22..cec0a2fc0 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Playback/QueueRowIdentityTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Playback/QueueRowIdentityTests.swift @@ -360,6 +360,48 @@ struct QueueUpcomingReorderPolicyTests { ) == nil) } + @Test("moveSteps translates List onMove offsets into exact reordered occurrences") + func translatesListOnMoveOffsets() { + let initial = occurrences([first, second, last]) + let queueIDs = [current, first, second, last] + + let downSteps = QueueUpcomingReorderPolicy.moveSteps( + fromOffsets: IndexSet(integer: 0), + toOffset: 3, + in: initial + ) + #expect(downSteps.count == 1) + let afterDown = QueueUpcomingReorderPolicy.reorderedOccurrences( + dragging: downSteps[0].dragged, + over: downSteps[0].over, + queueEntryIDs: queueIDs, + upcomingOccurrences: initial + ) + #expect(afterDown == occurrences([second, last, first])) + + let upSteps = QueueUpcomingReorderPolicy.moveSteps( + fromOffsets: IndexSet(integer: 2), + toOffset: 0, + in: initial + ) + #expect(upSteps.count == 1) + let afterUp = QueueUpcomingReorderPolicy.reorderedOccurrences( + dragging: upSteps[0].dragged, + over: upSteps[0].over, + queueEntryIDs: queueIDs, + upcomingOccurrences: initial + ) + #expect(afterUp == occurrences([last, first, second])) + + #expect( + QueueUpcomingReorderPolicy.moveSteps( + fromOffsets: IndexSet(integer: 0), + toOffset: 1, + in: initial + ).isEmpty + ) + } + private func occurrence(_ id: UUID, roundOffset: Int = 0) -> QueueReorderOccurrenceID { QueueReorderOccurrenceID(queueEntryID: id, roundOffset: roundOffset) } diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift new file mode 100644 index 000000000..6de0b3a22 --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift @@ -0,0 +1,47 @@ +import Foundation +import PrimuseKit +import Testing + +@Suite("Podcast show-notes synthesized chapters") +struct PodcastShowNotesChaptersTests { + @Test("Synthesizes chapters from plain and HTML show-note timestamps with links") + func synthesizesRichChaptersFromShowNotes() { + let html = """ +

Welcome to the show! At 12:34 Bob made an offhand comment in prose that should be ignored.

+
    +
  • 00:00 Intro & News
  • +
  • (12:34) - Main Topic
  • +
  • [1:05:20] Q&A
  • +
+ """ + let chapters = PodcastShowNotes.chapters(from: html, duration: 4800) + #expect(chapters.count == 3) + #expect(chapters[0].title == "Intro & News") + #expect(chapters[0].startTime == 0) + #expect(chapters[0].endTime == 754) + #expect(chapters[1].title == "Main Topic") + #expect(chapters[1].startTime == 754) + #expect(chapters[1].endTime == 3920) + #expect(chapters[1].webURL == URL(string: "https://example.com/topic")) + #expect(chapters[2].title == "Q&A") + #expect(chapters[2].startTime == 3920) + #expect(chapters[2].endTime == 4800) + } + + @Test("Handles ranges, trailing timestamps, and drops out-of-range or single-entry notes") + func handlesRangesTrailingAndFiltersNoise() { + let notes = """ + 00:00 - 05:30 Opening Remarks + Deep Dive — 05:30 + Closing (20:00) + Bonus Out Of Range 99:00 + """ + let chapters = PodcastShowNotes.chapters(from: notes, duration: 1800) + #expect(chapters.map(\.title) == ["Opening Remarks", "Deep Dive", "Closing"]) + #expect(chapters.map(\.startTime) == [0, 330, 1200]) + #expect(chapters.last?.endTime == 1800) + + #expect(PodcastShowNotes.chapters(from: "05:00 Only one timestamp", duration: 1800).isEmpty) + #expect(PodcastShowNotes.chapters(from: "No timestamps at all", duration: 1800).isEmpty) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordContentPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordContentPolicyTests.swift index 5d9c397d9..5ced0d06c 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordContentPolicyTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/SpokenWordContentPolicyTests.swift @@ -208,6 +208,26 @@ struct SpokenWordSmartRewindPolicyTests { #expect(SpokenWordSmartRewindPolicy.clampedLimit(10_000) == 300) #expect(SpokenWordSmartRewindPolicy.limitChoices.contains(SpokenWordSmartRewindPolicy.defaultLimit)) } + + @Test("Resuming after a sleep-timer pause rewinds at least the sleep-wake floor") + func sleepTimerWakeRewindsAtLeastFloor() { + #expect( + SpokenWordSmartRewindPolicy.rewind(afterAway: 2, limit: 60, triggeredBySleepTimer: true) + == SpokenWordSmartRewindPolicy.sleepWakeMinimumRewind + ) + #expect( + SpokenWordSmartRewindPolicy.rewind(afterAway: 2, limit: 15, triggeredBySleepTimer: true) + == 15 + ) + #expect( + SpokenWordSmartRewindPolicy.rewind(afterAway: 8 * 3600, limit: 120, triggeredBySleepTimer: true) + == 120 + ) + #expect( + SpokenWordSmartRewindPolicy.resumePosition(from: 600, away: 1, limit: 30, triggeredBySleepTimer: true) + == 570 + ) + } } @Suite("Spoken word skipping") diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index ea6cb19d7..bfa32bb28 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -377,4 +377,59 @@ final class ListeningSpacesReliabilityTests: XCTestCase { XCTAssertEqual(Int(decodedFrames), frameCount) XCTAssertGreaterThan(peakAmplitude, 0.25) } + + func testSleepWakeAutoRewindRewindsSpokenWordEvenOnImmediateResume() async throws { + let player = AudioPlayerService() + let prevEnabled = player.playbackSettings.spokenWordSmartRewindEnabled + let prevLimit = player.playbackSettings.spokenWordSmartRewindLimitSeconds + cleanups.append { + player.playbackSettings.spokenWordSmartRewindEnabled = prevEnabled + player.playbackSettings.spokenWordSmartRewindLimitSeconds = prevLimit + PodcastPlaybackState.shared.sleepTimerPausedSongID = nil + } + + player.playbackSettings.spokenWordSmartRewindEnabled = true + player.playbackSettings.spokenWordSmartRewindLimitSeconds = 60 + + let song = Song( + id: "sleep-wake-\(UUID().uuidString)", + title: "Chapter 1", + albumTitle: "Audiobook", + artistName: "Author", + duration: 1800, + fileFormat: .m4a, + filePath: "/tmp/sleep-wake.m4b", + sourceID: "local-test", + genre: "Audiobook" + ) + player.currentSong = song + player.currentItemIsSpokenWord = true + player.isPlaying = false + player.isAtTrackEnd = false + player.spokenWordStoppedAt = (song.id, Date()) + + // Without sleep-timer pause, immediate resume (0s away) does not rewind. + PodcastPlaybackState.shared.sleepTimerPausedSongID = nil + XCTAssertNil(player.spokenWordSmartRewindTarget(for: song, from: 600, seeksInPlace: false)) + + // After sleep-timer pause, immediate resume rewinds by at least sleepWakeMinimumRewind (30s). + PodcastPlaybackState.shared.sleepTimerPausedSongID = song.id + let target = try XCTUnwrap(player.spokenWordSmartRewindTarget(for: song, from: 600, seeksInPlace: false)) + XCTAssertEqual(target, 570, accuracy: 0.5) + + // Show-note chapter fallback returns synthesized chapters without remote file probing. + let episode = PodcastEpisode( + id: "notes-chapters-\(UUID().uuidString)", + showID: "show-1", + guid: "guid-1", + title: "Episode With Timestamps", + showNotes: "00:00 Intro\n10:00 Main Discussion\n25:00 Wrap Up", + duration: 1800, + enclosureURL: URL(string: "https://example.com/ep.mp3")!, + firstSeenAt: Date() + ) + let chapters = await PodcastChapterLoader.chapters(for: episode, readsRemoteFile: false) + XCTAssertEqual(chapters.map(\.title), ["Intro", "Main Discussion", "Wrap Up"]) + XCTAssertEqual(chapters.map(\.startTime), [0, 600, 1500]) + } } From 9356cc2835cb2195def51f3d72f61e9d989a9cf6 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 18:20:22 -0500 Subject: [PATCH 07/15] =?UTF-8?q?=E6=B3=9B=E5=8C=96=E6=9C=89=E5=A3=B0?= =?UTF-8?q?=E8=BF=9B=E5=BA=A6=E5=90=8C=E6=AD=A5=E6=94=AF=E6=8C=81=20Audiob?= =?UTF-8?q?ookshelf=EF=BC=8C=E8=A1=A5=E9=BD=90=E7=94=B5=E5=8F=B0=E6=9B=B2?= =?UTF-8?q?=E7=9B=AE=E5=B0=81=E9=9D=A2/=E5=90=AC=E8=BF=87=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E4=B8=8E=20Apple=20TV=20=E6=B7=A1=E5=87=BA=E5=92=8C?= =?UTF-8?q?=E8=8A=82=E7=9B=AE=E8=AF=B4=E6=98=8E=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 12 + Primuse/App/AppServices.swift | 12 +- ...verSpokenWordProgressSyncCoordinator.swift | 233 ++++++++++++++++++ .../Services/Library/SpokenWordStore.swift | 117 --------- Primuse/Views/Mac/MacNowPlayingView.swift | 3 +- Primuse/Views/NowPlaying/NowPlayingView.swift | 4 +- .../Views/Radio/RadioStationDetailView.swift | 66 ++++- Primuse/Views/Radio/RadioStationsView.swift | 12 - PrimuseTV/Model/TVStore+SleepTimer.swift | 95 +++++++ PrimuseTV/Model/TVStore.swift | 60 +---- PrimuseTV/Views/TVSpokenWordNowPlaying.swift | 38 ++- .../ListeningSpacesReliabilityTests.swift | 68 +++++ project.yml | 1 + 13 files changed, 523 insertions(+), 198 deletions(-) create mode 100644 Primuse/Services/Library/ServerSpokenWordProgressSyncCoordinator.swift create mode 100644 PrimuseTV/Model/TVStore+SleepTimer.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index f176e4805..17cafb36f 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -351,6 +351,7 @@ 19D86423FB6451728A3C6B20 /* LyricsTimingSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 176AB6D39DEC58EF59423D72 /* LyricsTimingSession.swift */; }; 19F058F7B3C2839A3B662A2B /* AudioPlayerService+Crossfade.swift in Sources */ = {isa = PBXBuildFile; fileRef = 202FD9C3E6649FA70A64E987 /* AudioPlayerService+Crossfade.swift */; }; 19F6C2E64A257AC081AC2C3D /* SourcePageCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4793CC53FB048C1B17E027D /* SourcePageCatalog.swift */; }; + 1A10E1E7F79016696803CC81 /* ServerSpokenWordProgressSyncCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73C81584A2D23908331A0562 /* ServerSpokenWordProgressSyncCoordinator.swift */; }; 1A1C7C4F1F0C1B7F7809335A /* StreamResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4430B0204E343AF011F490F1 /* StreamResolver.swift */; }; 1A2150318588F9991A698267 /* libavutil.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 97F67F7EA254BBF6D2BA74A0 /* libavutil.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 1A21CCE0B8669EAE338BAEDD /* ListeningScene.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F330EA3F66C9198B0F86BB8 /* ListeningScene.swift */; }; @@ -1693,6 +1694,7 @@ 7C79048A9955A27D0B866308 /* HomeForYouSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17E404D4638787229DC81095 /* HomeForYouSection.swift */; }; 7CAB3D5BD05832323A817285 /* ArtistIdentityPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BD1DE9D918F2F538F762AE7 /* ArtistIdentityPolicy.swift */; }; 7CC510CFB7AE45C4AF720D0E /* ID3SynchronizedLyricsParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25F35F3F45A8184ACB596613 /* ID3SynchronizedLyricsParser.swift */; }; + 7CCBBAC5687F575024E99733 /* TVStore+SleepTimer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D6DFB2A327EAB97BC58ADC8 /* TVStore+SleepTimer.swift */; }; 7D0832BD21EB9CCBD63E37FD /* ScanTLSTrustRetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 288A55230618464469979B71 /* ScanTLSTrustRetryPolicy.swift */; }; 7D0C759614CAB0E41E588E71 /* SleepTimerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D95C407321BB61F2AE5D951 /* SleepTimerSheet.swift */; }; 7D15AAD78D3B79FCA6E228D3 /* MusicLibrary+BoundedCollectionSongs.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9C9AE48EA362E6FF04D6A3D /* MusicLibrary+BoundedCollectionSongs.swift */; }; @@ -2499,6 +2501,7 @@ B9808C4B7AAE0E26CA63EF99 /* ImmersiveSyllableCrestPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E5472C7F798CEFC28DDC450 /* ImmersiveSyllableCrestPolicy.swift */; }; B98A72797203BA2A6DB77663 /* TVPlayerShelf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E54A3765FAC8D149BA0CFB3 /* TVPlayerShelf.swift */; }; B99C6369B3A2C508A5382E56 /* ScrobbleRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5AEA62DA6DCCE70D8C4B5B /* ScrobbleRequestTests.swift */; }; + B9A1E5CEA54900A2E0411456 /* ServerSpokenWordProgressSyncCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73C81584A2D23908331A0562 /* ServerSpokenWordProgressSyncCoordinator.swift */; }; B9B7A179432C96BAB4AD101A /* DiagnosticReportMailPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F13777CE949E8F95502C13D /* DiagnosticReportMailPolicy.swift */; }; B9BCEE24C2BCAF0F59F66FFF /* LibrarySnapshotSync+StagedPreparation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 045159A6132E6BE82E1D593D /* LibrarySnapshotSync+StagedPreparation.swift */; }; B9C56BF1262B286D0C1A4C98 /* LibraryCatalog+KindPointReads.swift in Sources */ = {isa = PBXBuildFile; fileRef = 361CCA1B12F522769DD09B73 /* LibraryCatalog+KindPointReads.swift */; }; @@ -2911,6 +2914,7 @@ D9CD4A48A986CC1899BE9BB7 /* ScanPruneAndWriteDurabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 678072D1979819435D623487 /* ScanPruneAndWriteDurabilityTests.swift */; }; D9DBE9996C1FC8988941DA4D /* NativeScraperHTTPTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D03AD6BE2F6F8943FFB29029 /* NativeScraperHTTPTests.swift */; }; D9DC4368717615C800518619 /* LibraryBackupService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DA681C96B015F3FD2422BB5 /* LibraryBackupService.swift */; }; + D9E409068C8F6DE1BFEEDB4B /* ServerSpokenWordProgressSyncCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73C81584A2D23908331A0562 /* ServerSpokenWordProgressSyncCoordinator.swift */; }; D9EACD0E66A448D26DAB2D59 /* PrimuseAppIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECCDD80F05FA4A71FA0CB32 /* PrimuseAppIntents.swift */; }; DA0AB6A4692632E876456A4B /* PlaybackChunkRetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD66BB78A62DF53FDEE661DF /* PlaybackChunkRetryPolicy.swift */; }; DA1C3C909B2CD5FA9B718272 /* LibraryInsightCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1409AE7542E2B418AF34CFA /* LibraryInsightCard.swift */; }; @@ -4854,6 +4858,7 @@ 7382A4287582C3E04B421BC5 /* zh-Hant */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hant"; path = "zh-Hant.lproj/WidgetConfiguration.strings"; sourceTree = ""; }; 738CA001A4119151DECB6874 /* MusicDiscoveryEngineEquivalenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicDiscoveryEngineEquivalenceTests.swift; sourceTree = ""; }; 739D39A7CBFF521C4444D560 /* LocalLyricTranslationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalLyricTranslationPolicy.swift; sourceTree = ""; }; + 73C81584A2D23908331A0562 /* ServerSpokenWordProgressSyncCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSpokenWordProgressSyncCoordinator.swift; sourceTree = ""; }; 7406E61804E7503B1E5D4475 /* ExternalPlaylistFetcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalPlaylistFetcher.swift; sourceTree = ""; }; 74134D8D32D016D927D59D77 /* ThemeService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThemeService.swift; sourceTree = ""; }; 7420AD8DFDE096459FC1629B /* fr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = fr; path = fr.lproj/InfoPlist.strings; sourceTree = ""; }; @@ -5112,6 +5117,7 @@ 8D3EB44902FAD68244A08A55 /* NonFiniteSongPersistenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NonFiniteSongPersistenceTests.swift; sourceTree = ""; }; 8D5809673781FF8F935A6E82 /* PodcastModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PodcastModels.swift; sourceTree = ""; }; 8D6C666CF15C82AE6B8454A0 /* SmartNudgeCenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmartNudgeCenter.swift; sourceTree = ""; }; + 8D6DFB2A327EAB97BC58ADC8 /* TVStore+SleepTimer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TVStore+SleepTimer.swift"; sourceTree = ""; }; 8D96641030CF424B634F4265 /* ListeningIntentRanking.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListeningIntentRanking.swift; sourceTree = ""; }; 8DCD6A621ACBB8145468F9D5 /* LibraryHubReleased.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryHubReleased.swift; sourceTree = ""; }; 8DD794230AEA7E56FF0C4348 /* MergedListeningHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MergedListeningHistory.swift; sourceTree = ""; }; @@ -7085,6 +7091,7 @@ 38876E4619D96AB7D86233BC /* TVStore+CatalogMaintenance.swift */, F8E29CBD10FEC7A67B8DAAA1 /* TVStore+CustomHeaders.swift */, 84DC4057DB3739DC78270429 /* TVStore+RecentlyAddedAlbums.swift */, + 8D6DFB2A327EAB97BC58ADC8 /* TVStore+SleepTimer.swift */, ); path = Model; sourceTree = ""; @@ -8022,6 +8029,7 @@ 19C54BEA9315D3A21ECC1E48 /* ScanService+CatalogStart.swift */, 8F97A658E0F97D4ED3A30462 /* ScanService+PagedCommitBatches.swift */, 6B60495B4617035491BA0CFA /* ServerPlaylistMirror.swift */, + 73C81584A2D23908331A0562 /* ServerSpokenWordProgressSyncCoordinator.swift */, AF3960617C3D665E949A8171 /* ShuffleWeighting.swift */, 8D6C666CF15C82AE6B8454A0 /* SmartNudgeCenter.swift */, C3577006473AE56E9BA09B47 /* SmartPlaylistEngine.swift */, @@ -11990,6 +11998,7 @@ E033450A9371A7BF05B5A587 /* ServerPlaylistSyncService.swift in Sources */, 6A4CFF7CE307928354FE584C /* ServerRatingSyncService.swift in Sources */, E43CEBD80C3FAB5885003541 /* ServerSongSearchService.swift in Sources */, + 1A10E1E7F79016696803CC81 /* ServerSpokenWordProgressSyncCoordinator.swift in Sources */, 94007D2F499B1D69BB3D4AC0 /* ServerTranscriptReload.swift in Sources */, 17F779845824B8919237B383 /* ServerUsersView.swift in Sources */, E5E977ED575BFEE1288ACF3E /* SettingsActionService.swift in Sources */, @@ -12364,6 +12373,7 @@ 7635925D8884E6C7EF5C9D57 /* ScrobbleService.swift in Sources */, 5C9C1102C689DE3A5D2756B2 /* ScrobbleSettings.swift in Sources */, 1B1495FAE0F8456866676C61 /* ServerPlaylistMirror.swift in Sources */, + B9A1E5CEA54900A2E0411456 /* ServerSpokenWordProgressSyncCoordinator.swift in Sources */, 9FE02F5BE86D879AA5937B53 /* ShuffleWeighting.swift in Sources */, E78EB768A433FB14F7946ECB /* SmartPlaylistEngine+Catalog.swift in Sources */, 1CEDC65A7EFD169B18E22B80 /* SmartPlaylistEngine.swift in Sources */, @@ -12460,6 +12470,7 @@ CFCA59302DB22ECC209325C0 /* TVStore+CatalogMaintenance.swift in Sources */, BCEDEAAFD3B6BF5B7780BBCC /* TVStore+CustomHeaders.swift in Sources */, FF7250D994D365404F2BE383 /* TVStore+RecentlyAddedAlbums.swift in Sources */, + 7CCBBAC5687F575024E99733 /* TVStore+SleepTimer.swift in Sources */, 69F39E580C4E08F73E195E62 /* TVStore.swift in Sources */, 3E6615C76D4636FBFFDBA789 /* TVStreamResourceLoader.swift in Sources */, 26FD125E371B9C01ED64F6F9 /* TVTheme.swift in Sources */, @@ -13209,6 +13220,7 @@ 8D3C22FB51AC690A69E3D9A9 /* ServerPlaylistSyncService.swift in Sources */, F70EAD0DDB121C4B26DB471D /* ServerRatingSyncService.swift in Sources */, 9BABC26675E6B98247940416 /* ServerSongSearchService.swift in Sources */, + D9E409068C8F6DE1BFEEDB4B /* ServerSpokenWordProgressSyncCoordinator.swift in Sources */, DAB97B65254CBC298D727078 /* ServerTranscriptReload.swift in Sources */, D23F19C9A6B5E030335F623A /* ServerUsersView.swift in Sources */, BA97287E4483EAD0F3AF06FD /* SettingsActionService.swift in Sources */, diff --git a/Primuse/App/AppServices.swift b/Primuse/App/AppServices.swift index 8ad87e522..1210a756d 100644 --- a/Primuse/App/AppServices.swift +++ b/Primuse/App/AppServices.swift @@ -1520,18 +1520,16 @@ final class AppServices { ) self.tingReaderProgressSync = TingReaderProgressSyncCoordinator( sources: { [weak store] in store?.sources ?? [] }, - songs: { [weak library] in - guard let library, library.isUsable else { return nil } - return library.sourceVisibleSongs($0) - }, + songs: { [weak library] in library?.isUsable == true ? library?.sourceVisibleSongs($0) : nil }, fetch: { [weak manager] source in guard let manager else { throw CancellationError() } return try await manager.fetchRecentTingReaderProgress(for: source) }, - protectedSongID: { [weak player] in - guard let player, player.isPlaying || player.isLoading else { return nil } - return player.currentSong?.id + fetchAudiobookshelf: { [weak manager] source, paths in + guard let manager else { throw CancellationError() } + return await manager.fetchServerListeningProgress(for: source, songPaths: paths) }, + protectedSongID: { [weak player] in (player?.isPlaying == true || player?.isLoading == true) ? player?.currentSong?.id : nil }, didAdopt: { [weak player] song in player?.applySyncedSpokenWordPosition(for: song) }, didFinishAdopting: { [weak player] in player?.followSpokenWordBookIfPaused() } ) diff --git a/Primuse/Services/Library/ServerSpokenWordProgressSyncCoordinator.swift b/Primuse/Services/Library/ServerSpokenWordProgressSyncCoordinator.swift new file mode 100644 index 000000000..3b6416157 --- /dev/null +++ b/Primuse/Services/Library/ServerSpokenWordProgressSyncCoordinator.swift @@ -0,0 +1,233 @@ +import Foundation +import Observation +import PrimuseKit + +/// 进度不随书目数量变化;启动、回前台与手动刷新单独读取,按服务端时间合并。 +/// 同时承接听书服务端(Ting Reader 与 Audiobookshelf)的有声进度同步,复用冷却、安全指纹校验与播放中保护。 +@MainActor +@Observable +final class TingReaderProgressSyncCoordinator { + private let defaults: UserDefaults + private let store: SpokenWordStore + private let sources: () -> [MusicSource] + /// 这个源的歌。nil:此刻答不了(歌曲模型不在内存里),不是「一首都没有」。 + private let songs: (String) -> [Song]? + private let fetch: @MainActor (MusicSource) async throws -> [TingReaderListeningProgress] + private let fetchAudiobookshelf: (@MainActor (MusicSource, [String]) async throws -> [ServerListeningProgress])? + private let protectedSongID: () -> String? + private let didAdopt: (Song) -> Void + /// 一轮读取确认了可用进度后,重新判断暂停中的播放器该接哪一章。 + private let didFinishAdopting: () -> Void + private var disabledSourceIDs: Set + private(set) var refreshingSourceIDs: Set = [] + private(set) var failedSourceIDs: Set = [] + @ObservationIgnored private var lastAttempt: [String: Date] = [:] + @ObservationIgnored private var preferenceRevision: [String: Int] = [:] + + init( + defaults: UserDefaults = .standard, + store: SpokenWordStore = .shared, + sources: @escaping () -> [MusicSource], + songs: @escaping (String) -> [Song]?, + fetch: @escaping @MainActor (MusicSource) async throws -> [TingReaderListeningProgress], + fetchAudiobookshelf: (@MainActor (MusicSource, [String]) async throws -> [ServerListeningProgress])? = nil, + protectedSongID: @escaping () -> String?, + didAdopt: @escaping (Song) -> Void = { _ in }, + didFinishAdopting: @escaping () -> Void = {} + ) { + self.defaults = defaults + self.store = store + self.sources = sources + self.songs = songs + self.fetch = fetch + self.fetchAudiobookshelf = fetchAudiobookshelf + self.protectedSongID = protectedSongID + self.didAdopt = didAdopt + self.didFinishAdopting = didFinishAdopting + disabledSourceIDs = Set(defaults.stringArray(forKey: Self.defaultsKey) ?? []) + } +} + +extension TingReaderProgressSyncCoordinator { + private static let defaultsKey = "primuse.ting-reader-progress-auto-sync.disabled.v1" + static let cooldown: TimeInterval = 30 + + var hasSources: Bool { sources().contains(where: supportsSource) } + + static func supports(_ source: MusicSource) -> Bool { + source.type == .tingReader && source.isEnabled && !source.isDeleted + } + + func supportsSource(_ source: MusicSource) -> Bool { + guard source.isEnabled, !source.isDeleted else { return false } + if source.type == .tingReader { return true } + return source.type == .audiobookshelf && fetchAudiobookshelf != nil + } + + func isEnabled(for sourceID: String) -> Bool { !disabledSourceIDs.contains(sourceID) } + + func setEnabled(_ enabled: Bool, for sourceID: String) { + if enabled { disabledSourceIDs.remove(sourceID) } + else { disabledSourceIDs.insert(sourceID) } + preferenceRevision[sourceID, default: 0] += 1 + lastAttempt.removeValue(forKey: sourceID) + defaults.set(Array(disabledSourceIDs).sorted(), forKey: Self.defaultsKey) + } + + func refresh(sourceID: String? = nil, manual: Bool = false) async { + for source in sources() where supportsSource(source) && (sourceID == nil || source.id == sourceID) { + guard !Task.isCancelled else { return } + guard manual || isEnabled(for: source.id), + manual || lastAttempt[source.id].map({ Date().timeIntervalSince($0) >= Self.cooldown }) != false, + refreshingSourceIDs.insert(source.id).inserted else { continue } + defer { refreshingSourceIDs.remove(source.id) } + lastAttempt[source.id] = Date() + failedSourceIDs.remove(source.id) + let fingerprint = MusicSourceSecurityRevision.scopedFingerprint(for: source) + let revision = preferenceRevision[source.id, default: 0] + let protectedAtStart = protectedSongID() + do { + switch source.type { + case .tingReader: + try await refreshTingReader( + source: source, + manual: manual, + fingerprint: fingerprint, + revision: revision, + protectedAtStart: protectedAtStart + ) + case .audiobookshelf: + try await refreshAudiobookshelf( + source: source, + manual: manual, + fingerprint: fingerprint, + revision: revision, + protectedAtStart: protectedAtStart + ) + default: + continue + } + } catch is CancellationError { + return + } catch { + failedSourceIDs.insert(source.id) + plog("Spoken-word server progress refresh failed (\(source.type.rawValue)): \(LogRedactionPolicy.errorSummary(error))") + } + } + } + + private func validatedCurrentSource( + id: String, + manual: Bool, + fingerprint: String, + revision: Int + ) -> MusicSource? { + guard !Task.isCancelled, + manual || (isEnabled(for: id) && preferenceRevision[id, default: 0] == revision), + let current = sources().first(where: { $0.id == id }), supportsSource(current), + MusicSourceSecurityRevision.scopedFingerprint(for: current) == fingerprint else { + return nil + } + return current + } + + private func refreshTingReader( + source: MusicSource, + manual: Bool, + fingerprint: String, + revision: Int, + protectedAtStart: String? + ) async throws { + let records = try await fetch(source) + guard let current = validatedCurrentSource( + id: source.id, + manual: manual, + fingerprint: fingerprint, + revision: revision + ) else { return } + // 曲库答不了这个源有哪些章节:这一轮什么也不对,也不算试过(不进冷却),曲库装好后的下一次照常对。 + guard let sourceSongs = songs(source.id) else { + lastAttempt[source.id] = nil + plog("Ting Reader progress refresh skipped: the library cannot list the source's chapters now") + return + } + let byChapter = Dictionary( + sourceSongs.compactMap { song -> (String, Song)? in + guard song.sourceID == source.id, + !current.excludedServerLibraryIDs.contains(song.serverLibraryID ?? ""), + let ref = TingReaderAPIProtocol.trackReference(from: song.filePath) else { return nil } + return (ref.chapterID, song) + }, uniquingKeysWith: { first, _ in first } + ) + var hasListeningProgress = false + for record in records { + guard let song = byChapter[record.chapterID], + TingReaderAPIProtocol.trackReference(from: song.filePath)?.bookID == record.bookID, + song.id != protectedAtStart, song.id != protectedSongID() else { continue } + let progress = record.progress + hasListeningProgress = true + if store.adoptServerProgress( + songID: song.id, position: progress.position, duration: progress.duration, + isFinished: progress.isFinished, updatedAt: progress.updatedAt + ) { + didAdopt(song) + } + } + store.persistLocally() + if hasListeningProgress { didFinishAdopting() } + } + + private func refreshAudiobookshelf( + source: MusicSource, + manual: Bool, + fingerprint: String, + revision: Int, + protectedAtStart: String? + ) async throws { + guard let fetchAudiobookshelf else { return } + guard let initialSongs = songs(source.id) else { + lastAttempt[source.id] = nil + plog("Audiobookshelf progress refresh skipped: the library cannot list the source's items now") + return + } + let candidatePaths = initialSongs.compactMap { song -> String? in + guard song.sourceID == source.id, + !source.excludedServerLibraryIDs.contains(song.serverLibraryID ?? ""), + AudiobookshelfAPIProtocol.trackReference(from: song.filePath) != nil else { return nil } + return song.filePath + } + guard !candidatePaths.isEmpty else { return } + let records = try await fetchAudiobookshelf(source, candidatePaths) + guard let current = validatedCurrentSource( + id: source.id, + manual: manual, + fingerprint: fingerprint, + revision: revision + ) else { return } + guard let latestSongs = songs(source.id) else { + lastAttempt[source.id] = nil + return + } + let byPath = Dictionary( + latestSongs.compactMap { song -> (String, Song)? in + guard song.sourceID == source.id, + !current.excludedServerLibraryIDs.contains(song.serverLibraryID ?? "") else { return nil } + return (song.filePath, song) + }, uniquingKeysWith: { first, _ in first } + ) + var hasListeningProgress = false + for progress in records { + guard let song = byPath[progress.songPath], + song.id != protectedAtStart, song.id != protectedSongID() else { continue } + hasListeningProgress = true + if store.adoptServerProgress( + songID: song.id, position: progress.position, duration: progress.duration, + isFinished: progress.isFinished, updatedAt: progress.updatedAt + ) { + didAdopt(song) + } + } + store.persistLocally() + if hasListeningProgress { didFinishAdopting() } + } +} diff --git a/Primuse/Services/Library/SpokenWordStore.swift b/Primuse/Services/Library/SpokenWordStore.swift index cc9b59330..13fbe3000 100644 --- a/Primuse/Services/Library/SpokenWordStore.swift +++ b/Primuse/Services/Library/SpokenWordStore.swift @@ -6,123 +6,6 @@ private let sharedClassificationSnapshotLock = OSAllocatedUnfairLock [MusicSource] - /// 这个源的歌。nil:此刻答不了(歌曲模型不在内存里),不是「一首都没有」。 - private let songs: (String) -> [Song]? - private let fetch: @MainActor (MusicSource) async throws -> [TingReaderListeningProgress] - private let protectedSongID: () -> String? - private let didAdopt: (Song) -> Void - /// 一轮读取确认了可用进度后,重新判断暂停中的播放器该接哪一章。 - private let didFinishAdopting: () -> Void - private var disabledSourceIDs: Set - private(set) var refreshingSourceIDs: Set = [] - private(set) var failedSourceIDs: Set = [] - @ObservationIgnored private var lastAttempt: [String: Date] = [:] - @ObservationIgnored private var preferenceRevision: [String: Int] = [:] - - init( - defaults: UserDefaults = .standard, - store: SpokenWordStore = .shared, - sources: @escaping () -> [MusicSource], - songs: @escaping (String) -> [Song]?, - fetch: @escaping @MainActor (MusicSource) async throws -> [TingReaderListeningProgress], - protectedSongID: @escaping () -> String?, - didAdopt: @escaping (Song) -> Void = { _ in }, - didFinishAdopting: @escaping () -> Void = {} - ) { - self.defaults = defaults - self.store = store - self.sources = sources - self.songs = songs - self.fetch = fetch - self.protectedSongID = protectedSongID - self.didAdopt = didAdopt - self.didFinishAdopting = didFinishAdopting - disabledSourceIDs = Set(defaults.stringArray(forKey: Self.defaultsKey) ?? []) - } - - var hasSources: Bool { sources().contains(where: Self.supports) } - - static func supports(_ source: MusicSource) -> Bool { - source.type == .tingReader && source.isEnabled && !source.isDeleted - } - - func isEnabled(for sourceID: String) -> Bool { !disabledSourceIDs.contains(sourceID) } - - func setEnabled(_ enabled: Bool, for sourceID: String) { - if enabled { disabledSourceIDs.remove(sourceID) } - else { disabledSourceIDs.insert(sourceID) } - preferenceRevision[sourceID, default: 0] += 1 - lastAttempt.removeValue(forKey: sourceID) - defaults.set(Array(disabledSourceIDs).sorted(), forKey: Self.defaultsKey) - } - - func refresh(sourceID: String? = nil, manual: Bool = false) async { - for source in sources() where Self.supports(source) && (sourceID == nil || source.id == sourceID) { - guard !Task.isCancelled else { return } - guard manual || isEnabled(for: source.id), - manual || lastAttempt[source.id].map({ Date().timeIntervalSince($0) >= Self.cooldown }) != false, - refreshingSourceIDs.insert(source.id).inserted else { continue } - defer { refreshingSourceIDs.remove(source.id) } - lastAttempt[source.id] = Date() - failedSourceIDs.remove(source.id) - let fingerprint = MusicSourceSecurityRevision.scopedFingerprint(for: source) - let revision = preferenceRevision[source.id, default: 0] - let protectedAtStart = protectedSongID() - do { - let records = try await fetch(source) - guard !Task.isCancelled, - manual || (isEnabled(for: source.id) && preferenceRevision[source.id, default: 0] == revision), - let current = sources().first(where: { $0.id == source.id }), Self.supports(current), - MusicSourceSecurityRevision.scopedFingerprint(for: current) == fingerprint else { continue } - // 曲库答不了这个源有哪些章节:这一轮什么也不对,也不算试过(不进冷却),曲库装好后的下一次照常对。 - guard let sourceSongs = songs(source.id) else { - lastAttempt[source.id] = nil - plog("Ting Reader progress refresh skipped: the library cannot list the source's chapters now") - continue - } - let byChapter = Dictionary( - sourceSongs.compactMap { song -> (String, Song)? in - guard song.sourceID == source.id, - !current.excludedServerLibraryIDs.contains(song.serverLibraryID ?? ""), - let ref = TingReaderAPIProtocol.trackReference(from: song.filePath) else { return nil } - return (ref.chapterID, song) - }, uniquingKeysWith: { first, _ in first } - ) - var hasListeningProgress = false - for record in records { - guard let song = byChapter[record.chapterID], - TingReaderAPIProtocol.trackReference(from: song.filePath)?.bookID == record.bookID, - song.id != protectedAtStart, song.id != protectedSongID() else { continue } - let progress = record.progress - hasListeningProgress = true - if store.adoptServerProgress( - songID: song.id, position: progress.position, duration: progress.duration, - isFinished: progress.isFinished, updatedAt: progress.updatedAt - ) { - didAdopt(song) - } - } - store.persistLocally() - if hasListeningProgress { didFinishAdopting() } - } catch is CancellationError { - return - } catch { - failedSourceIDs.insert(source.id) - plog("Ting Reader progress refresh failed: \(LogRedactionPolicy.errorSummary(error))") - } - } - } -} - /// Keeps the two things spoken-word listening needs that music does not: which /// items are spoken word, and where each one was left off. /// diff --git a/Primuse/Views/Mac/MacNowPlayingView.swift b/Primuse/Views/Mac/MacNowPlayingView.swift index beae90d05..edd468d49 100644 --- a/Primuse/Views/Mac/MacNowPlayingView.swift +++ b/Primuse/Views/Mac/MacNowPlayingView.swift @@ -670,7 +670,8 @@ struct MacNowPlayingView: View { RadioStationArtworkView( station: station, size: size, - cornerRadius: isWindowFullScreen ? 24 : 18 + cornerRadius: isWindowFullScreen ? 24 : 18, + liveArtworkURLString: player.radioNowPlayingArtworkURL ) .shadow(color: .black.opacity(0.30), radius: 28, y: 14) } diff --git a/Primuse/Views/NowPlaying/NowPlayingView.swift b/Primuse/Views/NowPlaying/NowPlayingView.swift index f9a0d3e87..e270f8796 100644 --- a/Primuse/Views/NowPlaying/NowPlayingView.swift +++ b/Primuse/Views/NowPlaying/NowPlayingView.swift @@ -6056,7 +6056,7 @@ struct NowPlayingView: View { // 内屏分屏半幅这类宽而矮的窗口会把底部控件顶出屏幕。 NowPlayingRadioArtworkCard(maximumSide: artworkSize, scale: scale) { side in if let station = player.currentRadioStation { - RadioStationArtworkView(station: station, size: side, cornerRadius: max(18, side * 0.06)) + RadioStationArtworkView(station: station, size: side, cornerRadius: max(18, side * 0.06), liveArtworkURLString: player.radioNowPlayingArtworkURL) } } .layoutPriority(1) @@ -6292,7 +6292,7 @@ struct NowPlayingView: View { private func liveRadioLandscapeLogoCard(size: CGFloat) -> some View { ZStack { if let station = player.currentRadioStation, size >= 48 { - RadioStationArtworkView(station: station, size: size, cornerRadius: 18) + RadioStationArtworkView(station: station, size: size, cornerRadius: 18, liveArtworkURLString: player.radioNowPlayingArtworkURL) .shadow(color: .black.opacity(0.28), radius: 20, y: 10) } } diff --git a/Primuse/Views/Radio/RadioStationDetailView.swift b/Primuse/Views/Radio/RadioStationDetailView.swift index c7502ca52..1f876cd98 100644 --- a/Primuse/Views/Radio/RadioStationDetailView.swift +++ b/Primuse/Views/Radio/RadioStationDetailView.swift @@ -425,7 +425,8 @@ struct RadioStationDetailView: View { } private func heardRow(_ entry: RadioHeardTitle) -> some View { - HStack(alignment: .firstTextBaseline, spacing: 12) { + let shareText = Self.copyText(for: entry) + return HStack(alignment: .firstTextBaseline, spacing: 12) { VStack(alignment: .leading, spacing: 2) { if let title = entry.title, let artist = entry.artist { Text(title) @@ -448,9 +449,36 @@ struct RadioStationDetailView: View { .foregroundStyle(.secondary) } .padding(.vertical, 10) + .contentShape(Rectangle()) + .contextMenu { + Button { + Self.copyToPasteboard(shareText) + } label: { + Label("copy_action", systemImage: "doc.on.doc") + } + ShareLink(item: shareText) { + Label("share", systemImage: "square.and.arrow.up") + } + } .accessibilityElement(children: .combine) } + private static func copyText(for entry: RadioHeardTitle) -> String { + if let artist = entry.artist, !artist.isEmpty, let title = entry.title, !title.isEmpty { + return "\(artist) - \(title)" + } + return entry.text + } + + private static func copyToPasteboard(_ text: String) { + #if os(iOS) + UIPasteboard.general.string = text + #elseif os(macOS) + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + #endif + } + /// 今天的只写时刻;更早的带上日期。 private static func timeText(_ date: Date) -> String { if Calendar.current.isDateInToday(date) { @@ -459,3 +487,39 @@ struct RadioStationDetailView: View { return date.formatted(.dateTime.month(.abbreviated).day().hour().minute()) } } + +/// 电台台标视图;直播流携带当前曲目封面链接(如 ICY `StreamArtwork`)时优先平滑叠加显示,加载中或失败时保留台标兜底。 +struct RadioStationArtworkView: View { + let station: RadioStation + var size: CGFloat + var cornerRadius: CGFloat + var liveArtworkURLString: String? = nil + + private var validLiveURL: URL? { + guard let raw = liveArtworkURLString?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty, + let url = URL(string: raw), + let scheme = url.scheme?.lowercased(), + scheme == "https" || scheme == "http", + url.host?.isEmpty == false else { return nil } + return url + } + + var body: some View { + ZStack { + RadioStationArtworkContent(station: station, decodeSize: size) + if let validLiveURL { + AsyncImage(url: validLiveURL) { phase in + if case .success(let image) = phase { + image + .resizable() + .scaledToFill() + } + } + .id(validLiveURL) + } + } + .frame(width: size, height: size) + .clipShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)) + } +} diff --git a/Primuse/Views/Radio/RadioStationsView.swift b/Primuse/Views/Radio/RadioStationsView.swift index 7a535cf39..7189cbad6 100644 --- a/Primuse/Views/Radio/RadioStationsView.swift +++ b/Primuse/Views/Radio/RadioStationsView.swift @@ -1784,18 +1784,6 @@ struct RadioStationArtworkContent: View { } } -struct RadioStationArtworkView: View { - let station: RadioStation - var size: CGFloat - var cornerRadius: CGFloat - - var body: some View { - RadioStationArtworkContent(station: station, decodeSize: size) - .frame(width: size, height: size) - .clipShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)) - } -} - /// 无台标时用当前主题色构成单色信号场,避免固定紫蓝色从整套外观里跳出来。 /// 同心环只承担“广播信号”的识别,不参与播放状态表达。 struct RadioStationPlaceholderArtwork: View { diff --git a/PrimuseTV/Model/TVStore+SleepTimer.swift b/PrimuseTV/Model/TVStore+SleepTimer.swift new file mode 100644 index 000000000..289914608 --- /dev/null +++ b/PrimuseTV/Model/TVStore+SleepTimer.swift @@ -0,0 +1,95 @@ +import Foundation +import PrimuseKit + +extension TVStore { + /// 睡眠定时:关→15→30→60→关 分钟。到点淡出后停止播放。 + func cycleSleepTimer() { + let presets = [0, 15, 30, 60] + let cur = presets.firstIndex(of: sleepTimerMinutes) ?? 0 + setSleepTimer(minutes: presets[(cur + 1) % presets.count]) + } + + /// 按分钟定时;0 关闭。与「本集结束 / 整本听完 / 本章结束」互斥;最后 30 秒复用 `SleepFadePolicy` 平滑淡出。 + func setSleepTimer(minutes: Int) { + sleepTimerTask?.cancel() + sleepTimerTask = nil + engine.setMixVolume(1) + + let clampedMinutes = max(0, minutes) + guard clampedMinutes > 0 else { + applySleepTimerState(minutes: 0, endDate: nil, stopAfterItemID: nil) + return + } + let endDate = Date().addingTimeInterval(Double(clampedMinutes) * 60) + applySleepTimerState(minutes: clampedMinutes, endDate: endDate, stopAfterItemID: nil) + + sleepTimerTask = Task { [weak self] in + guard let self else { return } + let fadeStart = max(0, endDate.timeIntervalSinceNow - SleepFadePolicy.fadeDuration) + do { + try await Task.sleep(for: .seconds(fadeStart)) + } catch { + self.engine.setMixVolume(1) + return + } + guard !Task.isCancelled else { + self.engine.setMixVolume(1) + return + } + + let finishesTrackEnabled = UserDefaults.standard.bool( + forKey: SleepTimerSchedulePolicy.finishesTrackPreferenceKey + ) + let shouldWaitForTrackEnd = { (delay: TimeInterval) -> Bool in + guard self.hasNowPlaying, self.isPlaying else { return false } + return SleepTimerSchedulePolicy.shouldFinishTrack( + isEnabled: finishesTrackEnabled, + isMusic: !self.currentItemIsSpokenWord, + isLiveRadio: self.isLiveRadio, + trackDuration: self.duration, + position: self.engine.currentTime + max(0, delay) + ) + } + + if shouldWaitForTrackEnd(endDate.timeIntervalSinceNow) { + do { + try await Task.sleep(for: .seconds(max(0, endDate.timeIntervalSinceNow))) + } catch { + return + } + guard !Task.isCancelled else { return } + if shouldWaitForTrackEnd(0) { + plog("🎧 TV sleep: timer ran out, letting '\(self.nowPlaying.title)' finish") + self.sleepTimerTask = nil + self.applySleepTimerState(minutes: 0, endDate: nil, stopAfterItemID: self.nowPlaying.songID) + return + } + self.sleepTimerTask = nil + self.applySleepTimerState(minutes: 0, endDate: nil, stopAfterItemID: nil) + self.pausePlayback() + return + } + + while true { + let remaining = endDate.timeIntervalSinceNow + if remaining <= 0 { break } + self.engine.setMixVolume(SleepFadePolicy.volume(remaining: remaining)) + do { + try await Task.sleep(for: .milliseconds(250)) + } catch { + self.engine.setMixVolume(1) + return + } + } + self.sleepTimerTask = nil + self.applySleepTimerState(minutes: 0, endDate: nil, stopAfterItemID: nil) + // 走 pausePlayback 而不是 engine.pause():电台要先断掉重连任务和解析任务。 + self.pausePlayback() + self.engine.setMixVolume(1) + } + } + + func cancelSleepTimer() { + setSleepTimer(minutes: 0) + } +} diff --git a/PrimuseTV/Model/TVStore.swift b/PrimuseTV/Model/TVStore.swift index b701332a4..08599c49d 100644 --- a/PrimuseTV/Model/TVStore.swift +++ b/PrimuseTV/Model/TVStore.swift @@ -1332,7 +1332,7 @@ final class TVStore { @ObservationIgnored private var currentSpokenWordIntroOutro: SpokenWordIntroOutro? /// 片尾已经跳过的那一条:每条只跳一次。 @ObservationIgnored private var serverOutroHandledSongID: String? - @ObservationIgnored private var sleepWorkItem: DispatchWorkItem? + @ObservationIgnored var sleepTimerTask: Task? /// 正在播的这一条所在的书:播放页每拍都要问。分书按(书、分类修订、曲库修订)缓存, /// 只是存了进度就只重读进度,不重新分书(见 `SpokenWordCurrentBookCache`)。 @ObservationIgnored private var spokenWordBookCache = SpokenWordCurrentBookCache() @@ -6158,7 +6158,7 @@ extension TVStore { } } - private func pausePlayback() { + func pausePlayback() { endSourceQuotaSkip(showingReason: true) if isMedleyActive { engine.pause(); return } radioReconnectTask?.cancel() @@ -6943,10 +6943,9 @@ extension TVStore { func setSpokenWordRateForCurrentBook(_ rate: Float) { guard let bookID = currentSpokenWordBookID else { return } - SpokenWordStore.shared.setPlaybackRate( - SpokenWordPlaybackRatePolicy.storedBookRate(for: rate, globalSpokenWordRate: 1), - forBookID: bookID - ) + // 电视没有全局听书倍速设置,显式保存本条目倍速,避免把手机同步过来的 1.0× 覆盖清成 nil。 + let clamped = SpokenWordPlaybackRatePolicy.clamped(rate) + SpokenWordStore.shared.setPlaybackRate(clamped, forBookID: bookID) engine.setSpokenWordRate(Double(spokenWordRate(forBookID: bookID))) } @@ -7747,54 +7746,13 @@ extension TVStore { } } - /// 睡眠定时:关→15→30→60→关 分钟。到点停止播放。 - func cycleSleepTimer() { - let presets = [0, 15, 30, 60] - let cur = presets.firstIndex(of: sleepTimerMinutes) ?? 0 - setSleepTimer(minutes: presets[(cur + 1) % presets.count]) - } - - /// 按分钟定时;0 关闭。与「本集结束 / 整本听完」互斥。 - func setSleepTimer(minutes: Int) { + func applySleepTimerState(minutes: Int, endDate: Date?, stopAfterItemID: String?) { selectedChapterSleep = nil - sleepWorkItem?.cancel() - sleepWorkItem = nil - sleepStopAfterItemID = nil + sleepStopAfterItemID = stopAfterItemID sleepStopAfterBookID = nil sleepStopAfterChapter = nil - sleepTimerMinutes = max(0, minutes) - guard sleepTimerMinutes > 0 else { - sleepTimerEndDate = nil - return - } - sleepTimerEndDate = Date().addingTimeInterval(Double(sleepTimerMinutes) * 60) - // 走 pausePlayback 而不是 engine.pause():电台要先断掉重连任务和 - // 解析任务,并在 .loading 阶段用 stop(),否则到点后又被拉起来接着播。 - let work = DispatchWorkItem { [weak self] in - guard let self else { return } - self.sleepTimerMinutes = 0 - self.sleepTimerEndDate = nil - // 开了「计时结束时播完当前这首」:这首还剩不多就改成曲终停止。 - if self.hasNowPlaying, self.isPlaying, - SleepTimerSchedulePolicy.shouldFinishTrack( - isEnabled: UserDefaults.standard.bool(forKey: SleepTimerSchedulePolicy.finishesTrackPreferenceKey), - isMusic: !self.currentItemIsSpokenWord, - isLiveRadio: self.isLiveRadio, - trackDuration: self.duration, - position: self.engine.currentTime - ) { - plog("🎧 TV sleep: timer ran out, letting '\(self.nowPlaying.title)' finish") - self.sleepStopAfterItemID = self.nowPlaying.songID - return - } - self.pausePlayback() - } - sleepWorkItem = work - DispatchQueue.main.asyncAfter(deadline: .now() + Double(sleepTimerMinutes) * 60, execute: work) - } - - func cancelSleepTimer() { - setSleepTimer(minutes: 0) + sleepTimerMinutes = minutes + sleepTimerEndDate = endDate } /// 音乐:当前这首播完就停(和有声内容的「本集结束」用同一把锁)。 diff --git a/PrimuseTV/Views/TVSpokenWordNowPlaying.swift b/PrimuseTV/Views/TVSpokenWordNowPlaying.swift index f3a80a1ee..4224930de 100644 --- a/PrimuseTV/Views/TVSpokenWordNowPlaying.swift +++ b/PrimuseTV/Views/TVSpokenWordNowPlaying.swift @@ -171,11 +171,20 @@ struct TVSpokenWordContentsColumn: View { @Environment(TVStore.self) private var store var onInteraction: () -> Void = {} - private enum Tab: Hashable { case contents, bookmarks } + private enum Tab: Hashable { case contents, notes, bookmarks } @State private var tab: Tab = .contents @State private var bookmarkFeedback = 0 @State private var chapterSong: Song? + private var showsPodcastNotesTab: Bool { + store.currentItemIsPodcast && ( + store.currentPodcastEpisodeID != nil + || store.libraryPodcastShowNotes != nil + || !store.podcastUpNext.isEmpty + || !store.queueUpNextIDs.isEmpty + ) + } + var body: some View { let spokenStore = SpokenWordStore.shared // 读这几张表,位置 / 听完 / 书签一变右栏就跟着刷新。 @@ -183,24 +192,37 @@ struct TVSpokenWordContentsColumn: View { _ = spokenStore.finishedAt.count _ = spokenStore.bookmarks.count let entries = store.currentBookBookmarkEntries + let showsNotes = showsPodcastNotesTab + let activeTab: Tab = (tab == .notes && !showsNotes) ? .contents : tab return VStack(alignment: .leading, spacing: 18) { HStack(spacing: 16) { TVPillButton( title: String(localized: "spoken_word_contents_title"), systemImage: "list.bullet", - style: tab == .contents ? .solid : .glass, - isSelected: tab == .contents + style: activeTab == .contents ? .solid : .glass, + isSelected: activeTab == .contents ) { onInteraction() tab = .contents } + if showsNotes { + TVPillButton( + title: String(localized: "podcast_show_notes"), + systemImage: "doc.text", + style: activeTab == .notes ? .solid : .glass, + isSelected: activeTab == .notes + ) { + onInteraction() + tab = .notes + } + } TVPillButton( title: entries.isEmpty ? String(localized: "spoken_word_bookmarks_title") : String(format: String(localized: "spoken_word_bookmarks_count_format"), entries.count), systemImage: "bookmark", - style: tab == .bookmarks ? .solid : .glass, - isSelected: tab == .bookmarks + style: activeTab == .bookmarks ? .solid : .glass, + isSelected: activeTab == .bookmarks ) { onInteraction() tab = .bookmarks @@ -209,10 +231,10 @@ struct TVSpokenWordContentsColumn: View { } .focusSection() - if let song = store.chapterGenerationSong { + if activeTab == .contents, let song = store.chapterGenerationSong { Button { chapterSong = song } label: { Label("spoken_chapters_manage", systemImage: "list.bullet.rectangle") } } - switch tab { + switch activeTab { case .contents: if let summary = TVSpokenWordText.bookSummary(store) { Text(summary) @@ -223,6 +245,8 @@ struct TVSpokenWordContentsColumn: View { .padding(.horizontal, 16) } contentsList + case .notes: + TVPodcastNowPlayingColumn(onInteraction: onInteraction) case .bookmarks: bookmarksList(entries) } diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index bfa32bb28..f5840bc29 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -432,4 +432,72 @@ final class ListeningSpacesReliabilityTests: XCTestCase { XCTAssertEqual(chapters.map(\.title), ["Intro", "Main Discussion", "Wrap Up"]) XCTAssertEqual(chapters.map(\.startTime), [0, 600, 1500]) } + + func testServerProgressSyncCoordinatorAdoptsAudiobookshelfProgressAndProtectsPlayingItem() async throws { + let suiteName = "primuse.abs-sync-test.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + let storeDir = FileManager.default.temporaryDirectory + .appendingPathComponent("abs-sync-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: storeDir, withIntermediateDirectories: true) + cleanups.append { + defaults.removePersistentDomain(forName: suiteName) + try? FileManager.default.removeItem(at: storeDir) + } + let store = SpokenWordStore(storeURL: storeDir.appendingPathComponent("spoken.json")) + let absSource = MusicSource( + id: "abs-src-\(UUID().uuidString)", + name: "My ABS", + type: .audiobookshelf, + host: "abs.example.com" + ) + let path1 = AudiobookshelfAPIProtocol.trackPath(itemID: "li_1", kind: .file(ino: "1"), fileExtension: "m4b") + let path2 = AudiobookshelfAPIProtocol.trackPath(itemID: "li_2", kind: .file(ino: "2"), fileExtension: "m4b") + let song1 = Song( + id: "abs-song-1-\(UUID().uuidString)", + title: "Book 1", + duration: 3600, + fileFormat: .m4a, + filePath: path1, + sourceID: absSource.id, + genre: "Audiobook" + ) + let song2 = Song( + id: "abs-song-2-\(UUID().uuidString)", + title: "Book 2", + duration: 3600, + fileFormat: .m4a, + filePath: path2, + sourceID: absSource.id, + genre: "Audiobook" + ) + + var adoptedIDs: [String] = [] + var finishCount = 0 + let stamp = Date(timeIntervalSince1970: 1_730_000_000) + let coordinator = TingReaderProgressSyncCoordinator( + defaults: defaults, + store: store, + sources: { [absSource] }, + songs: { $0 == absSource.id ? [song1, song2] : [] }, + fetch: { _ in [] }, + fetchAudiobookshelf: { _, paths in + XCTAssertEqual(Set(paths), Set([path1, path2])) + return [ + ServerListeningProgress(songPath: path1, position: 420, duration: 3600, isFinished: false, updatedAt: stamp), + ServerListeningProgress(songPath: path2, position: 900, duration: 3600, isFinished: false, updatedAt: stamp) + ] + }, + protectedSongID: { song2.id }, + didAdopt: { adoptedIDs.append($0.id) }, + didFinishAdopting: { finishCount += 1 } + ) + + XCTAssertTrue(coordinator.hasSources) + await coordinator.refresh(manual: true) + + XCTAssertEqual(adoptedIDs, [song1.id]) + XCTAssertEqual(finishCount, 1) + XCTAssertEqual(store.position(forSongID: song1.id)?.position ?? -1, 420, accuracy: 0.5) + XCTAssertNil(store.position(forSongID: song2.id)) + } } diff --git a/project.yml b/project.yml index deedc72e4..2ecb8ef17 100644 --- a/project.yml +++ b/project.yml @@ -871,6 +871,7 @@ targets: # 有声内容的判定与收听位置。MusicLibrary 靠它把有声书从音乐聚合里分出来, # 电视端的曲库是同一份代码, 少了它编不过。 - path: Primuse/Services/Library/SpokenWordStore.swift + - path: Primuse/Services/Library/ServerSpokenWordProgressSyncCoordinator.swift - path: Primuse/Services/Library/SongPlaybackRangeStore.swift - path: Primuse/Services/Library/SmartPlaylistEngine.swift - path: Primuse/Services/Library/SmartPlaylistEngine+Catalog.swift From f5d46d5cf418b59fa0e5f2c4d0bab710fd7469db Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 20:40:48 -0500 Subject: [PATCH 08/15] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E6=92=AD=E5=AE=A2?= =?UTF-8?q?=E4=BF=9D=E7=95=99=E6=9C=80=E8=BF=91=20N=20=E9=9B=86=E3=80=81?= =?UTF-8?q?=E8=8A=82=E7=9B=AE=E5=86=85=E4=B8=8E=E8=B7=A8=E8=8A=82=E7=9B=AE?= =?UTF-8?q?=E5=8D=95=E9=9B=86=E6=90=9C=E7=B4=A2=E3=80=815=20=E5=88=86?= =?UTF-8?q?=E9=92=9F=E7=89=87=E5=A4=B4=E7=89=87=E5=B0=BE=E5=8F=8A=E6=8C=89?= =?UTF-8?q?=E8=8A=82=E7=9B=AE=E9=9F=B3=E6=95=88=E5=85=A5=E5=8F=A3=20refs?= =?UTF-8?q?=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Resources/ar.lproj/Localizable.strings | 4 + .../Resources/de.lproj/Localizable.strings | 4 + .../Resources/en.lproj/Localizable.strings | 4 + .../Resources/es-MX.lproj/Localizable.strings | 4 + .../Resources/fr.lproj/Localizable.strings | 4 + .../Resources/hi.lproj/Localizable.strings | 4 + .../Resources/ja.lproj/Localizable.strings | 4 + .../Resources/ko.lproj/Localizable.strings | 4 + .../Resources/pl.lproj/Localizable.strings | 4 + .../Resources/pt-BR.lproj/Localizable.strings | 4 + .../Resources/ru.lproj/Localizable.strings | 4 + .../Resources/th.lproj/Localizable.strings | 4 + .../Resources/tr.lproj/Localizable.strings | 4 + .../Resources/uk.lproj/Localizable.strings | 4 + .../zh-Hans.lproj/Localizable.strings | 4 + .../zh-Hant.lproj/Localizable.strings | 4 + Primuse/Services/Podcast/PodcastStore.swift | 14 +-- .../Podcast/PodcastEpisodeDetailView.swift | 17 ++- .../Views/Podcast/PodcastShowDetailView.swift | 110 +++++++++++++++--- .../Podcast/PodcastEpisode+Song.swift | 19 +++ .../Podcast/PodcastLibraryPolicy.swift | 50 +++++++- .../PrimuseKit/Podcast/PodcastModels.swift | 78 ++++++++++--- .../PodcastKeepLatestPolicyTests.swift | 2 +- .../Podcast/PodcastShowNotesTests.swift | 96 +++++++++++++++ 24 files changed, 410 insertions(+), 40 deletions(-) diff --git a/Primuse/Resources/ar.lproj/Localizable.strings b/Primuse/Resources/ar.lproj/Localizable.strings index 3dd36ac76..ee0cb1092 100644 --- a/Primuse/Resources/ar.lproj/Localizable.strings +++ b/Primuse/Resources/ar.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "الهز للتمديد"; "sleep_timer_shake_to_extend_desc" = "خلال آخر 5 دقائق أو أثناء خفت الصوت، هزّ iPhone برفق لإضافة 15 دقيقة."; "chapter_open_link" = "فتح رابط الفصل"; +"podcast_keep_episodes" = "الاحتفاظ بالتنزيلات"; +"podcast_keep_episodes_all" = "كل الحلقات"; +"podcast_keep_episodes_count_format" = "أحدث %lld"; +"podcast_search_episodes_prompt" = "البحث في الحلقات"; diff --git a/Primuse/Resources/de.lproj/Localizable.strings b/Primuse/Resources/de.lproj/Localizable.strings index 3e3154399..0bee6eb1d 100644 --- a/Primuse/Resources/de.lproj/Localizable.strings +++ b/Primuse/Resources/de.lproj/Localizable.strings @@ -8467,3 +8467,7 @@ "sleep_timer_shake_to_extend" = "Schütteln zum Verlängern"; "sleep_timer_shake_to_extend_desc" = "In den letzten 5 Minuten oder beim Ausblenden kurz schütteln, um um 15 Minuten zu verlängern."; "chapter_open_link" = "Kapitellink öffnen"; +"podcast_keep_episodes" = "Downloads behalten"; +"podcast_keep_episodes_all" = "Alle Folgen"; +"podcast_keep_episodes_count_format" = "Neueste %lld"; +"podcast_search_episodes_prompt" = "Folgen durchsuchen"; diff --git a/Primuse/Resources/en.lproj/Localizable.strings b/Primuse/Resources/en.lproj/Localizable.strings index 19b0b3718..cadac9ebc 100644 --- a/Primuse/Resources/en.lproj/Localizable.strings +++ b/Primuse/Resources/en.lproj/Localizable.strings @@ -8229,3 +8229,7 @@ "sleep_timer_shake_to_extend" = "Shake to Extend"; "sleep_timer_shake_to_extend_desc" = "During the final 5 minutes or fade-out, gently shake your iPhone to add 15 minutes."; "chapter_open_link" = "Open Chapter Link"; +"podcast_keep_episodes" = "Keep Downloads"; +"podcast_keep_episodes_all" = "All Episodes"; +"podcast_keep_episodes_count_format" = "Latest %lld"; +"podcast_search_episodes_prompt" = "Search episodes"; diff --git a/Primuse/Resources/es-MX.lproj/Localizable.strings b/Primuse/Resources/es-MX.lproj/Localizable.strings index 8737ff36b..528c7d8a1 100644 --- a/Primuse/Resources/es-MX.lproj/Localizable.strings +++ b/Primuse/Resources/es-MX.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "Agitar para extender"; "sleep_timer_shake_to_extend_desc" = "Durante los últimos 5 minutos o el desvanecimiento, agita suavemente el iPhone para sumar 15 minutos."; "chapter_open_link" = "Abrir enlace del capítulo"; +"podcast_keep_episodes" = "Conservar descargas"; +"podcast_keep_episodes_all" = "Todos los episodios"; +"podcast_keep_episodes_count_format" = "Últimos %lld"; +"podcast_search_episodes_prompt" = "Buscar episodios"; diff --git a/Primuse/Resources/fr.lproj/Localizable.strings b/Primuse/Resources/fr.lproj/Localizable.strings index 8685c34c8..36df585a3 100644 --- a/Primuse/Resources/fr.lproj/Localizable.strings +++ b/Primuse/Resources/fr.lproj/Localizable.strings @@ -8467,3 +8467,7 @@ "sleep_timer_shake_to_extend" = "Secouer pour prolonger"; "sleep_timer_shake_to_extend_desc" = "Durant les 5 dernières minutes ou le fondu, secouez doucement l’iPhone pour ajouter 15 minutes."; "chapter_open_link" = "Ouvrir le lien du chapitre"; +"podcast_keep_episodes" = "Conserver les téléchargements"; +"podcast_keep_episodes_all" = "Tous les épisodes"; +"podcast_keep_episodes_count_format" = "%lld derniers"; +"podcast_search_episodes_prompt" = "Rechercher des épisodes"; diff --git a/Primuse/Resources/hi.lproj/Localizable.strings b/Primuse/Resources/hi.lproj/Localizable.strings index 8f4423ab3..87b470f50 100644 --- a/Primuse/Resources/hi.lproj/Localizable.strings +++ b/Primuse/Resources/hi.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "बढ़ाने के लिए हिलाएँ"; "sleep_timer_shake_to_extend_desc" = "अंतिम 5 मिनट या फ़ेड-आउट के दौरान 15 मिनट जोड़ने के लिए iPhone को हल्का हिलाएँ।"; "chapter_open_link" = "अध्याय लिंक खोलें"; +"podcast_keep_episodes" = "डाउनलोड सहेजें"; +"podcast_keep_episodes_all" = "सभी एपिसोड"; +"podcast_keep_episodes_count_format" = "नवीनतम %lld"; +"podcast_search_episodes_prompt" = "एपिसोड खोजें"; diff --git a/Primuse/Resources/ja.lproj/Localizable.strings b/Primuse/Resources/ja.lproj/Localizable.strings index 86af3b8ec..dff419cbd 100644 --- a/Primuse/Resources/ja.lproj/Localizable.strings +++ b/Primuse/Resources/ja.lproj/Localizable.strings @@ -8468,3 +8468,7 @@ "sleep_timer_shake_to_extend" = "シェイクで延長"; "sleep_timer_shake_to_extend_desc" = "残り5分以内またはフェードアウト中にiPhoneを軽く振ると15分延長されます。"; "chapter_open_link" = "チャプターリンクを開く"; +"podcast_keep_episodes" = "ダウンロード保持数"; +"podcast_keep_episodes_all" = "すべてのエピソード"; +"podcast_keep_episodes_count_format" = "最新 %lld 件"; +"podcast_search_episodes_prompt" = "エピソードを検索"; diff --git a/Primuse/Resources/ko.lproj/Localizable.strings b/Primuse/Resources/ko.lproj/Localizable.strings index a524d0c7e..d1a6cc832 100644 --- a/Primuse/Resources/ko.lproj/Localizable.strings +++ b/Primuse/Resources/ko.lproj/Localizable.strings @@ -8467,3 +8467,7 @@ "sleep_timer_shake_to_extend" = "흔들어서 연장"; "sleep_timer_shake_to_extend_desc" = "종료 5분 전 또는 페이드아웃 중에 iPhone을 가볍게 흔들면 15분 연장됩니다."; "chapter_open_link" = "챕터 링크 열기"; +"podcast_keep_episodes" = "다운로드 보관"; +"podcast_keep_episodes_all" = "모든 에피소드"; +"podcast_keep_episodes_count_format" = "최신 %lld개"; +"podcast_search_episodes_prompt" = "에피소드 검색"; diff --git a/Primuse/Resources/pl.lproj/Localizable.strings b/Primuse/Resources/pl.lproj/Localizable.strings index 370afeb43..4e71c4a6f 100644 --- a/Primuse/Resources/pl.lproj/Localizable.strings +++ b/Primuse/Resources/pl.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "Potrząśnij, aby przedłużyć"; "sleep_timer_shake_to_extend_desc" = "W ciągu ostatnich 5 minut lub wyciszania lekko potrząśnij iPhonem, aby dodać 15 minut."; "chapter_open_link" = "Otwórz link rozdziału"; +"podcast_keep_episodes" = "Zachowaj pobrane"; +"podcast_keep_episodes_all" = "Wszystkie odcinki"; +"podcast_keep_episodes_count_format" = "Ostatnie %lld"; +"podcast_search_episodes_prompt" = "Szukaj odcinków"; diff --git a/Primuse/Resources/pt-BR.lproj/Localizable.strings b/Primuse/Resources/pt-BR.lproj/Localizable.strings index 582aba6b3..87a5d25bc 100644 --- a/Primuse/Resources/pt-BR.lproj/Localizable.strings +++ b/Primuse/Resources/pt-BR.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "Agitar para estender"; "sleep_timer_shake_to_extend_desc" = "Nos últimos 5 minutos ou durante o fade-out, agite suavemente o iPhone para adicionar 15 minutos."; "chapter_open_link" = "Abrir link do capítulo"; +"podcast_keep_episodes" = "Manter downloads"; +"podcast_keep_episodes_all" = "Todos os episódios"; +"podcast_keep_episodes_count_format" = "Últimos %lld"; +"podcast_search_episodes_prompt" = "Buscar episódios"; diff --git a/Primuse/Resources/ru.lproj/Localizable.strings b/Primuse/Resources/ru.lproj/Localizable.strings index b1477c6f6..cf16712b6 100644 --- a/Primuse/Resources/ru.lproj/Localizable.strings +++ b/Primuse/Resources/ru.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "Встряхнуть для продления"; "sleep_timer_shake_to_extend_desc" = "В последние 5 минут или при затухании слегка встряхните iPhone, чтобы добавить 15 минут."; "chapter_open_link" = "Открыть ссылку главы"; +"podcast_keep_episodes" = "Хранить загрузки"; +"podcast_keep_episodes_all" = "Все выпуски"; +"podcast_keep_episodes_count_format" = "Последние %lld"; +"podcast_search_episodes_prompt" = "Поиск выпусков"; diff --git a/Primuse/Resources/th.lproj/Localizable.strings b/Primuse/Resources/th.lproj/Localizable.strings index a8f4ea40e..2b329f3ab 100644 --- a/Primuse/Resources/th.lproj/Localizable.strings +++ b/Primuse/Resources/th.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "เขย่าเพื่อต่อเวลา"; "sleep_timer_shake_to_extend_desc" = "ในช่วง 5 นาทีสุดท้ายหรือขณะค่อยๆ ลดเสียง เขย่า iPhone เบาๆ เพื่อเพิ่มอีก 15 นาที"; "chapter_open_link" = "เปิดลิงก์บท"; +"podcast_keep_episodes" = "เก็บไฟล์ที่ดาวน์โหลด"; +"podcast_keep_episodes_all" = "ทุกตอน"; +"podcast_keep_episodes_count_format" = "%lld ตอนล่าสุด"; +"podcast_search_episodes_prompt" = "ค้นหาตอน"; diff --git a/Primuse/Resources/tr.lproj/Localizable.strings b/Primuse/Resources/tr.lproj/Localizable.strings index 41b467bdd..631a985b1 100644 --- a/Primuse/Resources/tr.lproj/Localizable.strings +++ b/Primuse/Resources/tr.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "Uzatmak İçin Salla"; "sleep_timer_shake_to_extend_desc" = "Son 5 dakikada veya ses kısılırken 15 dakika eklemek için iPhone'u hafifçe sallayın."; "chapter_open_link" = "Bölüm Bağlantısını Aç"; +"podcast_keep_episodes" = "İndirilenleri Sakla"; +"podcast_keep_episodes_all" = "Tüm Bölümler"; +"podcast_keep_episodes_count_format" = "Son %lld"; +"podcast_search_episodes_prompt" = "Bölümlerde ara"; diff --git a/Primuse/Resources/uk.lproj/Localizable.strings b/Primuse/Resources/uk.lproj/Localizable.strings index ad8988495..d402effc9 100644 --- a/Primuse/Resources/uk.lproj/Localizable.strings +++ b/Primuse/Resources/uk.lproj/Localizable.strings @@ -8373,3 +8373,7 @@ "sleep_timer_shake_to_extend" = "Струсити для продовження"; "sleep_timer_shake_to_extend_desc" = "Протягом останніх 5 хвилин або затухання злегка струсіть iPhone, щоб додати 15 хвилин."; "chapter_open_link" = "Відкрити посилання розділу"; +"podcast_keep_episodes" = "Зберігати завантаження"; +"podcast_keep_episodes_all" = "Усі випуски"; +"podcast_keep_episodes_count_format" = "Останні %lld"; +"podcast_search_episodes_prompt" = "Пошук випусків"; diff --git a/Primuse/Resources/zh-Hans.lproj/Localizable.strings b/Primuse/Resources/zh-Hans.lproj/Localizable.strings index 6a591e9cc..96ad803c5 100644 --- a/Primuse/Resources/zh-Hans.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hans.lproj/Localizable.strings @@ -8560,3 +8560,7 @@ "sleep_timer_shake_to_extend" = "摇一摇延长定时"; "sleep_timer_shake_to_extend_desc" = "在倒计时最后 5 分钟或渐弱期间轻摇手机,自动延长 15 分钟。"; "chapter_open_link" = "打开章节链接"; +"podcast_keep_episodes" = "保留已下载单集"; +"podcast_keep_episodes_all" = "全部单集"; +"podcast_keep_episodes_count_format" = "最近 %lld 集"; +"podcast_search_episodes_prompt" = "搜索单集"; diff --git a/Primuse/Resources/zh-Hant.lproj/Localizable.strings b/Primuse/Resources/zh-Hant.lproj/Localizable.strings index e143da7d3..b38fcab9b 100644 --- a/Primuse/Resources/zh-Hant.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hant.lproj/Localizable.strings @@ -8444,3 +8444,7 @@ "sleep_timer_shake_to_extend" = "搖一搖延長定時"; "sleep_timer_shake_to_extend_desc" = "在倒數最後 5 分鐘或淡出期間輕搖手機,自動延長 15 分鐘。"; "chapter_open_link" = "開啟章節連結"; +"podcast_keep_episodes" = "保留已下載單集"; +"podcast_keep_episodes_all" = "全部單集"; +"podcast_keep_episodes_count_format" = "最近 %lld 集"; +"podcast_search_episodes_prompt" = "搜尋單集"; diff --git a/Primuse/Services/Podcast/PodcastStore.swift b/Primuse/Services/Podcast/PodcastStore.swift index 00ee20e75..9ccc1d1fd 100644 --- a/Primuse/Services/Podcast/PodcastStore.swift +++ b/Primuse/Services/Podcast/PodcastStore.swift @@ -267,8 +267,8 @@ extension PodcastStore { func latestEpisodes(limit: Int, includeFinished: Bool = false) -> [PodcastEpisode] { latestEpisodes(limit: limit, filter: includeFinished ? .all : .unplayed) } - func latestEpisodes(limit: Int, filter: PodcastEpisodeFilter) -> [PodcastEpisode] { - PodcastEpisodeListPolicy.latest(episodesByShow: visibleEpisodesByShow, state: state(for:), filter: filter, limit: limit) + func latestEpisodes(limit: Int, filter: PodcastEpisodeFilter, query: String = "") -> [PodcastEpisode] { + PodcastEpisodeListPolicy.latest(episodesByShow: visibleEpisodesByShow, state: state(for:), filter: filter, query: query, showTitle: { self.show(id: $0)?.title }, limit: limit) } private var visibleEpisodesByShow: [String: [PodcastEpisode]] { @@ -421,12 +421,12 @@ extension PodcastStore { /// 改一档节目的设置或水位线。算用户的决定:推 iCloud。 func updateDefinition(_ showID: String, mutate: (inout PodcastShow) -> Void) { guard let index = subscribedShows.firstIndex(where: { $0.id == showID }) else { return } - let wasKeepLatest = subscribedShows[index].settings.keepOnlyLatestEpisode + let previousKeepCount = subscribedShows[index].settings.keepLatestEpisodeCount var show = subscribedShows[index] mutate(&show) show.definitionModifiedAt = Date() subscribedShows[index] = show - if !wasKeepLatest, show.settings.keepOnlyLatestEpisode { + if PodcastKeepLatestPolicy.tightensRetention(from: previousKeepCount, to: show.settings.keepLatestEpisodeCount) { _ = enforceKeepOnlyLatest(at: index) } markDirty(showID: nil, showsChanged: true) @@ -753,9 +753,9 @@ extension PodcastStore { /// 这档节目现在有多少较早单集的下载(不分手动自动;最新一集、正在放的、听到一半的不算)。 /// 设置页在用户打开「仅保留最新一集」时拿它决定要不要问一句「已有的这些也删掉吗」。 - func olderDownloadCountForKeepLatest(showID: String) -> Int { - guard var show = show(id: showID) else { return 0 } - show.settings.keepOnlyLatestEpisode = true + func olderDownloadCountForKeepLatest(showID: String, limit: Int = 1) -> Int { + guard var show = show(id: showID), limit > 0 else { return 0 } + show.settings.keepLatestEpisodeCount = limit return keepLatestPlan(for: show, includesManualDownloads: true).downloadEpisodeIDsToRemove.count } diff --git a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift index b74c4449b..8bd3404f0 100644 --- a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift +++ b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift @@ -333,6 +333,7 @@ private struct PodcastEpisodeActions: View { struct PodcastEpisodeFeedView: View { @Environment(AudioPlayerService.self) private var player @AppStorage("primuse.podcast.feed.filter") private var filterRawValue = PodcastEpisodeFilter.unplayed.rawValue + @State private var searchText = "" @State private var pushedEpisodeID: String? @State private var pushedShowID: String? @@ -340,11 +341,20 @@ struct PodcastEpisodeFeedView: View { private var filter: PodcastEpisodeFilter { PodcastEpisodeFilter(rawValue: filterRawValue) ?? .unplayed } var body: some View { - let episodes = store.latestEpisodes(limit: 300, filter: filter) + let episodes = store.latestEpisodes(limit: 300, filter: filter, query: searchText) List { #if os(macOS) - PodcastInlineBackButton() - .listRowSeparator(.hidden) + HStack(spacing: 12) { + PodcastInlineBackButton() + Spacer() + MacSheetSearchField( + text: $searchText, + prompt: Text("podcast_search_episodes_prompt"), + tint: ListeningSpace.podcast.tint + ) + .frame(maxWidth: 260) + } + .listRowSeparator(.hidden) #endif Section { Picker("podcast_filter", selection: $filterRawValue) { @@ -416,6 +426,7 @@ struct PodcastEpisodeFeedView: View { #if os(iOS) .navigationTitle("podcast_latest_episodes") .navigationBarTitleDisplayMode(.inline) + .searchable(text: $searchText, prompt: Text("podcast_search_episodes_prompt")) #endif .refreshable { await store.refreshAll() } .navigationDestination(item: $pushedEpisodeID) { id in diff --git a/Primuse/Views/Podcast/PodcastShowDetailView.swift b/Primuse/Views/Podcast/PodcastShowDetailView.swift index 2fb905d00..23af65df8 100644 --- a/Primuse/Views/Podcast/PodcastShowDetailView.swift +++ b/Primuse/Views/Podcast/PodcastShowDetailView.swift @@ -20,6 +20,7 @@ struct PodcastShowDetailView: View { @State private var loadError: String? @State private var pendingInsecureHost: String? @State private var filter: PodcastEpisodeFilter = .all + @State private var searchText = "" @State private var expandsSummary = false @State private var showsSettings = false @State private var shareSelection: ListeningShareSelection? @@ -91,13 +92,26 @@ struct PodcastShowDetailView: View { private func content(_ show: PodcastShow) -> some View { let all = store.episodes(forShowID: show.id) let ordered = PodcastEpisodeListPolicy.ordered(all, order: show.effectiveEpisodeOrder) - let visible = ordered.filter { filter.includes(store.state(for: $0)) } + let tokens = PodcastEpisodeSearchPolicy.tokens(from: searchText) + let visible = ordered.filter { episode in + filter.includes(store.state(for: episode)) + && (tokens.isEmpty || PodcastEpisodeSearchPolicy.matches(episode, showTitle: show.title, tokens: tokens)) + } let groups = PodcastEpisodeListPolicy.seasonGroups(visible, order: show.effectiveEpisodeOrder) return List { Section { #if os(macOS) - PodcastInlineBackButton() - .listRowSeparator(.hidden) + HStack(spacing: 12) { + PodcastInlineBackButton() + Spacer() + MacSheetSearchField( + text: $searchText, + prompt: Text("podcast_search_episodes_prompt"), + tint: tint + ) + .frame(maxWidth: 260) + } + .listRowSeparator(.hidden) #endif header(show, episodes: all) .listRowSeparator(.hidden) @@ -135,6 +149,7 @@ struct PodcastShowDetailView: View { .podcastPushedPageChrome() #if os(iOS) .navigationTitle(show.title) + .searchable(text: $searchText, prompt: Text("podcast_search_episodes_prompt")) #endif .refreshable { if store.isSubscribed(show.id) { await store.refresh(showID: show.id) } @@ -537,14 +552,19 @@ enum PodcastClipboard { struct PodcastShowSettingsView: View { let showID: String + @Environment(AudioPlayerService.self) private var player @Environment(\.dismiss) private var dismiss - /// 刚打开「仅保留最新一集」、这档节目又有较早单集的下载:问一次要不要现在删掉。 + /// 收紧「保留最近 N 集」、这档节目又有较早单集的下载:问一次要不要现在删掉。 @State private var asksToRemoveOlderDownloads = false + @State private var showsAudioEffects = false private var store: PodcastStore { PodcastStore.shared } var body: some View { + let _ = SpokenWordStore.shared.bookRates.count + let _ = SpokenWordAudioEffectsPreferences.shared.revision Form { if let show = store.show(id: showID) { + let scopeID = PodcastPlaybackSong.bookID(for: show) Section { Picker("podcast_episode_order", selection: binding(\.episodeOrder, show: show)) { Text(show.isSerial ? "podcast_order_auto_serial" : "podcast_order_auto_episodic").tag(PodcastEpisodeOrder?.none) @@ -552,14 +572,29 @@ struct PodcastShowSettingsView: View { Text("podcast_order_oldest").tag(PodcastEpisodeOrder?.some(.oldestFirst)) } Toggle("podcast_auto_download", isOn: binding(\.autoDownloadsNewEpisodes, show: show)) - Toggle("podcast_keep_only_latest_episode", isOn: keepOnlyLatestBinding(show: show)) - .accessibilityIdentifier("podcast.show.keepOnlyLatest") + Picker("podcast_keep_episodes", selection: keepLatestCountBinding(show: show)) { + ForEach(PodcastShowSettings.keepLatestChoices, id: \.self) { count in + Text(keepLatestLabel(count)).tag(count) + } + } + .accessibilityIdentifier("podcast.show.keepOnlyLatest") } footer: { VStack(alignment: .leading, spacing: 6) { Text("podcast_auto_download_footer") Text("podcast_keep_latest_footer") } } + Section { + Button { + showsAudioEffects = true + } label: { + LabeledContent("spoken_word_speed_short") { + Text(audioEffectsSummary(forScopeID: scopeID)) + .foregroundStyle(.secondary) + } + } + .tint(.primary) + } Section { Picker("podcast_skip_intro", selection: binding(\.skipIntroSeconds, show: show)) { ForEach(PodcastShowSettings.skipChoices, id: \.self) { seconds in @@ -586,6 +621,18 @@ struct PodcastShowSettingsView: View { } } .formStyle(.grouped) + .sheet(isPresented: $showsAudioEffects) { + if let show = store.show(id: showID) { + SpokenWordAudioEffectsSheet( + targetBookID: PodcastPlaybackSong.bookID(for: show), + isPodcastContext: true + ) + .presentationDetents([.medium, .large]) + #if os(macOS) + .frame(minWidth: 380, minHeight: 420) + #endif + } + } .alert("podcast_keep_latest_confirm_title", isPresented: $asksToRemoveOlderDownloads) { Button("podcast_keep_latest_confirm_remove", role: .destructive) { store.removeOlderDownloadsForKeepLatest(showID: showID) @@ -614,21 +661,58 @@ struct PodcastShowSettingsView: View { #endif } + private func keepLatestLabel(_ count: Int?) -> String { + guard let count else { return String(localized: "podcast_keep_episodes_all") } + return String(format: String(localized: "podcast_keep_episodes_count_format"), count) + } + + private func audioEffectsSummary(forScopeID scopeID: String) -> String { + let rate = SpokenWordPlaybackRatePolicy.bookRate( + stored: SpokenWordStore.shared.playbackRate(forBookID: scopeID), + globalSpokenWordRate: player.playbackSettings.spokenWordPlaybackRate + ) + var parts = [SpokenWordPlaybackRatePolicy.label(for: rate)] + let override = SpokenWordAudioEffectsPreferences.shared.override(forScopeID: scopeID) + let globalSmart = SpokenWordAudioEffectsPolicy.globalSmartSpeedLevel( + enabled: player.playbackSettings.spokenWordSmartSpeedEnabled, + preferredLevel: player.playbackSettings.spokenWordSmartSpeedLevel + ) + let smartLevel = SpokenWordAudioEffectsPolicy.effectiveSmartSpeedLevel( + space: .podcast, + override: override, + globalLevel: globalSmart + ) + if smartLevel != .off { + parts.append(smartLevel.localizedTitle) + } + let voiceBoost = SpokenWordAudioEffectsPolicy.effectiveVoiceBoost( + space: .podcast, + override: override, + globalSpokenWordEnabled: player.playbackSettings.spokenWordVoiceBoostEnabled + ) + if voiceBoost { + parts.append(String(localized: "spoken_word_voice_boost")) + } + return parts.joined(separator: " · ") + } + private func secondsLabel(_ seconds: Int) -> String { seconds == 0 ? String(localized: "podcast_skip_off") : String(format: String(localized: "podcast_seconds_format %lld"), seconds) } - /// 打开开关本身只清自动下载的旧集。这档节目若还有别的较早下载(手动下的、升级前下的),问一次要不要一起删; - /// 不问就删会删掉用户特意留的,不问也不删则开关看起来没起作用。 - private func keepOnlyLatestBinding(show: PodcastShow) -> Binding { - let base = binding(\.keepOnlyLatestEpisode, show: show) + /// 收紧保留数量本身只清自动下载的旧集。这档节目若还有别的较早下载(手动下的、升级前下的),问一次要不要一起删。 + private func keepLatestCountBinding(show: PodcastShow) -> Binding { + let base = binding(\.keepLatestEpisodeCount, show: show) return Binding( get: { base.wrappedValue }, - set: { isOn in - base.wrappedValue = isOn - if isOn, store.olderDownloadCountForKeepLatest(showID: showID) > 0 { + set: { newCount in + let oldCount = base.wrappedValue + base.wrappedValue = newCount + if let newCount, + PodcastKeepLatestPolicy.tightensRetention(from: oldCount, to: newCount), + store.olderDownloadCountForKeepLatest(showID: showID, limit: newCount) > 0 { asksToRemoveOlderDownloads = true } } diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastEpisode+Song.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastEpisode+Song.swift index 9bdf2e6fa..35023ebb2 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastEpisode+Song.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastEpisode+Song.swift @@ -37,6 +37,25 @@ public enum PodcastPlaybackSong { isEpisode(song) && song?.mvPath?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false } + /// Stable spoken-word book/scope ID matching what `AudioPlayerService.spokenWordBookID(for:)` + /// produces for any episode of `show`. + public static func bookID(for show: PodcastShow) -> String { + let author = show.author ?? show.title + let probe = Song( + id: show.id, + title: show.title, + albumTitle: show.title, + artistName: author, + albumArtistName: author, + duration: 0, + fileFormat: .mp3, + filePath: show.feedURL.absoluteString, + sourceID: sourceID, + genre: genre + ) + return SpokenWordBookGrouping.bookID(for: SpokenWordBookItem(song: probe)) + } + public static func hasSeparateVideo(_ song: Song?) -> Bool { guard let song, isVideoEpisode(song) else { return false } return song.mvPath != song.filePath diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift index 5f4f472e0..a5c5c7b47 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift @@ -172,6 +172,44 @@ public enum PodcastEpisodeFilter: String, CaseIterable, Sendable { } /// 列表排序、分季、跨节目的「最新单集」、播完接着放哪几集。都是纯函数,界面和播放器共用。 +public enum PodcastEpisodeSearchPolicy { + public static func tokens(from query: String) -> [String] { + query + .trimmingCharacters(in: .whitespacesAndNewlines) + .split(whereSeparator: \.isWhitespace) + .map { normalized(String($0)) } + .filter { !$0.isEmpty } + } + + public static func matches( + _ episode: PodcastEpisode, + showTitle: String? = nil, + query: String + ) -> Bool { + let tokens = tokens(from: query) + guard !tokens.isEmpty else { return true } + return matches(episode, showTitle: showTitle, tokens: tokens) + } + + public static func matches( + _ episode: PodcastEpisode, + showTitle: String? = nil, + tokens: [String] + ) -> Bool { + guard !tokens.isEmpty else { return true } + let primary = normalized([episode.title, episode.subtitle, showTitle].compactMap { $0 }.joined(separator: " ")) + if tokens.allSatisfy({ primary.contains($0) }) { return true } + // 仅在标题与副标题未全部命中时提取节目说明摘要,避免遍历整库时对每集重复做 HTML 清洗。 + guard let summary = PodcastShowNotes.plainSummary(episode.showNotes, limit: 400) else { return false } + let combined = primary + " " + normalized(summary) + return tokens.allSatisfy { combined.contains($0) } + } + + private static func normalized(_ text: String) -> String { + text.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current) + } +} + public enum PodcastEpisodeListPolicy { /// `episodes` 约定是从新到旧(`PodcastFeedMerge` 的输出)。 public static func ordered(_ episodes: [PodcastEpisode], order: PodcastEpisodeOrder) -> [PodcastEpisode] { @@ -244,22 +282,30 @@ public enum PodcastEpisodeListPolicy { ) } - /// 所有订阅里符合筛选条件且最近发布的单集,从新到旧。先筛选再截断,较早下载或听到一半的单集不会被新集挤掉。 + /// 所有订阅里符合筛选条件且最近发布的单集,从新到旧。先筛选与搜索再截断,较早下载、听到一半或命中关键词的单集不会被新集挤掉。 public static func latest( episodesByShow: [String: [PodcastEpisode]], state: (PodcastEpisode) -> PodcastEpisodeState, filter: PodcastEpisodeFilter, + query: String = "", + showTitle: (String) -> String? = { _ in nil }, since: Date? = nil, limit: Int ) -> [PodcastEpisode] { guard limit > 0 else { return [] } + let tokens = PodcastEpisodeSearchPolicy.tokens(from: query) var candidates: [PodcastEpisode] = [] - for episodes in episodesByShow.values { + for (showID, episodes) in episodesByShow { + let resolvedShowTitle = tokens.isEmpty ? nil : showTitle(showID) var taken = 0 for episode in episodes { guard taken < limit else { break } if let since, let published = episode.publishedAt, published < since { break } guard filter.includes(state(episode)) else { continue } + if !tokens.isEmpty, + !PodcastEpisodeSearchPolicy.matches(episode, showTitle: resolvedShowTitle, tokens: tokens) { + continue + } candidates.append(episode) taken += 1 } diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift index e4b9c626f..727e057f7 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastModels.swift @@ -244,8 +244,19 @@ public struct PodcastShowSettings: Codable, Hashable, Sendable { public var episodeOrder: PodcastEpisodeOrder? /// 刷新到新单集时自动下载。 public var autoDownloadsNewEpisodes: Bool - /// 仅保留最新一集未播与本地下载,更早的单集自动标为已播并清理下载。 - public var keepOnlyLatestEpisode: Bool + /// 自动下载最多保留最近几集(`nil` = 全部保留,`1` = 仅保留最新一集,其余为最近 N 集)。 + public var keepLatestEpisodeCount: Int? + /// 兼容旧接口:是否启用了按数量保留最新单集(写 true 等价保留最新 1 集,写 false 等价全部保留)。 + public var keepOnlyLatestEpisode: Bool { + get { keepLatestEpisodeCount != nil } + set { + if newValue { + keepLatestEpisodeCount = keepLatestEpisodeCount ?? 1 + } else { + keepLatestEpisodeCount = nil + } + } + } /// 从这一档的每一集开头跳过多少秒(片头)。 public var skipIntroSeconds: Int /// 离结尾还剩多少秒就当播完(片尾)。 @@ -255,59 +266,95 @@ public struct PodcastShowSettings: Codable, Hashable, Sendable { episodeOrder: PodcastEpisodeOrder? = nil, autoDownloadsNewEpisodes: Bool = false, keepOnlyLatestEpisode: Bool = false, + keepLatestEpisodeCount: Int? = nil, skipIntroSeconds: Int = 0, skipOutroSeconds: Int = 0 ) { self.episodeOrder = episodeOrder self.autoDownloadsNewEpisodes = autoDownloadsNewEpisodes - self.keepOnlyLatestEpisode = keepOnlyLatestEpisode + if let count = keepLatestEpisodeCount, count > 0 { + self.keepLatestEpisodeCount = count + } else { + self.keepLatestEpisodeCount = keepOnlyLatestEpisode ? 1 : nil + } self.skipIntroSeconds = skipIntroSeconds self.skipOutroSeconds = skipOutroSeconds } private enum CodingKeys: String, CodingKey { - case episodeOrder, autoDownloadsNewEpisodes, keepOnlyLatestEpisode, skipIntroSeconds, skipOutroSeconds + case episodeOrder, autoDownloadsNewEpisodes, keepOnlyLatestEpisode, keepLatestEpisodeCount, skipIntroSeconds, skipOutroSeconds } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) episodeOrder = try c.decodeIfPresent(PodcastEpisodeOrder.self, forKey: .episodeOrder) autoDownloadsNewEpisodes = try c.decodeIfPresent(Bool.self, forKey: .autoDownloadsNewEpisodes) ?? false - keepOnlyLatestEpisode = try c.decodeIfPresent(Bool.self, forKey: .keepOnlyLatestEpisode) ?? false + if let count = try c.decodeIfPresent(Int.self, forKey: .keepLatestEpisodeCount), count > 0 { + keepLatestEpisodeCount = count + } else { + let legacy = try c.decodeIfPresent(Bool.self, forKey: .keepOnlyLatestEpisode) ?? false + keepLatestEpisodeCount = legacy ? 1 : nil + } skipIntroSeconds = try c.decodeIfPresent(Int.self, forKey: .skipIntroSeconds) ?? 0 skipOutroSeconds = try c.decodeIfPresent(Int.self, forKey: .skipOutroSeconds) ?? 0 } - /// 片头/片尾可选的秒数,设置页的菜单用。 - public static let skipChoices = [0, 5, 10, 15, 20, 30, 45, 60, 90, 120] + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encodeIfPresent(episodeOrder, forKey: .episodeOrder) + try c.encode(autoDownloadsNewEpisodes, forKey: .autoDownloadsNewEpisodes) + try c.encode(keepOnlyLatestEpisode, forKey: .keepOnlyLatestEpisode) + try c.encodeIfPresent(keepLatestEpisodeCount, forKey: .keepLatestEpisodeCount) + try c.encode(skipIntroSeconds, forKey: .skipIntroSeconds) + try c.encode(skipOutroSeconds, forKey: .skipOutroSeconds) + } + + /// 保留最近 N 集的可选档位(nil 表示不限数量)。 + public static let keepLatestChoices: [Int?] = [nil, 1, 2, 3, 5, 10] + /// 片头/片尾可选的秒数(最高 5 分钟),设置页的菜单用。 + public static let skipChoices = [0, 5, 10, 15, 20, 30, 45, 60, 90, 120, 150, 180, 240, 300] } -/// 单档节目「仅保留最新一集」的纯清理策略。 +/// 单档节目「保留最近 N 集」的纯清理策略。 /// 这个开关只限制自动下载:不标已播、不动播放位置、不动已播水位线(这些会同步到别的设备, /// 是用户对收听状态的决定)。只删「自动下载」下来的旧集;用户手动下载的、正在放的、 /// 放到一半(有已存位置)的不碰。 public enum PodcastKeepLatestPolicy { public struct Plan: Equatable, Sendable { public var keptEpisodeID: String? + public var keptEpisodeIDs: Set public var downloadEpisodeIDsToRemove: Set public var autoDownloadEpisodeIDs: Set public init( keptEpisodeID: String? = nil, + keptEpisodeIDs: Set = [], downloadEpisodeIDsToRemove: Set = [], autoDownloadEpisodeIDs: Set = [] ) { self.keptEpisodeID = keptEpisodeID + if keptEpisodeIDs.isEmpty, let keptEpisodeID { + self.keptEpisodeIDs = [keptEpisodeID] + } else { + self.keptEpisodeIDs = keptEpisodeIDs + } self.downloadEpisodeIDsToRemove = downloadEpisodeIDsToRemove self.autoDownloadEpisodeIDs = autoDownloadEpisodeIDs } } + /// 两个保留上限相比,新上限是否比旧上限更严格(用于决定改设置后是否立刻清理较早的自动下载)。 + public static func tightensRetention(from oldCount: Int?, to newCount: Int?) -> Bool { + guard let newCount, newCount > 0 else { return false } + guard let oldCount, oldCount > 0 else { return true } + return newCount < oldCount + } + /// - Parameters: /// - downloadedOrQueuedEpisodeIDs: 已下载或排队中的单集。 /// - automaticDownloadEpisodeIDs: 其中由「自动下载」产生的。没有这条记录的(含升级前下的)一律按手动算,保留。 /// - inProgressEpisodeIDs: 有已存播放位置的单集,保留。 - /// - includesManualDownloads: 用户在打开开关时确认过「把这档节目已有的较早下载也删掉」的那一次传 true: + /// - includesManualDownloads: 用户在收紧保留数量时确认过「把这档节目已有的较早下载也删掉」的那一次传 true: /// 较早的下载不分手动自动都删(正在放的、听到一半的照旧保留)。平时为 false。 public static func evaluate( show: PodcastShow, @@ -319,7 +366,7 @@ public enum PodcastKeepLatestPolicy { addedEpisodeIDs: Set = [], nowPlayingEpisodeID: String? = nil ) -> Plan { - guard show.settings.keepOnlyLatestEpisode else { + guard let keepCount = show.settings.keepLatestEpisodeCount, keepCount > 0 else { return Plan(autoDownloadEpisodeIDs: addedEpisodeIDs) } guard !episodes.isEmpty else { return Plan() } @@ -332,15 +379,18 @@ public enum PodcastKeepLatestPolicy { } }.map(\.element) - let kept = ordered.first(where: { $0.kind != .trailer }) ?? ordered[0] + let nonTrailers = ordered.filter { $0.kind != .trailer } + let keptList = Array((nonTrailers.isEmpty ? ordered : nonTrailers).prefix(keepCount)) + let keptIDs = Set(keptList.map(\.id)) let downloadsToRemove = downloadedOrQueuedEpisodeIDs.filter { id in - id != kept.id && id != nowPlayingEpisodeID + !keptIDs.contains(id) && id != nowPlayingEpisodeID && (includesManualDownloads || automaticDownloadEpisodeIDs.contains(id)) && !inProgressEpisodeIDs.contains(id) } - let autoDownload: Set = addedEpisodeIDs.contains(kept.id) ? [kept.id] : [] + let autoDownload = addedEpisodeIDs.intersection(keptIDs) return Plan( - keptEpisodeID: kept.id, + keptEpisodeID: keptList.first?.id, + keptEpisodeIDs: keptIDs, downloadEpisodeIDsToRemove: downloadsToRemove, autoDownloadEpisodeIDs: autoDownload ) diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastKeepLatestPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastKeepLatestPolicyTests.swift index e867dec0b..03d7098ed 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastKeepLatestPolicyTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastKeepLatestPolicyTests.swift @@ -222,6 +222,6 @@ struct PodcastKeepLatestPolicyTests { automaticDownloadEpisodeIDs: ["podcast:ep1"] ) #expect(Mirror(reflecting: plan).children.map { $0.label ?? "" }.sorted() - == ["autoDownloadEpisodeIDs", "downloadEpisodeIDsToRemove", "keptEpisodeID"]) + == ["autoDownloadEpisodeIDs", "downloadEpisodeIDsToRemove", "keptEpisodeID", "keptEpisodeIDs"]) } } diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift index 6de0b3a22..e8957c9cf 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift @@ -44,4 +44,100 @@ struct PodcastShowNotesChaptersTests { #expect(PodcastShowNotes.chapters(from: "05:00 Only one timestamp", duration: 1800).isEmpty) #expect(PodcastShowNotes.chapters(from: "No timestamps at all", duration: 1800).isEmpty) } + + @Test("Keep-Last-N retains latest N non-trailer episodes and stays Codable backwards compatible") + func keepLastNPolicyAndBackwardsCompatibility() throws { + // Legacy Bool JSON decodes to count 1; new count encodes both count and Bool. + let legacyJSON = #"{"keepOnlyLatestEpisode":true,"autoDownloadsNewEpisodes":true}"#.data(using: .utf8)! + let decodedLegacy = try JSONDecoder().decode(PodcastShowSettings.self, from: legacyJSON) + #expect(decodedLegacy.keepLatestEpisodeCount == 1) + #expect(decodedLegacy.keepOnlyLatestEpisode == true) + + let multiSettings = PodcastShowSettings(autoDownloadsNewEpisodes: true, keepLatestEpisodeCount: 3) + let encoded = try JSONEncoder().encode(multiSettings) + let decodedMulti = try JSONDecoder().decode(PodcastShowSettings.self, from: encoded) + #expect(decodedMulti.keepLatestEpisodeCount == 3) + #expect(decodedMulti.keepOnlyLatestEpisode == true) + #expect(PodcastShowSettings.skipChoices.contains(300)) + + #expect(PodcastKeepLatestPolicy.tightensRetention(from: nil, to: 3)) + #expect(PodcastKeepLatestPolicy.tightensRetention(from: 5, to: 2)) + #expect(!PodcastKeepLatestPolicy.tightensRetention(from: 2, to: 5)) + #expect(!PodcastKeepLatestPolicy.tightensRetention(from: 2, to: nil)) + + let baseDate = Date(timeIntervalSince1970: 1_730_000_000) + let show = PodcastShow( + id: "show-k", + feedURL: URL(string: "https://example.com/feed.xml")!, + title: "Tech Show", + author: "Host", + subscribedAt: baseDate, + settings: PodcastShowSettings(keepLatestEpisodeCount: 2) + ) + let episodes = (0..<4).map { idx in + PodcastEpisode( + id: "ep-\(idx)", + showID: show.id, + guid: "g-\(idx)", + title: "Episode \(idx)", + publishedAt: baseDate.addingTimeInterval(TimeInterval(-idx * 3600)), + enclosureURL: URL(string: "https://example.com/ep-\(idx).mp3")!, + firstSeenAt: baseDate + ) + } + let plan = PodcastKeepLatestPolicy.evaluate( + show: show, + episodes: episodes, + downloadedOrQueuedEpisodeIDs: Set(episodes.map(\.id)), + automaticDownloadEpisodeIDs: Set(episodes.map(\.id)), + inProgressEpisodeIDs: ["ep-3"], + addedEpisodeIDs: ["ep-0", "ep-1", "ep-2"] + ) + #expect(plan.keptEpisodeID == "ep-0") + #expect(plan.keptEpisodeIDs == ["ep-0", "ep-1"]) + #expect(plan.downloadEpisodeIDsToRemove == ["ep-2"]) // ep-3 is in progress so protected + #expect(plan.autoDownloadEpisodeIDs == ["ep-0", "ep-1"]) + + // PodcastPlaybackSong.bookID(for:) matches SpokenWordBookGrouping.bookID(for: episode song). + let epSong = PodcastPlaybackSong.song(for: episodes[0], show: show) + #expect(PodcastPlaybackSong.bookID(for: show) == SpokenWordBookGrouping.bookID(for: SpokenWordBookItem(song: epSong))) + } + + @Test("Episode search matches multi-token queries across title, show title, and show notes before limit") + func episodeSearchMatchesAcrossFieldsBeforeLimit() { + let baseDate = Date(timeIntervalSince1970: 1_730_000_000) + let ep1 = PodcastEpisode( + id: "s-1", + showID: "show-a", + guid: "g1", + title: "Swift 6 Concurrency", + showNotes: "

Deep dive into actors and sendable checking.

", + publishedAt: baseDate, + enclosureURL: URL(string: "https://example.com/1.mp3")!, + firstSeenAt: baseDate + ) + let ep2 = PodcastEpisode( + id: "s-2", + showID: "show-a", + guid: "g2", + title: "Quarterly News", + showNotes: "

Talking about CoreAudio and spatial DSP.

", + publishedAt: baseDate.addingTimeInterval(-3600), + enclosureURL: URL(string: "https://example.com/2.mp3")!, + firstSeenAt: baseDate + ) + #expect(PodcastEpisodeSearchPolicy.matches(ep1, showTitle: "Compiler Weekly", query: "compiler actors")) + #expect(!PodcastEpisodeSearchPolicy.matches(ep1, showTitle: "Compiler Weekly", query: "coreaudio")) + #expect(PodcastEpisodeSearchPolicy.matches(ep2, showTitle: "Compiler Weekly", query: "coreaudio dsp")) + + let results = PodcastEpisodeListPolicy.latest( + episodesByShow: ["show-a": [ep1, ep2]], + state: { _ in .untouched }, + filter: .all, + query: "coreaudio", + showTitle: { _ in "Compiler Weekly" }, + limit: 1 + ) + #expect(results.map(\.id) == ["s-2"]) + } } From 1ad3d3ef9e300ce2beff822631cb7acb8da1a9a3 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 20:55:15 -0500 Subject: [PATCH 09/15] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E7=9B=B4=E6=92=AD?= =?UTF-8?q?=E7=94=B5=E5=8F=B0=E5=8D=A1=E9=A1=BF=E7=9C=8B=E9=97=A8=E7=8B=97?= =?UTF-8?q?=E4=B8=8E=E6=96=AD=E7=BD=91=E6=81=A2=E5=A4=8D=E5=8D=B3=E6=97=B6?= =?UTF-8?q?=E9=87=8D=E8=BF=9E=EF=BC=8C=E5=B9=B6=E6=94=AF=E6=8C=81=E6=92=AD?= =?UTF-8?q?=E5=AE=A2/=E6=9C=89=E5=A3=B0=E4=B9=A6=E4=B9=A6=E7=AD=BE?= =?UTF-8?q?=E4=B8=8E=E7=94=B5=E5=8F=B0=E5=8E=86=E5=8F=B2=20Markdown=20?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 4 + .../Audio/AudioPlayerService+Radio.swift | 91 ++++++++++++++++-- .../Radio/RadioPlaybackController.swift | 37 +++++++- .../Views/NowPlaying/ChapterListView.swift | 27 ++++++ .../Views/Radio/RadioStationDetailView.swift | 13 +++ .../Radio/RadioPlaybackPolicy.swift | 21 +++++ .../SpokenWord/ListeningNotesExporter.swift | 92 +++++++++++++++++++ .../Radio/RadioPlaybackPolicyTests.swift | 36 ++++++++ .../ListeningNotesExporterTests.swift | 53 +++++++++++ .../ListeningSpacesReliabilityTests.swift | 27 ++++++ 10 files changed, 391 insertions(+), 10 deletions(-) create mode 100644 PrimuseKit/Sources/PrimuseKit/SpokenWord/ListeningNotesExporter.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/SpokenWord/ListeningNotesExporterTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index 17cafb36f..b73f311e3 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -2218,6 +2218,7 @@ A5BBF5A5AB2A64A236235F3E /* SemanticAlbumResultCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69918F7E72B36379DC66865F /* SemanticAlbumResultCard.swift */; }; A5C2B802243EEA2162C949F1 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4D5D8BD40FCC0AA7011B551B /* Assets.xcassets */; }; A5DD3D4EAED83CA8302E3E9B /* LibrarySnapshotWriteFenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4893010C0775637C1121FB9 /* LibrarySnapshotWriteFenceTests.swift */; }; + A5FE4AF91BAC16523C6CEAEC /* ListeningNotesExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A095EC17A110856B477D934 /* ListeningNotesExporter.swift */; }; A5FFE4BC3301E365837F8BD2 /* BoundedAsyncChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DCCA5E6AE09D02992FDF3A5 /* BoundedAsyncChannel.swift */; }; A60575D5BCDE298CBD867678 /* SingleSongScrapeGatePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41A32079C53F50ACB8EAC429 /* SingleSongScrapeGatePolicy.swift */; }; A606B82534BA1607CE951D17 /* ReleaseDateLibraryView+Catalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60757F24DAB272A25A5DFBCC /* ReleaseDateLibraryView+Catalog.swift */; }; @@ -5220,6 +5221,7 @@ 99915C129D240493EF357305 /* AudioChannelConversionPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioChannelConversionPolicy.swift; sourceTree = ""; }; 99EFC98501CD6AA2D5515B66 /* KeepAlbumsAsMasteredRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeepAlbumsAsMasteredRow.swift; sourceTree = ""; }; 9A0009FEE3F7B9452AFE010B /* SubsonicPlaylistCreateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubsonicPlaylistCreateTests.swift; sourceTree = ""; }; + 9A095EC17A110856B477D934 /* ListeningNotesExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListeningNotesExporter.swift; sourceTree = ""; }; 9A14533AEA2998D9938AB997 /* MetadataTagRereadQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MetadataTagRereadQueue.swift; sourceTree = ""; }; 9A58DEFC03CD2898D68E1ECD /* RecentPlaybackHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecentPlaybackHistory.swift; sourceTree = ""; }; 9A731E59355B56771A9016F8 /* MacImmersiveEffectPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacImmersiveEffectPicker.swift; sourceTree = ""; }; @@ -7591,6 +7593,7 @@ isa = PBXGroup; children = ( 45D63F1E85E4889572BF0485 /* AudiobookOfflinePolicy.swift */, + 9A095EC17A110856B477D934 /* ListeningNotesExporter.swift */, A030D8AD71D4A5246B0645C8 /* SpokenChapterImport.swift */, 2CC0AAFC72677216495BC44E /* SpokenTranscriptImport.swift */, F23E2B9031979010BC0EE0DF /* SpokenTranscriptSources.swift */, @@ -10710,6 +10713,7 @@ 0D19694FB93F362590F506CA /* ListeningIntentRanking.swift in Sources */, 85AE66E564BD7A271234DC62 /* ListeningIntentShelf.swift in Sources */, 37D320455BB09ACAAAFD7909 /* ListeningMood.swift in Sources */, + A5FE4AF91BAC16523C6CEAEC /* ListeningNotesExporter.swift in Sources */, 4F383624377880621793D9B3 /* ListeningProfile.swift in Sources */, E485580DE8D88F39A4F2F0F6 /* ListeningRecap.swift in Sources */, 1A21CCE0B8669EAE338BAEDD /* ListeningScene.swift in Sources */, diff --git a/Primuse/Services/Audio/AudioPlayerService+Radio.swift b/Primuse/Services/Audio/AudioPlayerService+Radio.swift index 5c3cc056e..3eaff8810 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Radio.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Radio.swift @@ -594,22 +594,30 @@ extension AudioPlayerService { updatePlaybackState() } - private func scheduleRadioReconnect(station: RadioStation, playID id: UUID) { + private func scheduleRadioReconnect(station: RadioStation, playID id: UUID, immediate: Bool = false) { radioReconnectTask?.cancel() - radioReconnectAttempt += 1 - let delay = min(pow(2, Double(max(0, radioReconnectAttempt - 1))), 15) + if immediate { + radioReconnectAttempt = 0 + } else { + radioReconnectAttempt += 1 + } + let delay: Double = immediate ? 0 : min(pow(2, Double(max(0, radioReconnectAttempt - 1))), 15) isLoading = true + RadioNetworkRecoveryObserver.shared.start(for: self) radioReconnectTask = Task { @MainActor [weak self] in - do { - try await Task.sleep(for: .seconds(delay)) - } catch { - return + if delay > 0 { + do { + try await Task.sleep(for: .seconds(delay)) + } catch { + return + } } guard let self, self.playID == id, self.currentRadioStation?.id == station.id, self.interruptionResumePolicy.playbackIsIntended, !self.interruptionResumePolicy.isAwaitingInterruptionEnd else { return } + self.radioReconnectTask = nil if station.requiresSourceStreamResolution { do { self.radioResolvedStreamURL = try await self.resolveRadioStreamURL( @@ -633,7 +641,27 @@ extension AudioPlayerService { } } + @discardableResult + func handleRadioNetworkRecoveryIfNeeded(isNetworkReachable: Bool = NetworkMonitor.shared.isReachable) -> Bool { + guard let station = currentRadioStation, + let id = playID, + RadioStallWatchdogPolicy.shouldTriggerImmediateReconnectOnNetworkReachability( + isLiveRadio: isLiveRadio, + isNetworkReachable: isNetworkReachable, + playbackIntended: interruptionResumePolicy.playbackIsIntended, + awaitingInterruptionEnd: interruptionResumePolicy.isAwaitingInterruptionEnd, + hasPendingReconnect: radioReconnectTask != nil, + isPlaying: isPlaying + ) else { + return false + } + plog("📻 Network path recovered; reconnecting '\(station.name)' immediately") + scheduleRadioReconnect(station: station, playID: id, immediate: true) + return true + } + func stopRadioTransport(clearSelection: Bool) { + RadioNetworkRecoveryObserver.shared.stop(for: self) radioReconnectTask?.cancel() radioReconnectTask = nil radioPlaybackController.stop() @@ -783,3 +811,52 @@ extension AudioPlayerService { updatePlaybackState() } } + +/// 仅在直播电台进入退避重连等待时监听 `NetworkMonitor.pathGeneration`: +/// 网络恢复可达即刻唤醒重连,正常播放或停止后不留常驻观察。 +@MainActor +private final class RadioNetworkRecoveryObserver { + static let shared = RadioNetworkRecoveryObserver() + + private weak var player: AudioPlayerService? + private var lastObservedGeneration: UInt64 = 0 + private var isObserving = false + + func start(for player: AudioPlayerService) { + self.player = player + lastObservedGeneration = NetworkMonitor.shared.pathGeneration + guard !isObserving else { return } + isObserving = true + trackNextPathChange() + } + + func stop(for player: AudioPlayerService) { + guard self.player === player else { return } + self.player = nil + isObserving = false + } + + private func trackNextPathChange() { + guard isObserving, player != nil else { + isObserving = false + return + } + withObservationTracking { + _ = NetworkMonitor.shared.pathGeneration + } onChange: { [weak self] in + Task { @MainActor [weak self] in + guard let self, self.isObserving, let player = self.player else { return } + let generation = NetworkMonitor.shared.pathGeneration + if generation != self.lastObservedGeneration { + self.lastObservedGeneration = generation + _ = player.handleRadioNetworkRecoveryIfNeeded() + } + if player.isLiveRadio, player.radioReconnectTask != nil { + self.trackNextPathChange() + } else { + self.isObserving = false + } + } + } + } +} diff --git a/Primuse/Services/Radio/RadioPlaybackController.swift b/Primuse/Services/Radio/RadioPlaybackController.swift index 18149b623..591fdfc62 100644 --- a/Primuse/Services/Radio/RadioPlaybackController.swift +++ b/Primuse/Services/Radio/RadioPlaybackController.swift @@ -38,6 +38,7 @@ final class RadioPlaybackController: NSObject { private var inferredFormat: RadioStreamFormat = .automatic private var generation = UUID() private var terminalFailureDelivered = false + private var stallWatchdogTask: Task? func start(url: URL, volume: Float, eventHandler: @escaping (Event) -> Void) { stop() @@ -48,6 +49,7 @@ final class RadioPlaybackController: NSObject { self.inferredFormat = RadioStreamFormat.inferred(from: url) terminalFailureDelivered = false eventHandler(.loading) + armStallWatchdog(generation: generation) let asset = AVURLAsset(url: url) let item = AVPlayerItem(asset: asset) @@ -88,9 +90,14 @@ final class RadioPlaybackController: NSObject { Task { @MainActor [weak self] in guard let self, self.generation == generation else { return } switch player.timeControlStatus { - case .playing: self.eventHandler?(.playing) - case .waitingToPlayAtSpecifiedRate: self.eventHandler?(.buffering) - case .paused: break + case .playing: + self.disarmStallWatchdog() + self.eventHandler?(.playing) + case .waitingToPlayAtSpecifiedRate: + self.armStallWatchdog(generation: generation) + self.eventHandler?(.buffering) + case .paused: + self.disarmStallWatchdog() @unknown default: break } } @@ -114,6 +121,7 @@ final class RadioPlaybackController: NSObject { ) { [weak self] _ in Task { @MainActor [weak self] in guard let self, self.generation == generation else { return } + self.armStallWatchdog(generation: generation) self.eventHandler?(.buffering) } } @@ -143,6 +151,7 @@ final class RadioPlaybackController: NSObject { } func stop() { + disarmStallWatchdog() generation = UUID() player?.pause() player?.replaceCurrentItem(with: nil) @@ -180,7 +189,29 @@ final class RadioPlaybackController: NSObject { eventHandler?(.ready(format: inferredFormat, bitRate: bitRate)) } + private func armStallWatchdog(generation: UUID) { + guard stallWatchdogTask == nil else { return } + let timeout = RadioStallWatchdogPolicy.stallTimeoutSeconds + stallWatchdogTask = Task { @MainActor [weak self] in + do { + try await Task.sleep(for: .seconds(timeout)) + } catch { + return + } + guard let self, self.generation == generation, !self.terminalFailureDelivered else { return } + self.stallWatchdogTask = nil + plog("📻 Radio stall watchdog triggered after \(Int(timeout))s; reconnecting") + self.publishFailure(nil, shouldReconnect: true) + } + } + + private func disarmStallWatchdog() { + stallWatchdogTask?.cancel() + stallWatchdogTask = nil + } + private func publishFailure(_ error: Error?, shouldReconnect: Bool) { + disarmStallWatchdog() guard !terminalFailureDelivered else { return } terminalFailureDelivered = true let message = error?.localizedDescription ?? String(localized: "radio_stream_ended") diff --git a/Primuse/Views/NowPlaying/ChapterListView.swift b/Primuse/Views/NowPlaying/ChapterListView.swift index 2f05eaeb8..5127d5556 100644 --- a/Primuse/Views/NowPlaying/ChapterListView.swift +++ b/Primuse/Views/NowPlaying/ChapterListView.swift @@ -355,6 +355,16 @@ struct SpokenWordContentsView: View { } #endif } + if !entries.isEmpty { + ShareLink(item: bookmarksMarkdown(entries)) { + Label("share", systemImage: "square.and.arrow.up") + .font(.subheadline) + } + .buttonStyle(.plain) + .foregroundStyle(palette?.accent ?? spokenContentsSheetAccent) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } if !isSheet { addBookmarkButton .buttonStyle(.plain) @@ -367,6 +377,23 @@ struct SpokenWordContentsView: View { .scrollContentBackground(isSheet ? .automatic : .hidden) } + private func bookmarksMarkdown(_ entries: [SpokenWordBookBookmarkPolicy.Entry]) -> String { + let title = player.currentSpokenWordBook?.title + ?? player.currentSong?.albumTitle + ?? player.currentSong?.title + ?? "" + let author = player.currentSpokenWordBook?.author ?? player.currentSong?.artistName + let exported = entries.map { entry in + ListeningNotesExporter.BookmarkEntry( + title: entry.bookmark.title, + partTitle: entry.partNumber.map { "#\($0)" }, + position: entry.bookmark.position, + createdAt: entry.bookmark.createdAt + ) + } + return ListeningNotesExporter.bookmarksMarkdown(title: title, author: author, entries: exported) + } + private var addBookmarkButton: some View { Button { if player.addSpokenWordBookmark() { bookmarkFeedbackToken += 1 } diff --git a/Primuse/Views/Radio/RadioStationDetailView.swift b/Primuse/Views/Radio/RadioStationDetailView.swift index 1f876cd98..916d01540 100644 --- a/Primuse/Views/Radio/RadioStationDetailView.swift +++ b/Primuse/Views/Radio/RadioStationDetailView.swift @@ -379,6 +379,19 @@ struct RadioStationDetailView: View { .accessibilityAddTraits(.isHeader) Spacer() if !entries.isEmpty { + ShareLink( + item: ListeningNotesExporter.radioHistoryMarkdown( + stationName: station.name, + streamURL: station.streamURL, + entries: entries + ) + ) { + Image(systemName: "square.and.arrow.up") + .font(.subheadline) + } + .buttonStyle(.plain) + .foregroundStyle(RadioSpacePalette.accent) + .accessibilityLabel(Text("share")) Button("clear") { showsClearHistoryConfirm = true } .font(.subheadline) .buttonStyle(.plain) diff --git a/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift index 78e0e6fb2..6f70062b6 100644 --- a/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Radio/RadioPlaybackPolicy.swift @@ -108,3 +108,24 @@ public enum RadioTransportRoutingPolicy { return outputAllowsEffects && (voiceBoostActive || equalizerEnabled) } } + +/// 直播电台卡顿看门狗与网络恢复即时重连策略: +/// - 原生 AVPlayer 长时间停留在缓冲/无声状态时,由看门狗超时后交回重连状态机; +/// - 断网后进入指数退避等待期间,一旦网络路径恢复可达,立刻跳过剩余退避时间重连。 +public enum RadioStallWatchdogPolicy { + public static let stallTimeoutSeconds: TimeInterval = 18 + + public static func shouldTriggerImmediateReconnectOnNetworkReachability( + isLiveRadio: Bool, + isNetworkReachable: Bool, + playbackIntended: Bool, + awaitingInterruptionEnd: Bool, + hasPendingReconnect: Bool, + isPlaying: Bool + ) -> Bool { + guard isLiveRadio, isNetworkReachable, playbackIntended, !awaitingInterruptionEnd else { + return false + } + return hasPendingReconnect || !isPlaying + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/ListeningNotesExporter.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/ListeningNotesExporter.swift new file mode 100644 index 000000000..9c5120bf7 --- /dev/null +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/ListeningNotesExporter.swift @@ -0,0 +1,92 @@ +import Foundation + +/// 跨收听空间共享的 Markdown 导出器:统一承接播客书签、有声书书签与直播电台「刚播过」曲目记录, +/// 可直接通过系统分享写入备忘录、Obsidian、Notion 等笔记应用。 +public enum ListeningNotesExporter { + public struct BookmarkEntry: Equatable, Sendable { + public var title: String + public var partTitle: String? + public var position: TimeInterval + public var createdAt: Date? + + public init( + title: String, + partTitle: String? = nil, + position: TimeInterval, + createdAt: Date? = nil + ) { + self.title = title + self.partTitle = partTitle + self.position = position + self.createdAt = createdAt + } + } + + public static func bookmarksMarkdown( + title: String, + author: String? = nil, + entries: [BookmarkEntry] + ) -> String { + let heading = title.trimmingCharacters(in: .whitespacesAndNewlines) + var lines: [String] = ["# \(heading.isEmpty ? "Bookmarks" : heading)"] + if let author = author?.trimmingCharacters(in: .whitespacesAndNewlines), !author.isEmpty { + lines.append("*\(author)*") + } + if !entries.isEmpty { + lines.append("") + for entry in entries { + let stamp = formatTimestamp(entry.position) + let part = entry.partTitle?.trimmingCharacters(in: .whitespacesAndNewlines) + let note = entry.title.trimmingCharacters(in: .whitespacesAndNewlines) + var parts: [String] = [] + if let part, !part.isEmpty { parts.append(part) } + if !note.isEmpty { parts.append(note) } + let body = parts.isEmpty ? "" : " " + parts.joined(separator: " — ") + lines.append("- **[\(stamp)]**\(body)") + } + } + return lines.joined(separator: "\n") + } + + public static func radioHistoryMarkdown( + stationName: String, + streamURL: String? = nil, + entries: [RadioHeardTitle], + timeZone: TimeZone = .current + ) -> String { + let heading = stationName.trimmingCharacters(in: .whitespacesAndNewlines) + var lines: [String] = ["# \(heading.isEmpty ? "Radio" : heading)"] + if let streamURL = streamURL?.trimmingCharacters(in: .whitespacesAndNewlines), !streamURL.isEmpty { + lines.append("<\(streamURL)>") + } + if !entries.isEmpty { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = timeZone + formatter.dateFormat = "yyyy-MM-dd HH:mm" + lines.append("") + for entry in entries { + let time = formatter.string(from: entry.heardAt) + if let artist = entry.artist?.trimmingCharacters(in: .whitespacesAndNewlines), !artist.isEmpty, + let track = entry.title?.trimmingCharacters(in: .whitespacesAndNewlines), !track.isEmpty { + lines.append("- **\(artist)** — \(track) *(\(time))*") + } else { + lines.append("- \(entry.text) *(\(time))*") + } + } + } + return lines.joined(separator: "\n") + } + + public static func formatTimestamp(_ seconds: TimeInterval) -> String { + guard seconds.isFinite, seconds > 0 else { return "00:00" } + let total = Int(seconds.rounded(.down)) + let hours = total / 3600 + let minutes = (total % 3600) / 60 + let secs = total % 60 + if hours > 0 { + return String(format: "%d:%02d:%02d", hours, minutes, secs) + } + return String(format: "%02d:%02d", minutes, secs) + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift index 5f92af4e6..4a123e9f6 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Radio/RadioPlaybackPolicyTests.swift @@ -134,4 +134,40 @@ struct RadioPlaybackPolicyTests { stationFormat: .hls, resolvedURL: hlsURL, voiceBoostActive: true, equalizerEnabled: true, outputAllowsEffects: true ) == false) } + + @Test func stallWatchdogAndNetworkRecoveryReconnectPolicy() { + #expect(RadioStallWatchdogPolicy.stallTimeoutSeconds >= 10) + #expect(RadioStallWatchdogPolicy.shouldTriggerImmediateReconnectOnNetworkReachability( + isLiveRadio: true, + isNetworkReachable: true, + playbackIntended: true, + awaitingInterruptionEnd: false, + hasPendingReconnect: true, + isPlaying: false + )) + #expect(!RadioStallWatchdogPolicy.shouldTriggerImmediateReconnectOnNetworkReachability( + isLiveRadio: true, + isNetworkReachable: false, + playbackIntended: true, + awaitingInterruptionEnd: false, + hasPendingReconnect: true, + isPlaying: false + )) + #expect(!RadioStallWatchdogPolicy.shouldTriggerImmediateReconnectOnNetworkReachability( + isLiveRadio: true, + isNetworkReachable: true, + playbackIntended: true, + awaitingInterruptionEnd: false, + hasPendingReconnect: false, + isPlaying: true + )) + #expect(!RadioStallWatchdogPolicy.shouldTriggerImmediateReconnectOnNetworkReachability( + isLiveRadio: false, + isNetworkReachable: true, + playbackIntended: true, + awaitingInterruptionEnd: false, + hasPendingReconnect: true, + isPlaying: false + )) + } } diff --git a/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/ListeningNotesExporterTests.swift b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/ListeningNotesExporterTests.swift new file mode 100644 index 000000000..9be96bf9f --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/SpokenWord/ListeningNotesExporterTests.swift @@ -0,0 +1,53 @@ +import Foundation +import PrimuseKit +import Testing + +@Suite("Cross-space Markdown listening notes exporter") +struct ListeningNotesExporterTests { + @Test("Formats podcast and audiobook bookmarks into Markdown with HH:MM:SS timestamps") + func formatsBookmarksMarkdown() { + let md = ListeningNotesExporter.bookmarksMarkdown( + title: "Designing Data-Intensive Applications", + author: "Martin Kleppmann", + entries: [ + .init(title: "Replication quote", partTitle: "#2", position: 125), + .init(title: "", partTitle: "#5", position: 3723), + .init(title: "Solo note", partTitle: nil, position: 0), + ] + ) + #expect(md.contains("# Designing Data-Intensive Applications")) + #expect(md.contains("*Martin Kleppmann*")) + #expect(md.contains("- **[02:05]** #2 — Replication quote")) + #expect(md.contains("- **[1:02:03]** #5")) + #expect(md.contains("- **[00:00]** Solo note")) + } + + @Test("Formats live radio heard-song history into Markdown") + func formatsRadioHistoryMarkdown() { + let heardAt = Date(timeIntervalSince1970: 1_730_000_000) + let entries = [ + RadioHeardTitle( + text: "Daft Punk - Digital Love", + artist: "Daft Punk", + title: "Digital Love", + heardAt: heardAt + ), + RadioHeardTitle( + text: "Evening Jazz Hour", + artist: nil, + title: nil, + heardAt: heardAt + ), + ] + let md = ListeningNotesExporter.radioHistoryMarkdown( + stationName: "FIP", + streamURL: "https://icecast.radiofrance.fr/fip-hifi.aac", + entries: entries, + timeZone: TimeZone(secondsFromGMT: 0)! + ) + #expect(md.contains("# FIP")) + #expect(md.contains("")) + #expect(md.contains("- **Daft Punk** — Digital Love *(2024-10-27 03:33)*")) + #expect(md.contains("- Evening Jazz Hour *(2024-10-27 03:33)*")) + } +} diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index f5840bc29..8627777ab 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -500,4 +500,31 @@ final class ListeningSpacesReliabilityTests: XCTestCase { XCTAssertEqual(store.position(forSongID: song1.id)?.position ?? -1, 420, accuracy: 0.5) XCTAssertNil(store.position(forSongID: song2.id)) } + + func testRadioNetworkRecoveryResetsBackoffAndSchedulesImmediateReconnect() { + let player = AudioPlayerService() + cleanups.append { player.stopRadioTransport(clearSelection: true) } + + let station = RadioStation( + id: "reconnect-\(UUID().uuidString)", + name: "News FM", + streamURL: "https://radio.example.com/news.mp3", + streamFormat: .mp3 + ) + player.playbackKind = .liveRadio + player.currentRadioStation = station + player.currentSong = station.playbackSong + player.playID = UUID() + player.isPlaying = false + player.radioReconnectAttempt = 4 + player.registerPlayIntent() + player.radioReconnectTask = Task { try? await Task.sleep(for: .seconds(60)) } + + XCTAssertFalse(player.handleRadioNetworkRecoveryIfNeeded(isNetworkReachable: false)) + XCTAssertEqual(player.radioReconnectAttempt, 4) + + XCTAssertTrue(player.handleRadioNetworkRecoveryIfNeeded(isNetworkReachable: true)) + XCTAssertEqual(player.radioReconnectAttempt, 0) + XCTAssertNotNil(player.radioReconnectTask) + } } From 47dbbccafa20a6a659c2e12641d164a2f2913f00 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 21:25:59 -0500 Subject: [PATCH 10/15] =?UTF-8?q?=E8=A7=A3=E9=94=81=E6=92=AD=E5=AE=A2?= =?UTF-8?q?=E4=B8=8E=E6=9C=89=E5=A3=B0=E4=B9=A6=E9=9F=B3=E9=A2=91=E7=89=87?= =?UTF-8?q?=E6=AE=B5=E5=AF=BC=E5=87=BA=EF=BC=8C=E5=B9=B6=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E8=B7=A8=E7=A9=BA=E9=97=B4=E6=8C=81=E4=B9=85=E5=8C=96=E6=92=AD?= =?UTF-8?q?=E5=AE=A2=E9=98=9F=E5=88=97=E8=AE=B0=E5=BF=86=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 14 ++++ .../Services/Audio/AudioClipExporter.swift | 29 +++++-- .../AudioPlayerService+ListeningSpaces.swift | 10 ++- .../AudioPlayerService+PlaybackRange.swift | 13 +++ .../Audio/AudioPlayerService+Podcast.swift | 63 +++++++++++++++ .../Audio/AudioPlayerService+Radio.swift | 1 + .../Podcast/PodcastQueueMemoryStore.swift | 80 +++++++++++++++++++ .../Components/SongPlaybackRangeEditor.swift | 74 +++++------------ .../SongPlaybackRangeMenuItems.swift | 46 +++++++++++ Primuse/Views/Mac/PlayerMoreMenu.swift | 35 ++++---- Primuse/Views/NowPlaying/NowPlayingView.swift | 2 +- .../NowPlaying/PodcastPlayerComponents.swift | 48 +++++++++++ .../Podcast/PodcastEpisodeDetailView.swift | 4 + .../Audio/AudioClipExportPolicy.swift | 21 +++++ .../Podcast/PodcastLibraryPolicy.swift | 30 +++++++ .../Podcast/PodcastShowNotesTests.swift | 28 +++++++ .../ListeningSpacesReliabilityTests.swift | 66 +++++++++++++++ 17 files changed, 484 insertions(+), 80 deletions(-) create mode 100644 Primuse/Services/Podcast/PodcastQueueMemoryStore.swift create mode 100644 Primuse/Views/Components/SongPlaybackRangeMenuItems.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index b73f311e3..d1626225a 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -147,6 +147,7 @@ 0AB609F33F44AFDEE2E345DB /* LibraryIndexMaintenancePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7DE9ABC7DD452FA9E024A52 /* LibraryIndexMaintenancePolicy.swift */; }; 0ACA25C2348D8CA0D4AE2966 /* EmbyLyricsTrackEventParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98C6228B8950A5EAB88F9960 /* EmbyLyricsTrackEventParser.swift */; }; 0ACB1D658F47D5EAA17E73DF /* SongloftSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A373D69542A894AC0E311DF /* SongloftSource.swift */; }; + 0AE4D709D477E3CD884158CD /* SongPlaybackRangeMenuItems.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0C9BD90B049B1584F8F8994 /* SongPlaybackRangeMenuItems.swift */; }; 0AFB38222A6E5CD31AC4C1EF /* MacKeyboardShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66190DBA8D3523EDE74EED81 /* MacKeyboardShortcuts.swift */; }; 0B27BB086E12A8042A20DCAA /* BaiduPanIncrementalSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6260D8F4F4648F9D7376C4F5 /* BaiduPanIncrementalSync.swift */; }; 0B877004E9BC6105414BD7A5 /* MacDetailContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D09F74F18E7CED7C6CDC0960 /* MacDetailContainer.swift */; }; @@ -2334,6 +2335,7 @@ AD2E0BAD17702DAEDC49EE31 /* ServerCatalogMetadataInspectionPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2650E897644F3365C533BBA4 /* ServerCatalogMetadataInspectionPolicy.swift */; }; AD475F09F1B75490AECBF0E1 /* SpokenWordSmartRewindPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0E9911D80216D0A87EDA876 /* SpokenWordSmartRewindPolicy.swift */; }; AD4E66E2DCDDA13E782457A4 /* AppleMusicSystemQueuePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E97B1EB2BFFD617A5FD6308 /* AppleMusicSystemQueuePolicy.swift */; }; + AD57051335F88BBBEF21A15C /* PodcastQueueMemoryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E19295BCFC34DE6AD761717 /* PodcastQueueMemoryStore.swift */; }; AD5D327D76859376F6EFC34E /* HTTPChunkedBodyDecodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C271778C5DE77B04EB337C67 /* HTTPChunkedBodyDecodingTests.swift */; }; AD675AE2312AF7C41C011A20 /* SemanticAlbumResultCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69918F7E72B36379DC66865F /* SemanticAlbumResultCard.swift */; }; AD67A69E72837A8AA7866B3A /* MetadataBackfillService.swift in Sources */ = {isa = PBXBuildFile; fileRef = B56809F1C697EF691877166D /* MetadataBackfillService.swift */; }; @@ -2383,6 +2385,7 @@ B131E84BCCEDBE08EFB68055 /* MetadataReadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4CAEC08D91349C3E75D266D /* MetadataReadScheduler.swift */; }; B13688CE93C1CBDC0F1F8445 /* AlbumRecommendationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13A15DE9BA51C9AB93D6A5A9 /* AlbumRecommendationService.swift */; }; B13E62F876EB7413E713B876 /* FloatingLyricsViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = BADEEBD667CF5AF1A651686D /* FloatingLyricsViews.swift */; }; + B14110E1D09DFB2F9474DE2C /* PodcastQueueMemoryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E19295BCFC34DE6AD761717 /* PodcastQueueMemoryStore.swift */; }; B14EDD2A7CD9E890E3C823A1 /* FullReleaseAlbumArtistMemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD21448B40E17AC43E7CFD88 /* FullReleaseAlbumArtistMemo.swift */; }; B17219BB90BF44AC71EF1275 /* ArtistHeroBackgroundResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5B70DDFFBE693A36434AB1A /* ArtistHeroBackgroundResolver.swift */; }; B1967D2CBF55455583636063 /* LibraryCatalog+PointReads.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F6C75D1E967428CD03AA4E1 /* LibraryCatalog+PointReads.swift */; }; @@ -2525,6 +2528,7 @@ BAF49048C4B8E0BEB42DC905 /* RenderingVisibility.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4DB999971CA92DDD0B89B9E /* RenderingVisibility.swift */; }; BB0E4FBB6078333D949124D5 /* KaraokeDemucsFrontEnd.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2092736FF24061B419F178A3 /* KaraokeDemucsFrontEnd.swift */; }; BB3D6E2273DFAA1F96DF08E5 /* MusicIntelligenceService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 696F0EA37D288187E2E33DD2 /* MusicIntelligenceService.swift */; }; + BB64B903F9CA13210F5D1F8F /* PodcastQueueMemoryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E19295BCFC34DE6AD761717 /* PodcastQueueMemoryStore.swift */; }; BB70AEDD03F7FA1FCDA235F3 /* ListeningHistoryResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35411141B8422024CD83DF66 /* ListeningHistoryResolution.swift */; }; BB73612297D7821DA7EFEB7D /* AudioPlayerService+AutoContinuation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D94F9FC1470B10DD0338A9 /* AudioPlayerService+AutoContinuation.swift */; }; BB8CB95F81DAD944536146FF /* ReadOnlyMetadataWritebackTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C24F24EB087C68DFCFF84CFB /* ReadOnlyMetadataWritebackTests.swift */; }; @@ -3385,6 +3389,7 @@ FBC11C5AC73342AAB00CD96B /* LibraryDetailTintPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD3514B3ADBA1E0AA5531411 /* LibraryDetailTintPolicy.swift */; }; FBD3B4F97C3184F20CB3F0EC /* WikipediaInsight.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CCFA52C1B81B286DBEF8A60 /* WikipediaInsight.swift */; }; FBD63DDB02B6204B7815BB5A /* TingReaderAPIProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = A528206BA6162F67A0237CDD /* TingReaderAPIProtocol.swift */; }; + FBE590A49460DE82E1D5522F /* SongPlaybackRangeMenuItems.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0C9BD90B049B1584F8F8994 /* SongPlaybackRangeMenuItems.swift */; }; FC02EE351E7C5563F907F263 /* MetadataBackfillRetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CDDA2005F50FC39CB7A872A /* MetadataBackfillRetryPolicy.swift */; }; FC03BF45CFF795C29718C5BC /* PlaylistExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 285C1472009479A6CC7B2177 /* PlaylistExporter.swift */; }; FC0AE9797AAAD098FD564643 /* SpokenWordSleepSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = F239A5B925B9F1E8568F8995 /* SpokenWordSleepSelection.swift */; }; @@ -5123,6 +5128,7 @@ 8DCD6A621ACBB8145468F9D5 /* LibraryHubReleased.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryHubReleased.swift; sourceTree = ""; }; 8DD794230AEA7E56FF0C4348 /* MergedListeningHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MergedListeningHistory.swift; sourceTree = ""; }; 8DFB5AEB2960B8723D2E4E8E /* LANSync.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LANSync.swift; sourceTree = ""; }; + 8E19295BCFC34DE6AD761717 /* PodcastQueueMemoryStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PodcastQueueMemoryStore.swift; sourceTree = ""; }; 8E235EE9368769D3D11DEB69 /* RemoteGatewayBackoffPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteGatewayBackoffPolicy.swift; sourceTree = ""; }; 8E8FE90B3241939ADD3F1BE7 /* AudioCalibrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioCalibrationTests.swift; sourceTree = ""; }; 8E9331C4FF0398A26F758BA0 /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/CacheSync.strings; sourceTree = ""; }; @@ -5422,6 +5428,7 @@ B06003B549EC006989BEE5AB /* SourceCustomHeadersSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SourceCustomHeadersSection.swift; sourceTree = ""; }; B09C4FBAAE2E4BE5F74A9E51 /* hi */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = hi; path = hi.lproj/InfoPlist.strings; sourceTree = ""; }; B0AA7EC4D7A4EFC36DF55E56 /* WiFiTransferLibraryPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WiFiTransferLibraryPicker.swift; sourceTree = ""; }; + B0C9BD90B049B1584F8F8994 /* SongPlaybackRangeMenuItems.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SongPlaybackRangeMenuItems.swift; sourceTree = ""; }; B0CC301A56FBF0E17FE3661D /* UpcomingPlaybackPrefetchPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpcomingPlaybackPrefetchPolicy.swift; sourceTree = ""; }; B0CF1E96A5B91201245170B5 /* SourceLoginSessionStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SourceLoginSessionStore.swift; sourceTree = ""; }; B0F7CA606A01C1BEAABDCEDE /* SpokenWordBookPlaybackPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordBookPlaybackPolicy.swift; sourceTree = ""; }; @@ -6932,6 +6939,7 @@ 0BDB4CF23CF925515FBC484D /* PodcastDownloadStore.swift */, EAE2612A6C872FDE582BFD30 /* PodcastFormat.swift */, F130E9C212ECBE573672CF94 /* PodcastNetwork.swift */, + 8E19295BCFC34DE6AD761717 /* PodcastQueueMemoryStore.swift */, F330312B7C4C3D055018B052 /* PodcastStore.swift */, ); path = Podcast; @@ -8688,6 +8696,7 @@ 7E6D8F9E72019BB5755F6F3C /* SmartNudgeOverlay.swift */, AE8A8737AA8056BECA3E6078 /* SongListAppearanceViews.swift */, 2E92A864271E38E25A6430A4 /* SongPlaybackRangeEditor.swift */, + B0C9BD90B049B1584F8F8994 /* SongPlaybackRangeMenuItems.swift */, 8781DF958BF4476F3C2BE6E4 /* SongRowPressFeedback.swift */, 1424E7F042F598B858110FDB /* SongRowView.swift */, 811D43996EDFF1738D72950E /* SongRowView+Released.swift */, @@ -11909,6 +11918,7 @@ CCFE8C63400D6EDD79A59A81 /* PodcastMacLibraryView.swift in Sources */, 4AA69BAE207825C410A36459 /* PodcastNetwork.swift in Sources */, 96AF9CD85444F274C1171033 /* PodcastPlayerComponents.swift in Sources */, + BB64B903F9CA13210F5D1F8F /* PodcastQueueMemoryStore.swift in Sources */, 76AEBD3B7024DC2AF50352A9 /* PodcastResumeItem+Recent.swift in Sources */, 21DFD7099F0DD7869C388C9A /* PodcastShowDetailView.swift in Sources */, C1AF76796CED17D4DEA48A8F /* PodcastStore.swift in Sources */, @@ -12041,6 +12051,7 @@ 3EDD8F0535AFFCAD9E9F864C /* SongListView+SortOrder.swift in Sources */, 5980823594F7E539787FAED3 /* SongListView.swift in Sources */, 411242F6317B094309DAEB1A /* SongPlaybackRangeEditor.swift in Sources */, + FBE590A49460DE82E1D5522F /* SongPlaybackRangeMenuItems.swift in Sources */, FEDB5708BC791E97FE8C05CB /* SongPlaybackRangeStore.swift in Sources */, B0E0F125D39A9C619838A4EE /* SongRowPressFeedback.swift in Sources */, 888BDB1C8B749013C7F7CE94 /* SongRowView+Released.swift in Sources */, @@ -12343,6 +12354,7 @@ 00785E24B25147B59FADCBAD /* PodcastDownloadStore.swift in Sources */, 33A0AF5B686C79EAA245F3C2 /* PodcastFormat.swift in Sources */, 9CEDDC85144C3D65E30A9126 /* PodcastNetwork.swift in Sources */, + AD57051335F88BBBEF21A15C /* PodcastQueueMemoryStore.swift in Sources */, 37E8C2C8A7FB12D5968E8F45 /* PodcastStore.swift in Sources */, BF01CD833FA8C8CDAD5EDD7D /* PortableArtworkCollector.swift in Sources */, 4C75E4027A9C62034D152C42 /* PortableSnapshotPreparationRun.swift in Sources */, @@ -13131,6 +13143,7 @@ 690FA7DD6B9CE22866A48BEE /* PodcastMacLibraryView.swift in Sources */, F42719D18702C67BDED29230 /* PodcastNetwork.swift in Sources */, 40EC97728B1A59F19064168A /* PodcastPlayerComponents.swift in Sources */, + B14110E1D09DFB2F9474DE2C /* PodcastQueueMemoryStore.swift in Sources */, 5B31F6587BB8D65E29EEFED5 /* PodcastResumeItem+Recent.swift in Sources */, A6B492B42C0C4E7F687AA3A2 /* PodcastShowDetailView.swift in Sources */, 369C66911BC2EA6FA3E31EDC /* PodcastStore.swift in Sources */, @@ -13263,6 +13276,7 @@ 1477F6895C795950038FF6F8 /* SongListView+SortOrder.swift in Sources */, F7C1D24746A9EFBB09955A64 /* SongListView.swift in Sources */, 4548279245A54F7442AED9F8 /* SongPlaybackRangeEditor.swift in Sources */, + 0AE4D709D477E3CD884158CD /* SongPlaybackRangeMenuItems.swift in Sources */, 4F6B787BEBB3677FAB17E22C /* SongPlaybackRangeStore.swift in Sources */, 583536651BCC96D2EDBA9176 /* SongRowPressFeedback.swift in Sources */, 2B6B472B56159A051FBD9601 /* SongRowView+Released.swift in Sources */, diff --git a/Primuse/Services/Audio/AudioClipExporter.swift b/Primuse/Services/Audio/AudioClipExporter.swift index 3dbc67731..3dd5ae96b 100644 --- a/Primuse/Services/Audio/AudioClipExporter.swift +++ b/Primuse/Services/Audio/AudioClipExporter.swift @@ -41,6 +41,11 @@ enum AudioClipExporter { /// 其次是离线精简副本)。不下载、不拿播放租约。 @MainActor static func onDeviceFile(for song: Song, sourceManager: SourceManager) async -> URL? { + if PodcastPlaybackSong.isEpisode(song), + let local = PodcastDownloadStore.shared.localURL(for: song.id), + FileManager.default.isReadableFile(atPath: local.path) { + return local + } if let local = await sourceManager.directLocalFileURL(for: song), FileManager.default.isReadableFile(atPath: local.path) { return local @@ -49,19 +54,29 @@ enum AudioClipExporter { return sourceManager.cachedPlaybackURL(for: song) } - /// 整首歌的一份文件:在这台设备上的直接用,否则经音乐源取一份(和听歌识词同一条路)。 + /// 整首歌的一份文件:在这台设备上的直接用,否则经音乐源或播客音频地址取一份(和听歌识词同一条路)。 @MainActor static func wholeFile(for song: Song, sourceManager: SourceManager) async throws -> WholeFile { if let onDevice = await onDeviceFile(for: song, sourceManager: sourceManager) { return WholeFile(url: onDevice, isTemporary: false) } let resolved: URL - do { - resolved = try await sourceManager.resolveFullDownloadSourceURL(for: song) - } catch is CancellationError { - throw CancellationError() - } catch { - throw Failure.audioUnavailable + if PodcastPlaybackSong.isEpisode(song) { + if let probed = PodcastEnclosureProbeCache.shared.probe(forEpisodeID: song.id)?.finalURL { + resolved = probed + } else if let direct = URL(string: song.filePath) { + resolved = direct + } else { + throw Failure.audioUnavailable + } + } else { + do { + resolved = try await sourceManager.resolveFullDownloadSourceURL(for: song) + } catch is CancellationError { + throw CancellationError() + } catch { + throw Failure.audioUnavailable + } } if resolved.isFileURL { guard FileManager.default.isReadableFile(atPath: resolved.path) else { throw Failure.audioUnavailable } diff --git a/Primuse/Services/Audio/AudioPlayerService+ListeningSpaces.swift b/Primuse/Services/Audio/AudioPlayerService+ListeningSpaces.swift index c5cd36213..83a8369b5 100644 --- a/Primuse/Services/Audio/AudioPlayerService+ListeningSpaces.swift +++ b/Primuse/Services/Audio/AudioPlayerService+ListeningSpaces.swift @@ -475,9 +475,13 @@ extension AudioPlayerService { } func rememberMusicSessionIfLeaving(from outgoing: Song?, to incoming: Song?) { - guard let outgoing, let incoming, - listeningSpace(of: outgoing) == .music, - listeningSpace(of: incoming) != .music else { return } + guard let outgoing, let incoming else { return } + let outgoingSpace = listeningSpace(of: outgoing) + let incomingSpace = listeningSpace(of: incoming) + if outgoingSpace == .podcast, incomingSpace != .podcast { + rememberCurrentPodcastQueue(outgoing: outgoing) + } + guard outgoingSpace == .music, incomingSpace != .music else { return } rememberCurrentMusicQueue(outgoing: outgoing) remembersMusicQueue = false } diff --git a/Primuse/Services/Audio/AudioPlayerService+PlaybackRange.swift b/Primuse/Services/Audio/AudioPlayerService+PlaybackRange.swift index 9f3b06186..852c17c18 100644 --- a/Primuse/Services/Audio/AudioPlayerService+PlaybackRange.swift +++ b/Primuse/Services/Audio/AudioPlayerService+PlaybackRange.swift @@ -114,6 +114,19 @@ enum SongPlaybackRangeAvailability { && !PodcastPlaybackSong.isEpisode(song) && SpokenWordStore.shared.isMusic(song) } + + /// 音频片段导出(铃声 / 片段分享):除了普通音乐外,也支持本地/服务端有声书及已下载或带音频链接的播客单集。 + @MainActor + static func supportsClipExport(_ song: Song) -> Bool { + guard song.sourceID != AppleMusicLibraryService.systemSourceID, + !song.isStandaloneMusicVideo, + !song.id.hasPrefix(RadioStation.playbackSongIDPrefix) else { return false } + if PodcastPlaybackSong.isEpisode(song) { + return PodcastDownloadStore.shared.localURL(for: song.id) != nil + || URL(string: song.filePath) != nil + } + return SpokenWordStore.shared.kind(for: song) != .ambient + } } // MARK: - 循环方式、停止点与 A-B 循环 diff --git a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift index a26f69be5..f69c6e078 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Podcast.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Podcast.swift @@ -52,9 +52,72 @@ extension AudioPlayerService { if !isPlaying { togglePlayPause() } return } + PodcastQueueMemoryStore.shared.clear() await play(queue: songs, startingAt: 0) } + // MARK: - Remembered Podcast Queue + + func rememberCurrentPodcastQueue( + outgoing: Song? = nil, + store: PodcastQueueMemoryStore = .shared + ) { + guard let song = outgoing ?? currentSong, + listeningSpace(of: song) == .podcast, + queueEntries.indices.contains(currentIndex), + queueEntries[currentIndex].song.id == song.id else { return } + let items = queueEntries.map { entry in + PodcastQueueMemoryStore.Item( + id: entry.song.id, + title: entry.song.title, + subtitle: (entry.song.albumTitle?.isEmpty == false ? entry.song.albumTitle : nil) ?? entry.song.artistName, + coverRef: entry.song.coverArtFileName + ) + } + store.save(items: items, currentIndex: currentIndex) + } + + var rememberedPodcastQueueSummary: (lead: PodcastQueueMemoryStore.Item, remainingCount: Int)? { + guard currentListeningSpace != .podcast, + let memory = PodcastQueueMemoryStore.shared.memory, + let plan = PodcastQueueMemoryPolicy.restored( + songIDs: memory.items.map(\.id), + currentIndex: memory.currentIndex, + isFinished: { SpokenWordStore.shared.isFinished(songID: $0) } + ), + let firstID = plan.songIDs.first, + let lead = memory.items.first(where: { $0.id == firstID }) else { return nil } + return (lead, plan.songIDs.count) + } + + @discardableResult + func resumeRememberedPodcastQueue(store: PodcastQueueMemoryStore = .shared) async -> Bool { + guard let memory = store.memory, + let plan = PodcastQueueMemoryPolicy.restored( + songIDs: memory.items.map(\.id), + currentIndex: memory.currentIndex, + isFinished: { SpokenWordStore.shared.isFinished(songID: $0) } + ) else { + store.clear() + return false + } + let podcastStore = PodcastStore.shared + podcastStore.loadIfNeeded() + let songs: [Song] = plan.songIDs.compactMap { id in + if let found = podcastStore.episode(id: id) { + return PodcastPlaybackSong.song(for: found.episode, show: found.show) + } + return library?.visibleSong(id: id) + } + guard !songs.isEmpty else { + store.clear() + return false + } + store.clear() + await play(queue: songs, startingAt: 0) + return true + } + /// 起播前的准备(`play(song:)` 里、取地址之前调)。探到的长度写回 `currentSong` /// 和队列里的那一项,拖动进度、断流恢复都按它来。 func preparePodcastEpisodeForPlayback(_ song: Song) async -> Song { diff --git a/Primuse/Services/Audio/AudioPlayerService+Radio.swift b/Primuse/Services/Audio/AudioPlayerService+Radio.swift index 3eaff8810..8d2e2926a 100644 --- a/Primuse/Services/Audio/AudioPlayerService+Radio.swift +++ b/Primuse/Services/Audio/AudioPlayerService+Radio.swift @@ -148,6 +148,7 @@ extension AudioPlayerService { stopTimeUpdater() radioPlaybackController.stop() rememberCurrentMusicQueue() + rememberCurrentPodcastQueue() remembersMusicQueue = false playbackKind = .liveRadio diff --git a/Primuse/Services/Podcast/PodcastQueueMemoryStore.swift b/Primuse/Services/Podcast/PodcastQueueMemoryStore.swift new file mode 100644 index 000000000..94fb4195f --- /dev/null +++ b/Primuse/Services/Podcast/PodcastQueueMemoryStore.swift @@ -0,0 +1,80 @@ +import Foundation +import Observation +import PrimuseKit + +/// 切离播客空间去听音乐、电台或有声书时记住当时的播客队列(当前集 + 接下来列表), +/// 回到播客空间时一键恢复整个 Up Next 队列并从上次进度继续。 +@MainActor +@Observable +final class PodcastQueueMemoryStore { + private(set) var memory: Memory? + @ObservationIgnored private let url: URL + + init(url: URL? = nil) { + if let url { + self.url = url + } else { + #if os(tvOS) + let base = FileManager.default.primuseDirectoryURL(for: .cachesDirectory) + #else + let base = FileManager.default.primuseDirectoryURL(for: .applicationSupportDirectory) + #endif + self.url = base.appendingPathComponent("Primuse/Podcasts/remembered-queue.json") + } + self.memory = Self.load(from: self.url) + } +} + +extension PodcastQueueMemoryStore { + struct Item: Codable, Equatable, Sendable, Identifiable { + var id: String + var title: String + var subtitle: String? + var coverRef: String? + } + + struct Memory: Codable, Equatable, Sendable { + var items: [Item] + var currentIndex: Int + var savedAt: Date + } + + static let shared = PodcastQueueMemoryStore() + static let maximumItems = PodcastQueueMemoryPolicy.maxStoredItems + + func save(items: [Item], currentIndex: Int, now: Date = Date()) { + guard !items.isEmpty else { + clear() + return + } + let clamped = min(max(0, currentIndex), items.count - 1) + let bounded = Array(items[clamped...].prefix(Self.maximumItems)) + let next = Memory(items: bounded, currentIndex: 0, savedAt: now) + guard memory != next else { return } + memory = next + persist(next) + } + + func clear() { + guard memory != nil else { return } + memory = nil + try? FileManager.default.removeItem(at: url) + } + + private func persist(_ memory: Memory) { + let targetURL = url + guard let data = try? JSONEncoder().encode(memory) else { return } + try? FileManager.default.createDirectory( + at: targetURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try? data.write(to: targetURL, options: .atomic) + } + + private static func load(from url: URL) -> Memory? { + guard let data = try? Data(contentsOf: url), + let decoded = try? JSONDecoder().decode(Memory.self, from: data), + !decoded.items.isEmpty else { return nil } + return decoded + } +} diff --git a/Primuse/Views/Components/SongPlaybackRangeEditor.swift b/Primuse/Views/Components/SongPlaybackRangeEditor.swift index 9545a0a55..c9800c440 100644 --- a/Primuse/Views/Components/SongPlaybackRangeEditor.swift +++ b/Primuse/Views/Components/SongPlaybackRangeEditor.swift @@ -5,54 +5,6 @@ import AppKit import UniformTypeIdentifiers #endif -/// 「播放时间段」在菜单里的样子:设过时间段时是一个开关(标题下面写着时间段) -/// 加一项「编辑」,一点就能开关;没设过时只有「设置播放时间段…」。最后一项是 -/// 「铃声与导出」,打开同一个面板的另一页。播放页「更多」里两部分可以分别关掉。 -/// 读写都走 `SongPlaybackRangeStore`,不依赖环境,菜单放在单独的宿主里也能用。 -struct SongPlaybackRangeMenuItems: View { - let song: Song - var showsPlaybackRange = true - var showsClipExport = true - let onEdit: (SongPlaybackRangeEditor.Purpose) -> Void - - var body: some View { - let store = SongPlaybackRangeStore.shared - if SongPlaybackRangeAvailability.supports(song) { - if !showsPlaybackRange { - EmptyView() - } else if let range = store.range(for: song) { - Toggle(isOn: Binding( - get: { range.isEnabled }, - set: { store.setEnabled($0, for: song) } - )) { - Label { - Text("playback_range_title") - Text(verbatim: SongPlaybackRangePolicy.rangeLabel(range)) - } icon: { - Image(systemName: "selection.pin.in.out") - } - .labelStyle(.titleAndIcon) - } - Button { onEdit(.playbackRange) } label: { - Label(String(localized: "playback_range_edit"), systemImage: "slider.horizontal.3") - .labelStyle(.titleAndIcon) - } - } else { - Button { onEdit(.playbackRange) } label: { - Label(String(localized: "playback_range_set"), systemImage: "selection.pin.in.out") - .labelStyle(.titleAndIcon) - } - } - if showsClipExport { - Button { onEdit(.clip) } label: { - Label(SongPlaybackRangeEditor.clipMenuTitle, systemImage: SongPlaybackRangeEditor.clipSymbol) - .labelStyle(.titleAndIcon) - } - } - } - } -} - /// 设置一首歌的播放时间段,或者选一段做成铃声、导出成音频文件,两页共用一条时间轴。 /// /// 播放时间段那页:开关和时间段放在同一张卡片里,开关下面直接写着时间段与时长;拖动把手、 @@ -148,6 +100,7 @@ struct SongPlaybackRangeEditor: View { } private var isCurrentSong: Bool { player.currentSong?.id == song.id } + private var supportsPlaybackRangeEditing: Bool { SongPlaybackRangeAvailability.supports(song) } /// 曲库里记的时长;还没有时用播放器这次量到的。 private var songDuration: TimeInterval { @@ -162,11 +115,20 @@ struct SongPlaybackRangeEditor: View { var body: some View { editorChrome .onAppear { + if !supportsPlaybackRangeEditing { + purpose = .clip + } // 曲库里还没有时长、打开时才从播放器知道的那种,结束点补成整首。 if draft.end <= 0, songDuration > 0 { draft = SongPlaybackRangePolicy.initialRange(songDuration: songDuration) } - if clipDraft.end <= 0, songDuration > 0 { + if !supportsPlaybackRangeEditing, isCurrentSong, songDuration > 0, player.currentTime > 1, + let centered = AudioClipExportPolicy.centeredClipRange( + around: player.currentTime, + songDuration: songDuration + ) { + clipDraft = centered + } else if clipDraft.end <= 0, songDuration > 0 { clipDraft = SongPlaybackRange( start: 0, end: min(songDuration, AudioClipExportPolicy.ringtoneMaximumLength), @@ -230,10 +192,12 @@ struct SongPlaybackRangeEditor: View { systemImage: purpose == .clip ? Self.clipSymbol : "timer", onClose: { dismiss() } ) { - MacSheetSegmentedControl(selection: purposeBinding, segments: [ - .init(value: .playbackRange, title: String(localized: "playback_range_title")), - .init(value: .clip, title: Self.clipTabTitle), - ]) + if supportsPlaybackRangeEditing { + MacSheetSegmentedControl(selection: purposeBinding, segments: [ + .init(value: .playbackRange, title: String(localized: "playback_range_title")), + .init(value: .clip, title: Self.clipTabTitle), + ]) + } } ScrollView { VStack(alignment: .leading, spacing: 16) { @@ -255,7 +219,9 @@ struct SongPlaybackRangeEditor: View { ScrollView { VStack(alignment: .leading, spacing: 18) { header - purposePicker + if supportsPlaybackRangeEditing { + purposePicker + } pageContent } .padding(20) diff --git a/Primuse/Views/Components/SongPlaybackRangeMenuItems.swift b/Primuse/Views/Components/SongPlaybackRangeMenuItems.swift new file mode 100644 index 000000000..98aadae04 --- /dev/null +++ b/Primuse/Views/Components/SongPlaybackRangeMenuItems.swift @@ -0,0 +1,46 @@ +import PrimuseKit +import SwiftUI + +/// 「播放时间段」与「片段导出」菜单项:音乐显示时间段 + 导出,播客与有声书自动仅显示片段导出。 +/// 读写都走 `SongPlaybackRangeStore`,不依赖环境,菜单放在单独的宿主里也能用。 +struct SongPlaybackRangeMenuItems: View { + let song: Song + var showsPlaybackRange = true + var showsClipExport = true + let onEdit: (SongPlaybackRangeEditor.Purpose) -> Void + + var body: some View { + let store = SongPlaybackRangeStore.shared + if showsPlaybackRange, SongPlaybackRangeAvailability.supports(song) { + if let range = store.range(for: song) { + Toggle(isOn: Binding( + get: { range.isEnabled }, + set: { store.setEnabled($0, for: song) } + )) { + Label { + Text("playback_range_title") + Text(verbatim: SongPlaybackRangePolicy.rangeLabel(range)) + } icon: { + Image(systemName: "selection.pin.in.out") + } + .labelStyle(.titleAndIcon) + } + Button { onEdit(.playbackRange) } label: { + Label(String(localized: "playback_range_edit"), systemImage: "slider.horizontal.3") + .labelStyle(.titleAndIcon) + } + } else { + Button { onEdit(.playbackRange) } label: { + Label(String(localized: "playback_range_set"), systemImage: "selection.pin.in.out") + .labelStyle(.titleAndIcon) + } + } + } + if showsClipExport, SongPlaybackRangeAvailability.supportsClipExport(song) { + Button { onEdit(.clip) } label: { + Label(SongPlaybackRangeEditor.clipMenuTitle, systemImage: SongPlaybackRangeEditor.clipSymbol) + .labelStyle(.titleAndIcon) + } + } + } +} diff --git a/Primuse/Views/Mac/PlayerMoreMenu.swift b/Primuse/Views/Mac/PlayerMoreMenu.swift index 969db5ce8..91618e4a7 100644 --- a/Primuse/Views/Mac/PlayerMoreMenu.swift +++ b/Primuse/Views/Mac/PlayerMoreMenu.swift @@ -887,20 +887,24 @@ struct PlayerMoreMenu: View { @ViewBuilder private var editingSubmenu: some View { if let rangeSong = playbackRangeSong { - // 播放时间段:设过时这一行就是开关(行尾写着时间段,开着打勾), - // 下面一行编辑;没设过时只有「设置播放时间段…」。 - if let range = SongPlaybackRangeStore.shared.range(for: rangeSong) { - playbackRangeToggleRow(song: rangeSong, range: range) - menuRow(title: "playback_range_edit", symbol: "slider.horizontal.3") { - playbackRangeEditorRequest = .init(song: rangeSong, purpose: .playbackRange) - } - } else { - menuRow(title: "playback_range_set", symbol: "selection.pin.in.out") { - playbackRangeEditorRequest = .init(song: rangeSong, purpose: .playbackRange) + if SongPlaybackRangeAvailability.supports(rangeSong) { + // 播放时间段:设过时这一行就是开关(行尾写着时间段,开着打勾), + // 下面一行编辑;没设过时只有「设置播放时间段…」。 + if let range = SongPlaybackRangeStore.shared.range(for: rangeSong) { + playbackRangeToggleRow(song: rangeSong, range: range) + menuRow(title: "playback_range_edit", symbol: "slider.horizontal.3") { + playbackRangeEditorRequest = .init(song: rangeSong, purpose: .playbackRange) + } + } else { + menuRow(title: "playback_range_set", symbol: "selection.pin.in.out") { + playbackRangeEditorRequest = .init(song: rangeSong, purpose: .playbackRange) + } } } - menuRow(title: "clip_export_menu_mac", symbol: SongPlaybackRangeEditor.clipSymbol) { - playbackRangeEditorRequest = .init(song: rangeSong, purpose: .clip) + if SongPlaybackRangeAvailability.supportsClipExport(rangeSong) { + menuRow(title: "clip_export_menu_mac", symbol: SongPlaybackRangeEditor.clipSymbol) { + playbackRangeEditorRequest = .init(song: rangeSong, purpose: .clip) + } } divider() } @@ -1222,11 +1226,12 @@ struct PlayerMoreMenu: View { return ShuffleLinkMenuState(songID: songID, library: library) } - /// 能设播放时间段的当前歌曲(整首);有声内容、Apple Music、电台没有这一项。 + /// 能设播放时间段或导出片段的当前条目(整首);Apple Music 与直播电台不提供。 private var playbackRangeSong: Song? { - guard !player.isAppleMusicMode, !player.isLiveRadio, !player.currentItemIsSpokenWord, + guard !player.isAppleMusicMode, !player.isLiveRadio, let song = player.currentSong?.withoutAppliedPlaybackRange, - SongPlaybackRangeAvailability.supports(song) else { return nil } + SongPlaybackRangeAvailability.supports(song) + || SongPlaybackRangeAvailability.supportsClipExport(song) else { return nil } return song } diff --git a/Primuse/Views/NowPlaying/NowPlayingView.swift b/Primuse/Views/NowPlaying/NowPlayingView.swift index e270f8796..fe4da2185 100644 --- a/Primuse/Views/NowPlaying/NowPlayingView.swift +++ b/Primuse/Views/NowPlaying/NowPlayingView.swift @@ -10993,7 +10993,7 @@ struct NowPlayingView: View { isSavingLibrarySong: libraryActions.isBusy, canDislike: player.canDislikeCurrentSong && !menuSuppressed.contains(.dislike) && shows(.dislike), isCurrentDisliked: isCurrentDisliked, - playbackRangeSong: isSpokenWord || player.isAppleMusicMode || player.isLiveRadio + playbackRangeSong: player.isAppleMusicMode || player.isLiveRadio || (!shows(.playbackRange) && !shows(.clipExport)) ? nil : player.currentSong?.withoutAppliedPlaybackRange, diff --git a/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift b/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift index 835324809..fd1806b26 100644 --- a/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift +++ b/Primuse/Views/NowPlaying/PodcastPlayerComponents.swift @@ -387,6 +387,54 @@ private struct PodcastUpNextRow: View { // MARK: - Menu items +/// 切去听音乐/电台后再回播客列表时展示的「恢复播客队列」横幅,一键恢复上次的 Up Next 队列。 +struct PodcastRememberedQueueBanner: View { + @Environment(AudioPlayerService.self) private var player + + var body: some View { + let _ = PodcastQueueMemoryStore.shared.memory + let _ = SpokenWordStore.shared.finishedAt.count + if let summary = player.rememberedPodcastQueueSummary { + HStack(spacing: 12) { + Image(systemName: "text.line.first.and.arrowtriangle.forward") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(ListeningSpace.podcast.tint) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: "\(String(localized: "up_next")) · \(summary.remainingCount)") + .font(.caption.weight(.semibold).monospacedDigit()) + .foregroundStyle(ListeningSpace.podcast.tint) + Text(verbatim: summary.lead.title) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + } + Spacer(minLength: 8) + Button("podcast_continue") { + Task { _ = await player.resumeRememberedPodcastQueue() } + } + .buttonStyle(.borderedProminent) + .tint(ListeningSpace.podcast.tint) + .controlSize(.small) + Button { + pmWithAnimation(.list) { + PodcastQueueMemoryStore.shared.clear() + } + } label: { + Image(systemName: "xmark") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel(Text("clear")) + } + .padding(12) + .background( + ListeningSpace.podcast.tint.opacity(0.10), + in: RoundedRectangle(cornerRadius: 12, style: .continuous) + ) + } + } +} + /// 更多菜单里「下载 / 取消下载」这一项。单独一个视图:下载进度一变只重画它,不惊动整个播放页。 /// 已经下好的不给「删除下载」:正在播的就是这个文件。 struct PodcastPlayerDownloadMenuItem: View { diff --git a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift index 8bd3404f0..a52d2bc43 100644 --- a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift +++ b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift @@ -357,6 +357,10 @@ struct PodcastEpisodeFeedView: View { .listRowSeparator(.hidden) #endif Section { + if player.rememberedPodcastQueueSummary != nil { + PodcastRememberedQueueBanner() + .listRowSeparator(.hidden) + } Picker("podcast_filter", selection: $filterRawValue) { Text("podcast_filter_unplayed").tag(PodcastEpisodeFilter.unplayed.rawValue) Text("podcast_filter_in_progress").tag(PodcastEpisodeFilter.inProgress.rawValue) diff --git a/PrimuseKit/Sources/PrimuseKit/Audio/AudioClipExportPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Audio/AudioClipExportPolicy.swift index 0550748f1..90e9c7477 100644 --- a/PrimuseKit/Sources/PrimuseKit/Audio/AudioClipExportPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Audio/AudioClipExportPolicy.swift @@ -77,6 +77,27 @@ public enum AudioClipExportPolicy { return SongPlaybackRange(start: start, end: end, isEnabled: true) } + /// Centers a spoken-word share clip window (default 30s) around `playhead`, + /// clamped cleanly inside `0...songDuration` so listeners immediately clip what + /// they just heard. + public static func centeredClipRange( + around playhead: TimeInterval, + songDuration: TimeInterval, + windowLength: TimeInterval = ringtoneMaximumLength + ) -> SongPlaybackRange? { + guard playhead.isFinite, songDuration.isFinite, songDuration >= minimumLength, + windowLength.isFinite, windowLength >= minimumLength else { return nil } + let span = min(songDuration, min(windowLength, clipMaximumLength)) + let clampedPlayhead = min(max(0, playhead), songDuration) + var start = max(0, clampedPlayhead - span / 2) + var end = start + span + if end > songDuration { + end = songDuration + start = max(0, end - span) + } + return SongPlaybackRange(start: start.rounded(.down), end: end.rounded(.down), isEnabled: true) + } + // MARK: - Fades public struct Fades: Equatable, Sendable { diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift index a5c5c7b47..0fcf203be 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift @@ -210,6 +210,36 @@ public enum PodcastEpisodeSearchPolicy { } } +/// 跨收听空间切离播客时保存的播客队列(当前集 + Up Next)在恢复时的裁剪策略: +/// 保留从当前位起尚未播完的单集顺序;若当前集已在别的设备标为听完,则自动推进到下一集未播单集。 +public enum PodcastQueueMemoryPolicy { + public static let maxStoredItems = 100 + + public struct Restored: Equatable, Sendable { + // crash-pattern: allow song-id-collection-property bounded remembered podcast queue capped at maxStoredItems (100) + public var songIDs: [String] + public var startIndex: Int + + public init(songIDs: [String], startIndex: Int) { + self.songIDs = songIDs + self.startIndex = startIndex + } + } + + public static func restored( + songIDs: [String], + currentIndex: Int, + isFinished: (String) -> Bool + ) -> Restored? { + guard !songIDs.isEmpty else { return nil } + let clamped = min(max(0, currentIndex), songIDs.count - 1) + let suffix = Array(songIDs[clamped...].prefix(maxStoredItems)) + let remaining = suffix.filter { !isFinished($0) } + guard !remaining.isEmpty else { return nil } + return Restored(songIDs: remaining, startIndex: 0) + } +} + public enum PodcastEpisodeListPolicy { /// `episodes` 约定是从新到旧(`PodcastFeedMerge` 的输出)。 public static func ordered(_ episodes: [PodcastEpisode], order: PodcastEpisodeOrder) -> [PodcastEpisode] { diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift index e8957c9cf..473ab0a2d 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastShowNotesTests.swift @@ -140,4 +140,32 @@ struct PodcastShowNotesChaptersTests { ) #expect(results.map(\.id) == ["s-2"]) } + + @Test("PodcastQueueMemoryPolicy skips finished episodes and preserves Up Next order") + func podcastQueueMemoryPolicyAndCenteredClipRange() throws { + let restored = try #require(PodcastQueueMemoryPolicy.restored( + songIDs: ["ep-0", "ep-1", "ep-2", "ep-3"], + currentIndex: 1, + isFinished: { $0 == "ep-1" } + )) + #expect(restored.songIDs == ["ep-2", "ep-3"]) + #expect(restored.startIndex == 0) + #expect(PodcastQueueMemoryPolicy.restored( + songIDs: ["ep-0", "ep-1"], + currentIndex: 1, + isFinished: { _ in true } + ) == nil) + + let middle = try #require(AudioClipExportPolicy.centeredClipRange(around: 600, songDuration: 3600)) + #expect(middle.start == 585) + #expect(middle.end == 615) + + let nearStart = try #require(AudioClipExportPolicy.centeredClipRange(around: 5, songDuration: 3600)) + #expect(nearStart.start == 0) + #expect(nearStart.end == 30) + + let nearEnd = try #require(AudioClipExportPolicy.centeredClipRange(around: 3595, songDuration: 3600)) + #expect(nearEnd.start == 3570) + #expect(nearEnd.end == 3600) + } } diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index 8627777ab..448730d46 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -527,4 +527,70 @@ final class ListeningSpacesReliabilityTests: XCTestCase { XCTAssertEqual(player.radioReconnectAttempt, 0) XCTAssertNotNil(player.radioReconnectTask) } + + func testClipExportAvailabilityAndPodcastQueueMemoryPersistence() throws { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("podcast-q-mem-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + cleanups.append { try? FileManager.default.removeItem(at: dir) } + + let ep1 = PodcastEpisode( + id: "podcast:mem-ep-1", + showID: "show-1", + guid: "g1", + title: "Episode 1", + duration: 1800, + enclosureURL: URL(string: "https://example.com/1.mp3")!, + firstSeenAt: Date() + ) + let ep2 = PodcastEpisode( + id: "podcast:mem-ep-2", + showID: "show-1", + guid: "g2", + title: "Episode 2", + duration: 1800, + enclosureURL: URL(string: "https://example.com/2.mp3")!, + firstSeenAt: Date() + ) + let show = PodcastShow( + id: "show-1", + feedURL: URL(string: "https://example.com/feed.xml")!, + title: "Show 1", + subscribedAt: Date() + ) + let epSong1 = PodcastPlaybackSong.song(for: ep1, show: show) + let epSong2 = PodcastPlaybackSong.song(for: ep2, show: show) + + // Podcast episodes support clip export while keeping playback range music-only. + XCTAssertFalse(SongPlaybackRangeAvailability.supports(epSong1)) + XCTAssertTrue(SongPlaybackRangeAvailability.supportsClipExport(epSong1)) + + let audiobook = Song( + id: "book-clip-\(UUID().uuidString)", + title: "Chapter 1", + duration: 2400, + fileFormat: .m4a, + filePath: "/books/ch1.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + XCTAssertFalse(SongPlaybackRangeAvailability.supports(audiobook)) + XCTAssertTrue(SongPlaybackRangeAvailability.supportsClipExport(audiobook)) + + let radioStation = RadioStation(id: "r1", name: "FM", streamURL: "https://radio.example.com/live.mp3") + XCTAssertFalse(SongPlaybackRangeAvailability.supportsClipExport(radioStation.playbackSong)) + + // PodcastQueueMemoryStore persists and reloads remembered podcast queues. + let storeURL = dir.appendingPathComponent("remembered-queue.json") + let queueStore = PodcastQueueMemoryStore(url: storeURL) + let player = AudioPlayerService() + player.queueEntries = [QueueEntry(song: epSong1), QueueEntry(song: epSong2)] + player.currentIndex = 0 + player.currentSong = epSong1 + player.rememberCurrentPodcastQueue(store: queueStore) + + let reloaded = PodcastQueueMemoryStore(url: storeURL) + XCTAssertEqual(reloaded.memory?.items.map(\.id), [epSong1.id, epSong2.id]) + XCTAssertEqual(reloaded.memory?.currentIndex, 0) + } } From a726e48dc322bd5e5d609bc8cbd5ce32e5dec6fc Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 21:45:53 -0500 Subject: [PATCH 11/15] =?UTF-8?q?=E8=A7=A3=E9=94=81=E5=8D=95=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=9C=89=E5=A3=B0=E4=B9=A6=E8=AF=A6=E6=83=85=E9=A1=B5?= =?UTF-8?q?=E5=86=85=E5=B5=8C=E7=AB=A0=E8=8A=82=E4=B8=8E=E4=B9=A6=E7=AD=BE?= =?UTF-8?q?=EF=BC=8C=E5=B9=B6=E6=96=B0=E5=A2=9E=E8=B7=A8=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E6=9C=89=E5=A3=B0=E6=94=B6=E5=90=AC=E7=BB=9F=E8=AE=A1=E6=9D=A1?= =?UTF-8?q?=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 16 + .../Audio/AudioPlayerService+SmartSpeed.swift | 11 +- .../Services/Library/PlayHistoryStore.swift | 16 +- .../Views/Library/SpokenWordLibraryView.swift | 134 +++----- .../SpokenWordSingleFileChaptersSection.swift | 320 ++++++++++++++++++ .../Views/Library/SpokenWordStatsCard.swift | 96 ++++++ .../Podcast/PodcastEpisodeDetailView.swift | 4 + .../SpokenWordListeningStatsPolicy.swift | 128 +++++++ .../SpokenWordListeningStatsPolicyTests.swift | 76 +++++ .../ListeningSpacesReliabilityTests.swift | 57 ++++ 10 files changed, 751 insertions(+), 107 deletions(-) create mode 100644 Primuse/Views/Library/SpokenWordSingleFileChaptersSection.swift create mode 100644 Primuse/Views/Library/SpokenWordStatsCard.swift create mode 100644 PrimuseKit/Sources/PrimuseKit/Listening/SpokenWordListeningStatsPolicy.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/Listening/SpokenWordListeningStatsPolicyTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index d1626225a..9f72d3a1b 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -1466,6 +1466,7 @@ 6C8FAAC4610ADCC03E172169 /* LyricsTextBackfillService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D222BDEED4421F58F8D1C957 /* LyricsTextBackfillService.swift */; }; 6CD54BD91641BE2633837541 /* TransitionEnvelopeProbe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47045D142911DBCEDDECED31 /* TransitionEnvelopeProbe.swift */; }; 6D40CEA5056A0E2A6527368E /* OfflineDownloadFileStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6519469238D7074B22F6F18E /* OfflineDownloadFileStore.swift */; }; + 6D4AFAB91486C5122A3AB918 /* SpokenWordSingleFileChaptersSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F6DB6C2C7431AA32B29A723 /* SpokenWordSingleFileChaptersSection.swift */; }; 6D4D076A60B72501F3B69CDE /* ScanCheckpointStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84411D12AE84C2609A04FB6B /* ScanCheckpointStore.swift */; }; 6D55C8029B8534FECC0F5DB2 /* AudioEffectsTransitionPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABDCB60F5EB44BCCD24DE3D1 /* AudioEffectsTransitionPolicy.swift */; }; 6D964D6877DEE572D7DFACE2 /* UPnPSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A7C2D0F07C125A333AC1046 /* UPnPSource.swift */; }; @@ -1492,6 +1493,7 @@ 6EDE5A5CD7699006B6EE5241 /* AMSMB2 in Frameworks */ = {isa = PBXBuildFile; productRef = BF09E2210DA639E4F6EBD3E8 /* AMSMB2 */; }; 6EE2B6F76F1B41FEDD0D7240 /* SpokenWordShelfStartupPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90536360A71BBADF88562393 /* SpokenWordShelfStartupPreview.swift */; }; 6EF6FA49561C4C1D9A44EBC6 /* PrimuseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B1E36F2FECF46E724081F983 /* PrimuseKit.framework */; }; + 6F06C4A8E71A0643E70E2C15 /* SpokenWordSingleFileChaptersSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F6DB6C2C7431AA32B29A723 /* SpokenWordSingleFileChaptersSection.swift */; }; 6F139A773725A49F443C3494 /* AIAvailabilityPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34C6D54A0624AAFCF3E1D472 /* AIAvailabilityPolicy.swift */; }; 6F182160588AE2FECBE3BFDD /* LibrarySnapshotSync+AutomaticUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FB4C97C255BE4EC76B38D39 /* LibrarySnapshotSync+AutomaticUpload.swift */; }; 6F1C5D1D40878DED923DB4E0 /* OfflineSettingsBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C674CD13BEA6A2470D749032 /* OfflineSettingsBackupTests.swift */; }; @@ -1591,6 +1593,7 @@ 75E15015A39C26CB480FCCBA /* MacSidebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBB01F11731477FA9B7F27D0 /* MacSidebar.swift */; }; 75E4B9E7E6C894010A781BDF /* ListeningIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38B0AF373DF20949FD8EF371 /* ListeningIntent.swift */; }; 75EB658DF4EA4FA781A5A776 /* ServerListeningStatsServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F300281145AEB5C3A9BC87 /* ServerListeningStatsServiceTests.swift */; }; + 75EE64ED7870699E59C92EE2 /* SpokenWordStatsCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD9B32231A69F289A96AD405 /* SpokenWordStatsCard.swift */; }; 7635925D8884E6C7EF5C9D57 /* ScrobbleService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51E683B96F169512351E3ACE /* ScrobbleService.swift */; }; 765CDF1C38171011299A3B47 /* SubsonicRatingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33DBF419A61F2A1604C966A1 /* SubsonicRatingTests.swift */; }; 767003E3F784EC1B246B7BAF /* AlbumGridView+Catalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = C68336285D3D3DA28DAF8094 /* AlbumGridView+Catalog.swift */; }; @@ -2797,7 +2800,9 @@ CEB337D49BD6067BDC01D6A2 /* LibrarySectionSwipeContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 082B366CC20E2B94D9771107 /* LibrarySectionSwipeContainer.swift */; }; CEC321453AC2E990053FA60C /* NowPlayingControlLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36367A1F3112A85481D1EEFE /* NowPlayingControlLayout.swift */; }; CEF5CEEB33A13003CE40EFBD /* NowPlayingCarouselTopBarPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62FBDAF01CA0F60F299A6DE8 /* NowPlayingCarouselTopBarPolicy.swift */; }; + CF05B74D55627D3AC8F70D09 /* SpokenWordStatsCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD9B32231A69F289A96AD405 /* SpokenWordStatsCard.swift */; }; CF2C65569F9F4785BA6CFBD9 /* ObjCExceptionUnwindPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA7173F45620F0015508F956 /* ObjCExceptionUnwindPolicy.swift */; }; + CF4A2BC7947C53B896BAC26D /* SpokenWordListeningStatsPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65F35BF7C8AC241BC0ABBEE2 /* SpokenWordListeningStatsPolicy.swift */; }; CF4E247C9F9B0A78A99BC8DF /* SVGArtworkRasterizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8972964595E4EC82C746FB2D /* SVGArtworkRasterizer.swift */; }; CF775FD46311E91C91E10E64 /* NowPlayingWatchView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21957BB2BE1463BE4D9884FB /* NowPlayingWatchView.swift */; }; CF8203EC228A6355A3DD68A9 /* PortableArtworkCollector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 357DFDFDC6F7F52D70377EC6 /* PortableArtworkCollector.swift */; }; @@ -4015,6 +4020,7 @@ 1F2F7456F3AC7BF84C2B9AFC /* ImmersiveKineticLyricsPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImmersiveKineticLyricsPolicy.swift; sourceTree = ""; }; 1F3348B436BFF62FC99E649F /* WatchOfflinePlayer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchOfflinePlayer.swift; sourceTree = ""; }; 1F4E9643FF737C29A9F6E686 /* MacLyricLineCommentsViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacLyricLineCommentsViewTests.swift; sourceTree = ""; }; + 1F6DB6C2C7431AA32B29A723 /* SpokenWordSingleFileChaptersSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordSingleFileChaptersSection.swift; sourceTree = ""; }; 1F6E94239552B76E1BD88FD9 /* LyricsSourcesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyricsSourcesView.swift; sourceTree = ""; }; 1F80DE6BB7AA236C830B490D /* LyricRomanizationAIExchange.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyricRomanizationAIExchange.swift; sourceTree = ""; }; 1F8BE745FB20EDEA78E90EEF /* MiniPlayerWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MiniPlayerWindowController.swift; sourceTree = ""; }; @@ -4728,6 +4734,7 @@ 65C163A6A5CD5B15DA0A6D1D /* LRCLIBHTTPErrorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LRCLIBHTTPErrorTests.swift; sourceTree = ""; }; 65CF531EA08CDFED93A005F3 /* hi */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = hi; path = hi.lproj/InfoPlist.strings; sourceTree = ""; }; 65D65B2970A8C9DF74733515 /* FavoriteEditorCandidatesCatalogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteEditorCandidatesCatalogTests.swift; sourceTree = ""; }; + 65F35BF7C8AC241BC0ABBEE2 /* SpokenWordListeningStatsPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordListeningStatsPolicy.swift; sourceTree = ""; }; 65FEC761CBDB0C4C6A6FC60A /* AudioPlayerService+CastCustomHeaders.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AudioPlayerService+CastCustomHeaders.swift"; sourceTree = ""; }; 6603576133F7798EFB9267D0 /* CloudDirectoryNameStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudDirectoryNameStore.swift; sourceTree = ""; }; 66190DBA8D3523EDE74EED81 /* MacKeyboardShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacKeyboardShortcuts.swift; sourceTree = ""; }; @@ -5538,6 +5545,7 @@ BD2F3A502AE584D82D1C5061 /* TransitionBoundaryPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransitionBoundaryPolicy.swift; sourceTree = ""; }; BD34CAC5AD7BB10FD3FE08AC /* TransitionCurve.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransitionCurve.swift; sourceTree = ""; }; BD66BB78A62DF53FDEE661DF /* PlaybackChunkRetryPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaybackChunkRetryPolicy.swift; sourceTree = ""; }; + BD9B32231A69F289A96AD405 /* SpokenWordStatsCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordStatsCard.swift; sourceTree = ""; }; BDC5ED08076B47DEE8ECB3AA /* NowPlayingWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowPlayingWidget.swift; sourceTree = ""; }; BDE7001BDFD168DC7EBC16D5 /* DebugScanSourceAtLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugScanSourceAtLaunchTests.swift; sourceTree = ""; }; BDEFF03F694CEEA426716816 /* LibraryCatalog+SongListPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibraryCatalog+SongListPage.swift"; sourceTree = ""; }; @@ -7150,6 +7158,7 @@ B05811C18E59641E8805290C /* SongDiscovery.swift */, 3F646DD4C72C434291F5DFAD /* SongListeningTraits.swift */, 301FB8BB0CBD1785553072A8 /* SongRadioMix.swift */, + 65F35BF7C8AC241BC0ABBEE2 /* SpokenWordListeningStatsPolicy.swift */, ); path = Listening; sourceTree = ""; @@ -8157,6 +8166,8 @@ 830C711D433ABB20BD76CE82 /* SpokenWordCatalogShelf.swift */, 27DD45712F9E0206213AB3FA /* SpokenWordLibraryView.swift */, 90536360A71BBADF88562393 /* SpokenWordShelfStartupPreview.swift */, + 1F6DB6C2C7431AA32B29A723 /* SpokenWordSingleFileChaptersSection.swift */, + BD9B32231A69F289A96AD405 /* SpokenWordStatsCard.swift */, 9F7380ABF7CFF416B08F01F2 /* TagEditorView.swift */, 22E87BBC6E0A7C293A818F11 /* TagEditorView+Queue.swift */, ); @@ -11115,6 +11126,7 @@ A8F621F3D5FDB8AA73B28B4E /* SpokenWordFolderRules.swift in Sources */, 09BF55DBA6ACA077811FF2B3 /* SpokenWordIntroOutro.swift in Sources */, ACF4DD6564BDBB969E2CE93C /* SpokenWordListeningPolicy.swift in Sources */, + CF4A2BC7947C53B896BAC26D /* SpokenWordListeningStatsPolicy.swift in Sources */, 1102517160C3798B332009EF /* SpokenWordNowPlayingPolicy.swift in Sources */, 02EF505F84B9837C24BE6AB7 /* SpokenWordPartTitleLabel.swift in Sources */, 847C73CBCB90E184FD0DD8B2 /* SpokenWordShelfStartupSnapshot.swift in Sources */, @@ -12100,6 +12112,8 @@ 620C22596174B16A2958B096 /* SpokenWordLibraryView.swift in Sources */, 7814030E97D0D88E7252DC4D /* SpokenWordPlayerComponents.swift in Sources */, CB67DE99E578703451D95323 /* SpokenWordShelfStartupPreview.swift in Sources */, + 6D4AFAB91486C5122A3AB918 /* SpokenWordSingleFileChaptersSection.swift in Sources */, + 75EE64ED7870699E59C92EE2 /* SpokenWordStatsCard.swift in Sources */, 4364BBE73E5E16055CBA24B9 /* SpokenWordStore.swift in Sources */, 0210526C4C63B35683700C39 /* SpokenWordTranscriptOffsetStore.swift in Sources */, 0E919053B51EF248F6C69955 /* SpokenWordTranscriptSelection.swift in Sources */, @@ -13325,6 +13339,8 @@ 278054AFB875BFD0D4548D29 /* SpokenWordLibraryView.swift in Sources */, 77D0B826FFF2C7ECF3507191 /* SpokenWordPlayerComponents.swift in Sources */, 6EE2B6F76F1B41FEDD0D7240 /* SpokenWordShelfStartupPreview.swift in Sources */, + 6F06C4A8E71A0643E70E2C15 /* SpokenWordSingleFileChaptersSection.swift in Sources */, + CF05B74D55627D3AC8F70D09 /* SpokenWordStatsCard.swift in Sources */, 325C09DC9D9271795E966AAD /* SpokenWordStore.swift in Sources */, C01BCE8A6DD90C0295B369BB /* SpokenWordTranscriptOffsetStore.swift in Sources */, 186A53281B796ED97981409B /* SpokenWordTranscriptSelection.swift in Sources */, diff --git a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift index e050d9139..e1592903f 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift @@ -169,16 +169,7 @@ final class SpokenWordSmartSpeedSavings { /// 设置里显示的「已节省」:几小时几分,不到一分钟显示秒。 var formattedTotal: String { - let seconds = Int64(totalSeconds.rounded(.down)) - let style: Duration.UnitsFormatStyle - if seconds >= 3_600 { - style = .units(allowed: [.hours, .minutes], width: .abbreviated) - } else if seconds >= 60 { - style = .units(allowed: [.minutes], width: .abbreviated) - } else { - style = .units(allowed: [.seconds], width: .abbreviated, zeroValueUnits: .show(length: 1)) - } - return Duration.seconds(seconds).formatted(style) + SpokenWordListeningStatsPolicy.formattedDuration(totalSeconds) } } diff --git a/Primuse/Services/Library/PlayHistoryStore.swift b/Primuse/Services/Library/PlayHistoryStore.swift index 2d231c8ad..dbb70be12 100644 --- a/Primuse/Services/Library/PlayHistoryStore.swift +++ b/Primuse/Services/Library/PlayHistoryStore.swift @@ -466,16 +466,24 @@ extension PlayHistoryStore { return entries.filter { context.space(for: $0) == .music } } - /// Seconds spent on spoken word in `range` (calendar windows, like the - /// stats page). - func spokenWordListeningSeconds(in range: Range, now: Date = Date(), calendar: Calendar = ListeningCalendar.current) -> TimeInterval { + /// Seconds spent in `space` during `range` (calendar windows, like the + /// stats page and spoken-word/podcast shelf strips). + func listeningSeconds(for space: ListeningSpace, in range: Range, now: Date = Date(), calendar: Calendar = ListeningCalendar.current) -> TimeInterval { let context = classification let cutoff = range.statisticsStartDate(now: now, calendar: calendar) return Self.listenedSeconds(entries.filter { - $0.playedAt.timeIntervalSinceReferenceDate >= cutoff.timeIntervalSinceReferenceDate && $0.playedAt.timeIntervalSinceReferenceDate <= now.timeIntervalSinceReferenceDate && context.space(for: $0) == .spokenWord + $0.playedAt.timeIntervalSinceReferenceDate >= cutoff.timeIntervalSinceReferenceDate + && $0.playedAt.timeIntervalSinceReferenceDate <= now.timeIntervalSinceReferenceDate + && context.space(for: $0) == space }) } + /// Seconds spent on spoken word in `range` (calendar windows, like the + /// stats page). + func spokenWordListeningSeconds(in range: Range, now: Date = Date(), calendar: Calendar = ListeningCalendar.current) -> TimeInterval { + listeningSeconds(for: .spokenWord, in: range, now: now, calendar: calendar) + } + nonisolated static func listenedSeconds(_ entries: [Entry]) -> TimeInterval { entries.reduce(0) { $0 + ($1.listenedSec.isFinite ? max(0, $1.listenedSec) : 0) } } diff --git a/Primuse/Views/Library/SpokenWordLibraryView.swift b/Primuse/Views/Library/SpokenWordLibraryView.swift index dc5cd46b7..101eedb1a 100644 --- a/Primuse/Views/Library/SpokenWordLibraryView.swift +++ b/Primuse/Views/Library/SpokenWordLibraryView.swift @@ -780,6 +780,10 @@ struct SpokenWordShelfContent: View { } #endif + if findQuery == nil, section == .all, snapshot.isPrepared, !isStartupPreview { + SpokenWordListeningStatsStrip(space: .spokenWord) + } + if !shelf.isEmpty || (section == .all && !finished.isEmpty) { VStack(alignment: .leading, spacing: 12) { HStack { @@ -1054,22 +1058,11 @@ struct SpokenWordShelfContent: View { ) } } - if book.items.count > 1 { - SpokenWordBookLink(bookID: book.id) { - cell - } - .buttonStyle(.pmPressable) - .accessibilityIdentifier("spokenWord.book." + book.id) - } else { - Button { - SpokenWordBookSupport.play(book, songs: songs, from: nil, player: player) - } label: { - cell - } - .buttonStyle(.pmPressable) - .contentShape(Rectangle()) - .accessibilityIdentifier("spokenWord.book." + book.id) + SpokenWordBookLink(bookID: book.id) { + cell } + .buttonStyle(.pmPressable) + .accessibilityIdentifier("spokenWord.book." + book.id) } @ViewBuilder @@ -1392,17 +1385,12 @@ private struct SpokenWordNowListeningCard: View { } .contentShape(Rectangle()) - if book.items.count > 1 { - SpokenWordBookLink(bookID: book.id) { - content - } - .buttonStyle(.plain) - .contentShape(Rectangle()) - .accessibilityElement(children: .combine) - } else { + SpokenWordBookLink(bookID: book.id) { content - .accessibilityElement(children: .combine) } + .buttonStyle(.plain) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) } } @@ -1521,73 +1509,23 @@ struct SpokenWordBookDetailView: View { let book = entry.book let songs = entry.songs let songsByID = Dictionary(songs.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) - SpokenWordChapterList(items: book.items) { - header(book, songs: songs) - } row: { index, item in - Button { - SpokenWordBookSupport.play(book, songs: songs, from: item.id, player: player) - } label: { - SpokenWordChapterItemRow( - item: item, - number: index + 1, - isResumeItem: item.id == book.resumeItemID && book.canContinue, - isPlaying: player.isPlaying && player.currentSong?.id == item.id, - isRepeating: player.isRepeatingSpokenWordItem(id: item.id) - ) - } - .buttonStyle(.plain) - .contentShape(Rectangle()) - .loadsOfflineAudioSnapshot(for: songsByID[item.id]) - .contextMenu { - let repeating = player.isRepeatingSpokenWordItem(id: item.id) - Button { - if let songIndex = songs.firstIndex(where: { $0.id == item.id }) { - player.playSpokenWordBookRepeating(songs: songs, startingAt: songIndex, bookID: book.id) - } - } label: { - Label( - String(localized: repeating - ? "spoken_word_repeat_chapter_stop" - : "spoken_word_repeat_chapter_play"), - systemImage: "repeat.1" - ) - } - Button { - store.markFinished(!item.isFinished, songIDs: [item.id]) - } label: { - Label( - item.isFinished - ? String(localized: "spoken_word_mark_unfinished") - : String(localized: "spoken_word_mark_finished"), - systemImage: item.isFinished ? "circle" : "checkmark.circle" + Group { + if book.items.count == 1, let singleItem = book.items.first, let singleSong = songs.first { + SpokenWordSingleFileDetailBody(book: book, item: singleItem, song: singleSong) { + header(book, songs: songs) + } fallbackRow: { + SpokenWordBookChapterRowButton( + book: book, songs: songs, song: singleSong, index: 0, item: singleItem ) } - Button { - // Everything before this chapter counts as - // heard: the usual way to pick up a series - // that was started elsewhere. - let earlier = book.items.prefix(index).map(\.id) - store.markFinished(true, songIDs: Array(earlier)) - } label: { - Label( - String(localized: "spoken_word_mark_previous_finished"), - systemImage: "checkmark.circle.badge.questionmark" + } else { + SpokenWordChapterList(items: book.items) { + header(book, songs: songs) + } row: { index, item in + SpokenWordBookChapterRowButton( + book: book, songs: songs, song: songsByID[item.id], index: index, item: item ) } - .disabled(index == 0) - if item.position != nil { - Button(role: .destructive) { - store.clearPosition(forSongID: item.id) - } label: { - Label( - String(localized: "spoken_word_clear_progress"), - systemImage: "arrow.counterclockwise" - ) - } - } - if let song = songsByID[item.id] { - SongOfflineMenuSection(song: song) - } } } #if os(iOS) @@ -2255,11 +2193,9 @@ private struct SpokenWordBookListRow: View { .foregroundStyle(tint) .accessibilityLabel(Text("spoken_word_finished")) } - if book.chapterCount > 1 { - Image(systemName: "chevron.right") - .font(.caption.weight(.semibold)) - .foregroundStyle(.tertiary) - } + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) } .multilineTextAlignment(.leading) .padding(.vertical, 10) @@ -3072,15 +3008,27 @@ enum SpokenWordBookSupport { /// Plays the book as the queue, so finishing one chapter continues into /// the next one rather than into unrelated music. Starts from `itemID`, - /// or from where the listener left off. + /// or from where the listener left off. When `position` is supplied (for + /// example tapping an embedded chapter or bookmark inside a single-file + /// M4B), opens directly at that offset. @MainActor static func play( _ book: SpokenWordBook, songs: [Song], from itemID: String?, + at position: TimeInterval? = nil, player: AudioPlayerService ) { guard let index = prepareStart(of: book, songs: songs, from: itemID) else { return } + let target = songs[index] + if let position, player.currentSong?.id == target.id { + player.seek(to: max(0, position), startPlaying: true) + player.rememberSpokenWordPosition(force: true) + return + } + if let position { + player.pendingSpokenWordSeekOverride = (target.id, max(0, position)) + } Task { await player.play(queue: songs, startingAt: index) } } diff --git a/Primuse/Views/Library/SpokenWordSingleFileChaptersSection.swift b/Primuse/Views/Library/SpokenWordSingleFileChaptersSection.swift new file mode 100644 index 000000000..3809450e5 --- /dev/null +++ b/Primuse/Views/Library/SpokenWordSingleFileChaptersSection.swift @@ -0,0 +1,320 @@ +import PrimuseKit +import SwiftUI + +/// 单文件有声书(如整本 M4B / M4A / MP3)的详情页主体: +/// 自动解析当前播放器、已生成或本机/离线缓存文件内嵌的章节列表,支持按章节浏览与一键跳转播放, +/// 若有书签也会顺带列出;找不到章节时退回显示单文件曲目行,保证完整操作入口不缺失。 +struct SpokenWordSingleFileDetailBody: View { + let book: SpokenWordBook + let item: SpokenWordBookItem + let song: Song + @ViewBuilder var header: () -> Header + @ViewBuilder var fallbackRow: () -> FallbackRow + + @Environment(AudioPlayerService.self) private var player + @Environment(MusicLibrary.self) private var library + @Environment(SourceManager.self) private var sourceManager + @Environment(\.openURL) private var openURL + @State private var loadedEmbeddedChapters: [MediaChapter] = [] + + private var tint: Color { ListeningSpace.spokenWord.tint } + + private var inset: CGFloat { + #if os(macOS) + PMSpace.xxxl + #else + 16 + #endif + } + + private var resolvedChapters: [MediaChapter] { + if player.currentSong?.id == song.id, !player.spokenWordChapters.isEmpty { + return player.spokenWordChapters + } + if let generated = library.generatedChapters(for: song.id), !generated.isEmpty { + return generated + } + return loadedEmbeddedChapters + } + + private var activePlaybackPosition: TimeInterval? { + if player.currentSong?.id == song.id { + return player.currentTime + } + return item.position + } + + var body: some View { + let _ = SpokenWordStore.shared.revision + let _ = library.generatedChaptersRevision + let chapters = resolvedChapters + let rows = SpokenWordSingleFileChapterPolicy.rows( + from: chapters, + totalDuration: max(item.duration, song.duration), + playbackPosition: activePlaybackPosition, + isFinished: item.isFinished + ) + let bookmarks = SpokenWordStore.shared.bookmarks(forSongID: song.id) + let isPlayingThisSong = player.isPlaying && player.currentSong?.id == song.id + + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + header() + .padding(.horizontal, inset) + .padding(.vertical, 16) + + if !rows.isEmpty { + sectionHeader(titleKey: "chapters_title", count: rows.count) + ForEach(rows) { row in + chapterButton(row, isPlayingSong: isPlayingThisSong) + .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading) + .padding(.horizontal, inset) + .overlay(alignment: .bottom) { + Divider() + .padding(.leading, inset + 40) + .padding(.trailing, inset) + } + } + } else { + fallbackRow() + .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading) + .padding(.horizontal, inset) + .overlay(alignment: .bottom) { + Divider() + .padding(.leading, inset + 40) + .padding(.trailing, inset) + } + } + + if !bookmarks.isEmpty { + sectionHeader(titleKey: "spoken_word_bookmarks_title", count: bookmarks.count) + .padding(.top, 16) + ForEach(bookmarks) { bookmark in + bookmarkRow(bookmark) + .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) + .padding(.horizontal, inset) + .overlay(alignment: .bottom) { + Divider() + .padding(.leading, inset + 40) + .padding(.trailing, inset) + } + } + } + } + } + .accessibilityIdentifier("spokenWord.chapters") + .pmExtendsUnderVerticalBar() + .task(id: "\(song.id)-\(sourceManager.offlineAudioSnapshotRevision)") { + guard player.currentSong?.id != song.id || player.spokenWordChapters.isEmpty, + library.generatedChapters(for: song.id)?.isEmpty != false else { return } + guard let localURL = await AudioClipExporter.onDeviceFile(for: song, sourceManager: sourceManager) else { + loadedEmbeddedChapters = [] + return + } + let parsed = await Task.detached(priority: .userInitiated) { + MediaChapter.embeddedChapters(inLocalFile: localURL) + }.value + guard !Task.isCancelled else { return } + loadedEmbeddedChapters = parsed + } + } + + private func sectionHeader(titleKey: LocalizedStringKey, count: Int) -> some View { + HStack(spacing: 8) { + Text(titleKey) + .font(.headline) + .accessibilityAddTraits(.isHeader) + Text(verbatim: "\(count)") + .font(.subheadline.monospacedDigit()) + .foregroundStyle(.secondary) + Spacer(minLength: 0) + } + .padding(.horizontal, inset) + .padding(.top, 8) + .padding(.bottom, 6) + } + + private func chapterButton(_ row: SpokenWordSingleFileChapterRow, isPlayingSong: Bool) -> some View { + HStack(spacing: 10) { + Button { + SpokenWordBookSupport.play( + book, + songs: [song], + from: song.id, + at: row.chapter.startTime, + player: player + ) + } label: { + HStack(spacing: 10) { + ZStack { + if row.isCompleted { + Image(systemName: "checkmark.circle.fill") + .foregroundStyle(.secondary) + } else if row.isCurrent && isPlayingSong { + Image(systemName: "waveform") + .foregroundStyle(tint) + } else { + Text(verbatim: "\(row.index + 1)") + .font(.footnote.monospacedDigit()) + .foregroundStyle(row.isCurrent ? tint : .secondary) + } + } + .frame(minWidth: 28, alignment: .center) + + VStack(alignment: .leading, spacing: 4) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(row.chapter.title) + .font(.body) + .foregroundStyle(row.isCurrent ? tint : (row.isCompleted ? .secondary : .primary)) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + Text(verbatim: ChapterTimeFormatter.string(from: row.chapter.startTime)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + if let duration = row.duration, duration > 0 { + Text(verbatim: "· \(ChapterTimeFormatter.string(from: duration))") + .font(.caption.monospacedDigit()) + .foregroundStyle(.tertiary) + } + } + if row.isCurrent, row.progress > 0 { + SpokenWordProgressBar(value: row.progress, tint: tint) + .frame(maxWidth: 200) + } + } + } + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if let link = row.chapter.webURL { + Button { + openURL(link) + } label: { + Image(systemName: "arrow.up.right.square") + .font(.subheadline) + .foregroundStyle(tint) + .frame(width: 32, height: 32) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + } + + private func bookmarkRow(_ bookmark: SpokenWordBookmark) -> some View { + Button { + SpokenWordBookSupport.play( + book, + songs: [song], + from: song.id, + at: bookmark.position, + player: player + ) + } label: { + HStack(spacing: 10) { + Image(systemName: "bookmark.fill") + .font(.footnote) + .foregroundStyle(tint) + .frame(minWidth: 28, alignment: .center) + Text(bookmark.title) + .font(.subheadline) + .foregroundStyle(.primary) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + Text(verbatim: ChapterTimeFormatter.string(from: bookmark.position)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .contextMenu { + Button(role: .destructive) { + SpokenWordStore.shared.removeBookmark(id: bookmark.id, songID: song.id) + } label: { + Label("delete", systemImage: "trash") + } + } + } +} + +/// 书详情页里的一条曲目章节行(供多文件章节列表与单文件无内嵌章节时的兜底行复用)。 +struct SpokenWordBookChapterRowButton: View { + let book: SpokenWordBook + let songs: [Song] // crash-pattern: allow library-array-property bounded chapters of a single audiobook + let song: Song? + let index: Int + let item: SpokenWordBookItem + + @Environment(AudioPlayerService.self) private var player + + private var store: SpokenWordStore { SpokenWordStore.shared } + + var body: some View { + Button { + SpokenWordBookSupport.play(book, songs: songs, from: item.id, player: player) + } label: { + SpokenWordChapterItemRow( + item: item, + number: index + 1, + isResumeItem: item.id == book.resumeItemID && book.canContinue, + isPlaying: player.isPlaying && player.currentSong?.id == item.id, + isRepeating: player.isRepeatingSpokenWordItem(id: item.id) + ) + } + .buttonStyle(.plain) + .contentShape(Rectangle()) + .loadsOfflineAudioSnapshot(for: song) + .contextMenu { + let repeating = player.isRepeatingSpokenWordItem(id: item.id) + Button { + if let songIndex = songs.firstIndex(where: { $0.id == item.id }) { + player.playSpokenWordBookRepeating(songs: songs, startingAt: songIndex, bookID: book.id) + } + } label: { + Label( + String(localized: repeating + ? "spoken_word_repeat_chapter_stop" + : "spoken_word_repeat_chapter_play"), + systemImage: "repeat.1" + ) + } + Button { + store.markFinished(!item.isFinished, songIDs: [item.id]) + } label: { + Label( + item.isFinished + ? String(localized: "spoken_word_mark_unfinished") + : String(localized: "spoken_word_mark_finished"), + systemImage: item.isFinished ? "circle" : "checkmark.circle" + ) + } + Button { + let earlier = book.items.prefix(index).map(\.id) + store.markFinished(true, songIDs: Array(earlier)) + } label: { + Label( + String(localized: "spoken_word_mark_previous_finished"), + systemImage: "checkmark.circle.badge.questionmark" + ) + } + .disabled(index == 0) + if item.position != nil { + Button(role: .destructive) { + store.clearPosition(forSongID: item.id) + } label: { + Label( + String(localized: "spoken_word_clear_progress"), + systemImage: "arrow.counterclockwise" + ) + } + } + if let song { + SongOfflineMenuSection(song: song) + } + } + } +} diff --git a/Primuse/Views/Library/SpokenWordStatsCard.swift b/Primuse/Views/Library/SpokenWordStatsCard.swift new file mode 100644 index 000000000..03b85b6b2 --- /dev/null +++ b/Primuse/Views/Library/SpokenWordStatsCard.swift @@ -0,0 +1,96 @@ +import PrimuseKit +import SwiftUI + +/// 跨空间复用的有声收听统计条(本周时长 / 历史累计 / 智能速度节省时间)。 +/// 复用 `PlayHistoryStore` 与 `SpokenWordSmartSpeedSavings`,自动按 `ListeningSpace` 染色; +/// 尚无有效收听与省时记录时自动隐藏,不占版面。 +struct SpokenWordListeningStatsStrip: View { + let space: ListeningSpace + + private var history: PlayHistoryStore { PlayHistoryStore.shared } + private var savings: SpokenWordSmartSpeedSavings { SpokenWordSmartSpeedSavings.shared } + + var body: some View { + let _ = history.classificationRevision + let summary = SpokenWordListeningStatsSummary( + weekSeconds: history.listeningSeconds(for: space, in: .week), + allTimeSeconds: history.listeningSeconds(for: space, in: .all), + smartSpeedSavedSeconds: savings.totalSeconds + ) + if summary.hasAnyActivity { + HStack(spacing: 12) { + metricColumn( + icon: "calendar", + titleKey: "stats_range_week", + value: SpokenWordListeningStatsPolicy.formattedDuration(summary.weekSeconds) + ) + divider + metricColumn( + icon: space.systemImage, + titleKey: "stats_all_time_total", + value: SpokenWordListeningStatsPolicy.formattedDuration(summary.allTimeSeconds) + ) + divider + metricColumn( + icon: "gauge.with.dots.needle.67percent", + titleKey: "spoken_word_smart_speed_saved", + value: SpokenWordListeningStatsPolicy.formattedDuration(summary.smartSpeedSavedSeconds) + ) + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(cardBackground) + .overlay(cardBorder) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("spokenWord.statsStrip.\(space.rawValue)") + } + } + + private func metricColumn(icon: String, titleKey: LocalizedStringKey, value: String) -> some View { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 4) { + Image(systemName: icon) + .font(.caption2.weight(.semibold)) + .foregroundStyle(space.tint) + Text(titleKey) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Text(verbatim: value) + .font(.subheadline.weight(.semibold).monospacedDigit()) + .foregroundStyle(.primary) + .lineLimit(1) + .minimumScaleFactor(0.85) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var divider: some View { + Rectangle() + .fill(Color.secondary.opacity(0.18)) + .frame(width: 1, height: 26) + } + + @ViewBuilder + private var cardBackground: some View { + #if os(macOS) + RoundedRectangle(cornerRadius: PMRadius.m10, style: .continuous) + .fill(PMColor.card) + #else + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color.secondary.opacity(0.08)) + #endif + } + + @ViewBuilder + private var cardBorder: some View { + #if os(macOS) + RoundedRectangle(cornerRadius: PMRadius.m10, style: .continuous) + .strokeBorder(PMColor.cardBorder, lineWidth: 0.5) + #else + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(space.tint.opacity(0.14), lineWidth: 0.5) + #endif + } +} diff --git a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift index a52d2bc43..990fd0c47 100644 --- a/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift +++ b/Primuse/Views/Podcast/PodcastEpisodeDetailView.swift @@ -357,6 +357,10 @@ struct PodcastEpisodeFeedView: View { .listRowSeparator(.hidden) #endif Section { + if searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + SpokenWordListeningStatsStrip(space: .podcast) + .listRowSeparator(.hidden) + } if player.rememberedPodcastQueueSummary != nil { PodcastRememberedQueueBanner() .listRowSeparator(.hidden) diff --git a/PrimuseKit/Sources/PrimuseKit/Listening/SpokenWordListeningStatsPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Listening/SpokenWordListeningStatsPolicy.swift new file mode 100644 index 000000000..f1de196a8 --- /dev/null +++ b/PrimuseKit/Sources/PrimuseKit/Listening/SpokenWordListeningStatsPolicy.swift @@ -0,0 +1,128 @@ +import Foundation + +/// 播客与有声书收听统计摘要(本周 / 累计 / 智能速度节省时间),供书架与播客页的统计条复用。 +public struct SpokenWordListeningStatsSummary: Equatable, Sendable { + public let weekSeconds: TimeInterval + public let allTimeSeconds: TimeInterval + public let smartSpeedSavedSeconds: TimeInterval + + public init( + weekSeconds: TimeInterval, + allTimeSeconds: TimeInterval, + smartSpeedSavedSeconds: TimeInterval + ) { + self.weekSeconds = Self.sanitized(weekSeconds) + self.allTimeSeconds = Self.sanitized(allTimeSeconds) + self.smartSpeedSavedSeconds = Self.sanitized(smartSpeedSavedSeconds) + } + + /// 避免刚装应用或误点几秒就展示全零统计条。 + public var hasAnyActivity: Bool { + weekSeconds >= 60 || allTimeSeconds >= 60 || smartSpeedSavedSeconds >= 30 + } + + private static func sanitized(_ value: TimeInterval) -> TimeInterval { + value.isFinite && value > 0 ? value : 0 + } +} + +public enum SpokenWordListeningStatsPolicy { + /// 统一的有声时长与智能速度节省时长格式化:>=1h 显示小时和分钟,>=1m 显示分钟,<1m 显示秒。 + public static func formattedDuration(_ seconds: TimeInterval) -> String { + let clamped = seconds.isFinite && seconds > 0 ? Int64(seconds.rounded(.down)) : 0 + let style: Duration.UnitsFormatStyle + if clamped >= 3_600 { + style = .units(allowed: [.hours, .minutes], width: .abbreviated) + } else if clamped >= 60 { + style = .units(allowed: [.minutes], width: .abbreviated) + } else { + style = .units(allowed: [.seconds], width: .abbreviated, zeroValueUnits: .show(length: 1)) + } + return Duration.seconds(clamped).formatted(style) + } +} + +/// 单文件有声书(如整本 M4B / MP3)详情页展示的一行章节状态。 +public struct SpokenWordSingleFileChapterRow: Equatable, Sendable, Identifiable { + public let index: Int + public let chapter: MediaChapter + public let duration: TimeInterval? + public let isCompleted: Bool + public let isCurrent: Bool + public let progress: Double + + public var id: String { "\(index)-\(chapter.id)" } + + public init( + index: Int, + chapter: MediaChapter, + duration: TimeInterval?, + isCompleted: Bool, + isCurrent: Bool, + progress: Double + ) { + self.index = index + self.chapter = chapter + self.duration = duration + self.isCompleted = isCompleted + self.isCurrent = isCurrent + self.progress = progress + } +} + +public enum SpokenWordSingleFileChapterPolicy { + /// 由内嵌或生成章节列表结合总时长与播放进度,生成单文件书详情页的章节行模型。 + public static func rows( + from chapters: [MediaChapter], + totalDuration: TimeInterval, + playbackPosition: TimeInterval?, + isFinished: Bool + ) -> [SpokenWordSingleFileChapterRow] { + guard !chapters.isEmpty else { return [] } + let safeTotal = totalDuration.isFinite && totalDuration > 0 ? totalDuration : 0 + let position: TimeInterval? = { + guard let playbackPosition, playbackPosition.isFinite, playbackPosition >= 0 else { return nil } + return playbackPosition + }() + let activeIndex: Int? = { + guard !isFinished, let position else { return nil } + return chapters.chapterIndex(at: position) + }() + + return chapters.enumerated().map { index, chapter in + let nextStart = index + 1 < chapters.count ? chapters[index + 1].startTime : nil + let resolvedEnd: TimeInterval? = { + if let end = chapter.endTime, end.isFinite, end > chapter.startTime { + return end + } + if let nextStart, nextStart.isFinite, nextStart > chapter.startTime { + return nextStart + } + if safeTotal > chapter.startTime { + return safeTotal + } + return nil + }() + let duration = resolvedEnd.map { max(0, $0 - chapter.startTime) } + let isCurrent = activeIndex == index + let isCompleted: Bool = { + if isFinished { return true } + guard let activeIndex else { return false } + return index < activeIndex + }() + let progress: Double = { + if isCompleted { return 1 } + guard isCurrent, let position, let duration, duration > 0 else { return 0 } + return min(1, max(0, (position - chapter.startTime) / duration)) + }() + return SpokenWordSingleFileChapterRow( + index: index, + chapter: chapter, + duration: duration, + isCompleted: isCompleted, + isCurrent: isCurrent, + progress: progress + ) + } + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Listening/SpokenWordListeningStatsPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Listening/SpokenWordListeningStatsPolicyTests.swift new file mode 100644 index 000000000..208948c68 --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Listening/SpokenWordListeningStatsPolicyTests.swift @@ -0,0 +1,76 @@ +import Foundation +import PrimuseKit +import Testing + +@Suite("SpokenWordListeningStatsPolicy and Single-File Chapter Policy") +struct SpokenWordListeningStatsPolicyTests { + + @Test("Stats summary hides below threshold and sanitizes invalid inputs") + func summaryVisibilityAndSanitization() { + let empty = SpokenWordListeningStatsSummary( + weekSeconds: -10, + allTimeSeconds: .nan, + smartSpeedSavedSeconds: 10 + ) + #expect(empty.weekSeconds == 0) + #expect(empty.allTimeSeconds == 0) + #expect(!empty.hasAnyActivity) + + let activeByListen = SpokenWordListeningStatsSummary( + weekSeconds: 90, + allTimeSeconds: 90, + smartSpeedSavedSeconds: 0 + ) + #expect(activeByListen.hasAnyActivity) + + let activeBySavings = SpokenWordListeningStatsSummary( + weekSeconds: 0, + allTimeSeconds: 0, + smartSpeedSavedSeconds: 45 + ) + #expect(activeBySavings.hasAnyActivity) + + #expect(!SpokenWordListeningStatsPolicy.formattedDuration(0).isEmpty) + #expect(!SpokenWordListeningStatsPolicy.formattedDuration(3_720).isEmpty) + } + + @Test("Single-file chapter rows compute durations, active chapter, and completion state") + func singleFileChapterRowComputation() { + let chapters = [ + MediaChapter(startTime: 0, title: "Prologue"), + MediaChapter(startTime: 600, title: "Chapter 1"), + MediaChapter(startTime: 1_800, title: "Chapter 2", endTime: 2_700), + ] + + let inProgress = SpokenWordSingleFileChapterPolicy.rows( + from: chapters, + totalDuration: 3_000, + playbackPosition: 1_200, + isFinished: false + ) + #expect(inProgress.count == 3) + #expect(inProgress[0].duration == 600) + #expect(inProgress[0].isCompleted) + #expect(!inProgress[0].isCurrent) + #expect(inProgress[0].progress == 1) + + #expect(inProgress[1].duration == 1_200) + #expect(!inProgress[1].isCompleted) + #expect(inProgress[1].isCurrent) + #expect(abs(inProgress[1].progress - 0.5) < 0.001) + + #expect(inProgress[2].duration == 900) + #expect(!inProgress[2].isCompleted) + #expect(!inProgress[2].isCurrent) + #expect(inProgress[2].progress == 0) + + let finished = SpokenWordSingleFileChapterPolicy.rows( + from: chapters, + totalDuration: 3_000, + playbackPosition: 200, + isFinished: true + ) + #expect(finished.allSatisfy { $0.isCompleted }) + #expect(finished.allSatisfy { !$0.isCurrent }) + } +} diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index 448730d46..8cb0ebba9 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -593,4 +593,61 @@ final class ListeningSpacesReliabilityTests: XCTestCase { XCTAssertEqual(reloaded.memory?.items.map(\.id), [epSong1.id, epSong2.id]) XCTAssertEqual(reloaded.memory?.currentIndex, 0) } + + func testPlayHistoryListeningSecondsSeparatesPodcastAndAudiobookAndSingleFileChapterSeekOverride() throws { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("history-stats-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + cleanups.append { try? FileManager.default.removeItem(at: dir) } + + let now = Date() + let historyURL = dir.appendingPathComponent("play_history.json") + let suite = "primuse.test.history.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + cleanups.append { defaults.removePersistentDomain(forName: suite) } + + let history = PlayHistoryStore(storeURL: historyURL, defaults: defaults) + let audiobook = Song( + id: "single-m4b-\(UUID().uuidString)", + title: "Dune", + artistName: "Frank Herbert", + duration: 72_000, + fileFormat: .m4a, + filePath: "/books/dune.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + let episode = PodcastEpisode( + id: "podcast:stats-ep-1", + showID: "stats-show", + guid: "stats-g1", + title: "Stats Episode", + duration: 3_600, + enclosureURL: URL(string: "https://example.com/stats.mp3")!, + firstSeenAt: now + ) + let show = PodcastShow( + id: "stats-show", + feedURL: URL(string: "https://example.com/feed.xml")!, + title: "Stats Show", + subscribedAt: now + ) + let podcastSong = PodcastPlaybackSong.song(for: episode, show: show) + history.spokenWordSongIDs.insert(audiobook.id) + history.record(song: audiobook, startedAt: now.addingTimeInterval(-900), listenedSec: 900) + history.record(song: podcastSong, startedAt: now.addingTimeInterval(-1_500), listenedSec: 1_500) + + XCTAssertEqual(history.listeningSeconds(for: .spokenWord, in: .week, now: now), 900, accuracy: 0.5) + XCTAssertEqual(history.spokenWordListeningSeconds(in: .week, now: now), 900, accuracy: 0.5) + XCTAssertEqual(history.listeningSeconds(for: .podcast, in: .week, now: now), 1_500, accuracy: 0.5) + XCTAssertEqual(history.listeningSeconds(for: .podcast, in: .all, now: now), 1_500, accuracy: 0.5) + + let bookItem = SpokenWordBookItem(song: audiobook) + let book = try XCTUnwrap(SpokenWordBookGrouping.books(from: [bookItem]).first) + let player = AudioPlayerService() + cleanups.append { player.stop() } + SpokenWordBookSupport.play(book, songs: [audiobook], from: audiobook.id, at: 1_800, player: player) + XCTAssertEqual(player.pendingSpokenWordSeekOverride?.songID, audiobook.id) + XCTAssertEqual(player.pendingSpokenWordSeekOverride?.position ?? -1, 1_800, accuracy: 0.1) + } } From 7ff6b1f31ee361c6bffe4a55ff1e6383def96e26 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 22:46:29 -0500 Subject: [PATCH 12/15] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8F=82=E8=80=83=20Ov?= =?UTF-8?q?ercast=20=E7=9A=84=E6=92=AD=E5=AE=A2=E6=99=BA=E8=83=BD=E5=88=97?= =?UTF-8?q?=E8=A1=A8=EF=BC=8C=E6=94=AF=E6=8C=81=E8=8A=82=E7=9B=AE=E8=8C=83?= =?UTF-8?q?=E5=9B=B4=E3=80=81=E4=BC=98=E5=85=88=E7=BD=AE=E9=A1=B6=E3=80=81?= =?UTF-8?q?=E6=97=B6=E9=95=BF=E4=B8=8A=E9=99=90=E4=B8=8E=20iCloud=20?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E5=90=8C=E6=AD=A5=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 18 + .../Resources/ar.lproj/Localizable.strings | 20 + .../Resources/de.lproj/Localizable.strings | 20 + .../Resources/en.lproj/Localizable.strings | 20 + .../Resources/es-MX.lproj/Localizable.strings | 20 + .../Resources/fr.lproj/Localizable.strings | 20 + .../Resources/hi.lproj/Localizable.strings | 20 + .../Resources/ja.lproj/Localizable.strings | 20 + .../Resources/ko.lproj/Localizable.strings | 20 + .../Resources/pl.lproj/Localizable.strings | 20 + .../Resources/pt-BR.lproj/Localizable.strings | 20 + .../Resources/ru.lproj/Localizable.strings | 20 + .../Resources/th.lproj/Localizable.strings | 20 + .../Resources/tr.lproj/Localizable.strings | 20 + .../Resources/uk.lproj/Localizable.strings | 20 + .../zh-Hans.lproj/Localizable.strings | 20 + .../zh-Hant.lproj/Localizable.strings | 20 + .../Podcast/PodcastSmartPlaylistStore.swift | 124 ++++ .../Views/Podcast/PodcastLibraryView.swift | 36 +- .../Podcast/PodcastSmartPlaylistsViews.swift | 624 ++++++++++++++++++ .../Podcast/PodcastLibraryPolicy.swift | 2 +- .../Podcast/PodcastSmartPlaylist.swift | 237 +++++++ .../Podcast/PodcastSmartPlaylistTests.swift | 115 ++++ PrimuseTests/PodcastReliabilityTests.swift | 34 + 24 files changed, 1479 insertions(+), 31 deletions(-) create mode 100644 Primuse/Services/Podcast/PodcastSmartPlaylistStore.swift create mode 100644 Primuse/Views/Podcast/PodcastSmartPlaylistsViews.swift create mode 100644 PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSmartPlaylist.swift create mode 100644 PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index 9f72d3a1b..e29d399f5 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -1394,6 +1394,7 @@ 677769AB511D06F3889FB970 /* NowPlayingStylePreviewScreens.swift in Sources */ = {isa = PBXBuildFile; fileRef = F27A05589D788FC47B4394B1 /* NowPlayingStylePreviewScreens.swift */; }; 6792A3FA5C148C38B1A0336E /* QueueRowIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2BAE3560D34292CB5DB2E61 /* QueueRowIdentity.swift */; }; 67AD2125DA2834D6C40DE63D /* ListeningWidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 704D629527CC26A59E4AA639 /* ListeningWidgetSnapshot.swift */; }; + 67AEEE1A153834ABE46FE36B /* PodcastSmartPlaylistStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = F48A908A854913A9BCAF15CB /* PodcastSmartPlaylistStore.swift */; }; 67BC7F85E03B6315DDA1AAE8 /* TVMetadataEnricher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E730878DCF4CBE75CF3D260 /* TVMetadataEnricher.swift */; }; 67C3ED30DCD901480622FD27 /* LibraryCatalog+SourceFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 230FCD2AF52D494D032E4A20 /* LibraryCatalog+SourceFiles.swift */; }; 67D45D818469B9D73A8AB157 /* BundleToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08C701D152027AB58C6C5B14 /* BundleToken.swift */; }; @@ -1436,6 +1437,7 @@ 6A9CC005D03D0B2C5E2A1381 /* ReleaseDateLibraryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD43CE7FEC4CBBA59ED3317 /* ReleaseDateLibraryView.swift */; }; 6AAE51EC0751E0A5E6A6DF7D /* AlbumRecommender.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB59AC36A915B7617A1447B6 /* AlbumRecommender.swift */; }; 6AB27D68701A40328A50C61B /* CloudTokenRefreshPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F1A2B6733CA4871B9249585 /* CloudTokenRefreshPolicy.swift */; }; + 6ABD004AABF2310F568FD864 /* PodcastSmartPlaylistsViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 104286074C7A173F2CE80C0B /* PodcastSmartPlaylistsViews.swift */; }; 6ACA18E6F7B7EDFC5E728C03 /* MacAudioCacheSyncView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0920BE117D1955C3E68DBEB /* MacAudioCacheSyncView.swift */; }; 6ADA1D28B7DC574BA462BACD /* MacWidgetLyricsPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCA9A512D4650F0F0D201DD4 /* MacWidgetLyricsPublisherTests.swift */; }; 6AE046838D6546471C6E2457 /* MusicScraperFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6255A91A1DE2B2C344A5491 /* MusicScraperFactory.swift */; }; @@ -1504,6 +1506,7 @@ 6F5899A91CEA7698A1F8C916 /* SmartNudgeOverlay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E6D8F9E72019BB5755F6F3C /* SmartNudgeOverlay.swift */; }; 6F5EC1303A1E72CEA7C88E1C /* NowPlayingCarouselExploreFace.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF122AE6759A483677132DF6 /* NowPlayingCarouselExploreFace.swift */; }; 6F7789BD834850AFCF14F44B /* GuangYaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7604FDFCC31C876592711589 /* GuangYaSource.swift */; }; + 6F84E2D7193A5CE28DDDA844 /* PodcastSmartPlaylistsViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 104286074C7A173F2CE80C0B /* PodcastSmartPlaylistsViews.swift */; }; 6FAF270BF179A3DF9200D7F1 /* DiscoveryFeatureTable+P4b2.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECE7734C2750D53EC6EB3732 /* DiscoveryFeatureTable+P4b2.swift */; }; 6FD343D31FDCA5EB52F81D2C /* ITunesScraper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1254C88A6F33F2A3A73C2CA /* ITunesScraper.swift */; }; 6FE53DDA9986F85A3897E582 /* EQPreset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B77E91ECC8568E876861750 /* EQPreset.swift */; }; @@ -2343,6 +2346,7 @@ AD675AE2312AF7C41C011A20 /* SemanticAlbumResultCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69918F7E72B36379DC66865F /* SemanticAlbumResultCard.swift */; }; AD67A69E72837A8AA7866B3A /* MetadataBackfillService.swift in Sources */ = {isa = PBXBuildFile; fileRef = B56809F1C697EF691877166D /* MetadataBackfillService.swift */; }; AD6FEFE184462870ADBFC294 /* EmbeddedMetadataWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10D8687352CA14B5A8B9D5A2 /* EmbeddedMetadataWriter.swift */; }; + AD7B3FED960A9DFA6D0BE751 /* PodcastSmartPlaylistStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = F48A908A854913A9BCAF15CB /* PodcastSmartPlaylistStore.swift */; }; AD8CD5AF66AE2A6B9D80B106 /* MediaServerSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = D799C291E3FDAA06B4A33EBA /* MediaServerSource.swift */; }; ADA970DC684E05BF6D6AE5C0 /* WidgetConfiguration.strings in Resources */ = {isa = PBXBuildFile; fileRef = BC23AD54CECCD6607FE810C6 /* WidgetConfiguration.strings */; }; ADB400688500A470719EBC83 /* PMVerticalBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A84D97F97A35EB01DF0F61E /* PMVerticalBar.swift */; }; @@ -2477,6 +2481,7 @@ B6D097684F4D0927BB7880C3 /* EqualizerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 181EE28124D9CD151E0338E1 /* EqualizerView.swift */; }; B6E40F285ACF849440298317 /* MergedListeningStatsViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43CE46C7398D1ABDD485676B /* MergedListeningStatsViews.swift */; }; B6E7BB06598F59D02E16C726 /* ConfigurableScraper.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFBD55481DE18F95FCC74F76 /* ConfigurableScraper.swift */; }; + B6F2BD640673B578153F9B8D /* PodcastSmartPlaylist.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82F4C4C397E16BDB85DC4D03 /* PodcastSmartPlaylist.swift */; }; B70C8CCEA516D4837B161860 /* WebDAVPathPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C86199FBD39A645D5AD53CB /* WebDAVPathPolicy.swift */; }; B71770DEE92F0EB8C0F8D470 /* TrustedHTTPTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABB95B932C07091233475361 /* TrustedHTTPTransport.swift */; }; B749D535BCCD28C1835E42C3 /* LibraryCatalogReader+P4a2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35B8B07FDE7B2E757C09FFD2 /* LibraryCatalogReader+P4a2.swift */; }; @@ -2905,6 +2910,7 @@ D89EBA3CE540A502564D336A /* ExternalPlaylistImport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9261E365FCA7CA1AF09E36F8 /* ExternalPlaylistImport.swift */; }; D8A692C9983764E57DAAEBEC /* CarPlayEditorComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFF7D33EE6AA248113308216 /* CarPlayEditorComponents.swift */; }; D8AD2317FD632CA23698007F /* MacQueuePanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57617F084B3B9CEF89DD3541 /* MacQueuePanel.swift */; }; + D8B7DD22B3AADB5A2DD457C9 /* PodcastSmartPlaylistStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = F48A908A854913A9BCAF15CB /* PodcastSmartPlaylistStore.swift */; }; D8C9A9D9B8AA79B55ED96EEC /* EmbeddedKaraokeTrackMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54170B0C66457D556A9AC0CE /* EmbeddedKaraokeTrackMenu.swift */; }; D8EBD25096403908B40EDC03 /* DuplicateSongsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A41D663BB9CFFF6AF3D062D6 /* DuplicateSongsView.swift */; }; D8F2DE031EB6C1683C409E59 /* WatchSessionBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1729792F7E0AC649901171B8 /* WatchSessionBridge.swift */; }; @@ -3884,6 +3890,7 @@ 0FED0B4693AC78E5BCEDF088 /* CloudHTTPRetryPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudHTTPRetryPolicy.swift; sourceTree = ""; }; 0FFF9D9DAA3CE6E23AF64DCC /* HomeFolderBrowserReleasedTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeFolderBrowserReleasedTests.swift; sourceTree = ""; }; 10101623A825B5DA960255C3 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "zh-Hans.lproj/InfoPlist.strings"; sourceTree = ""; }; + 104286074C7A173F2CE80C0B /* PodcastSmartPlaylistsViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PodcastSmartPlaylistsViews.swift; sourceTree = ""; }; 107520E4BD60F9B01B1F3963 /* NowPlayingCompactLandscapeLayoutPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowPlayingCompactLandscapeLayoutPolicy.swift; sourceTree = ""; }; 1079C4E17A1281851B04DF3B /* MusicLibrary+ScanCommit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MusicLibrary+ScanCommit.swift"; sourceTree = ""; }; 10921CA6E8EF4E5856C9AF9E /* SpokenWordWidgetPublisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordWidgetPublisher.swift; sourceTree = ""; }; @@ -5024,6 +5031,7 @@ 82C951D83E89D86B5BBCCF22 /* BuiltInCloudCredentials.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BuiltInCloudCredentials.swift; sourceTree = ""; }; 82DE90F4A0194B1571C2E0A2 /* PMLayoutChangeFade.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PMLayoutChangeFade.swift; sourceTree = ""; }; 82F1DA780C1EE2D2FECA07E6 /* MusicVideoLibraryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicVideoLibraryView.swift; sourceTree = ""; }; + 82F4C4C397E16BDB85DC4D03 /* PodcastSmartPlaylist.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PodcastSmartPlaylist.swift; sourceTree = ""; }; 82FEDDB18A0292FEC6CB614B /* DaoLiYuSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DaoLiYuSource.swift; sourceTree = ""; }; 830C711D433ABB20BD76CE82 /* SpokenWordCatalogShelf.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordCatalogShelf.swift; sourceTree = ""; }; 8321DC84502AE307E1C3B466 /* FnMusicServiceClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FnMusicServiceClient.swift; sourceTree = ""; }; @@ -6035,6 +6043,7 @@ F44E04BAF67DF37C98C9FDAF /* AnimatedArtworkDataView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnimatedArtworkDataView.swift; sourceTree = ""; }; F4534081CB97190875B18B30 /* KaraokeLyricsPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KaraokeLyricsPolicy.swift; sourceTree = ""; }; F45777B346934B7C89B279F3 /* BaiduWriteReplayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaiduWriteReplayTests.swift; sourceTree = ""; }; + F48A908A854913A9BCAF15CB /* PodcastSmartPlaylistStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PodcastSmartPlaylistStore.swift; sourceTree = ""; }; F4B66447535097048881AC2A /* ImmersiveWatercolorTheaterScene.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImmersiveWatercolorTheaterScene.swift; sourceTree = ""; }; F4CD481DA5AA6555CF38C4D9 /* zh-Hant */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hant"; path = "zh-Hant.lproj/Localizable.strings"; sourceTree = ""; }; F4CE8AA87E85B5327174700C /* CancellableResultRace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CancellableResultRace.swift; sourceTree = ""; }; @@ -6948,6 +6957,7 @@ EAE2612A6C872FDE582BFD30 /* PodcastFormat.swift */, F130E9C212ECBE573672CF94 /* PodcastNetwork.swift */, 8E19295BCFC34DE6AD761717 /* PodcastQueueMemoryStore.swift */, + F48A908A854913A9BCAF15CB /* PodcastSmartPlaylistStore.swift */, F330312B7C4C3D055018B052 /* PodcastStore.swift */, ); path = Podcast; @@ -8328,6 +8338,7 @@ 79D258CCAFC472A6F334BD11 /* PodcastMacHome.swift */, 6DD4D35A322A1518A9261B04 /* PodcastMacLibraryView.swift */, C57C25D9301AA85C1C54DDD2 /* PodcastShowDetailView.swift */, + 104286074C7A173F2CE80C0B /* PodcastSmartPlaylistsViews.swift */, ); path = Podcast; sourceTree = ""; @@ -9287,6 +9298,7 @@ 8D5809673781FF8F935A6E82 /* PodcastModels.swift */, 447A893CDF10838438421587 /* PodcastOPML.swift */, 77F1BFF69C22EC9A13B6EF3E /* PodcastShowNotes.swift */, + 82F4C4C397E16BDB85DC4D03 /* PodcastSmartPlaylist.swift */, EC329259B54D3F75A5383DBD /* PodcastSubscriptionSync.swift */, 6A4131ED5151550113E19983 /* PodcastText.swift */, CE54E5F4531DDDB62B59D76B /* SpokenWordVideoPolicy.swift */, @@ -10925,6 +10937,7 @@ 022DBA47DAEBEEDB9A60298F /* PodcastModels.swift in Sources */, 83BD61441C4320D03E79D2D4 /* PodcastOPML.swift in Sources */, F60EA717AEA810A15AE4A479 /* PodcastShowNotes.swift in Sources */, + B6F2BD640673B578153F9B8D /* PodcastSmartPlaylist.swift in Sources */, 1DE8176C3410A0E53CBCD5DF /* PodcastSubscriptionSync.swift in Sources */, E71FA426EFC830D0C5A66E13 /* PodcastText.swift in Sources */, A8539792D315E46370C4EC10 /* PreparedPlaybackStartPolicy.swift in Sources */, @@ -11933,6 +11946,8 @@ BB64B903F9CA13210F5D1F8F /* PodcastQueueMemoryStore.swift in Sources */, 76AEBD3B7024DC2AF50352A9 /* PodcastResumeItem+Recent.swift in Sources */, 21DFD7099F0DD7869C388C9A /* PodcastShowDetailView.swift in Sources */, + AD7B3FED960A9DFA6D0BE751 /* PodcastSmartPlaylistStore.swift in Sources */, + 6F84E2D7193A5CE28DDDA844 /* PodcastSmartPlaylistsViews.swift in Sources */, C1AF76796CED17D4DEA48A8F /* PodcastStore.swift in Sources */, 394D37B9DB69A52EB39009CD /* PortableArtworkCollector.swift in Sources */, 075D7C95D650AA429CD771A6 /* PortableSnapshotPreparationRun.swift in Sources */, @@ -12369,6 +12384,7 @@ 33A0AF5B686C79EAA245F3C2 /* PodcastFormat.swift in Sources */, 9CEDDC85144C3D65E30A9126 /* PodcastNetwork.swift in Sources */, AD57051335F88BBBEF21A15C /* PodcastQueueMemoryStore.swift in Sources */, + D8B7DD22B3AADB5A2DD457C9 /* PodcastSmartPlaylistStore.swift in Sources */, 37E8C2C8A7FB12D5968E8F45 /* PodcastStore.swift in Sources */, BF01CD833FA8C8CDAD5EDD7D /* PortableArtworkCollector.swift in Sources */, 4C75E4027A9C62034D152C42 /* PortableSnapshotPreparationRun.swift in Sources */, @@ -13160,6 +13176,8 @@ B14110E1D09DFB2F9474DE2C /* PodcastQueueMemoryStore.swift in Sources */, 5B31F6587BB8D65E29EEFED5 /* PodcastResumeItem+Recent.swift in Sources */, A6B492B42C0C4E7F687AA3A2 /* PodcastShowDetailView.swift in Sources */, + 67AEEE1A153834ABE46FE36B /* PodcastSmartPlaylistStore.swift in Sources */, + 6ABD004AABF2310F568FD864 /* PodcastSmartPlaylistsViews.swift in Sources */, 369C66911BC2EA6FA3E31EDC /* PodcastStore.swift in Sources */, CF8203EC228A6355A3DD68A9 /* PortableArtworkCollector.swift in Sources */, E3FFDF70E3C4D236E5C8DD38 /* PortableSnapshotPreparationRun.swift in Sources */, diff --git a/Primuse/Resources/ar.lproj/Localizable.strings b/Primuse/Resources/ar.lproj/Localizable.strings index ee0cb1092..3235dada1 100644 --- a/Primuse/Resources/ar.lproj/Localizable.strings +++ b/Primuse/Resources/ar.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "كل الحلقات"; "podcast_keep_episodes_count_format" = "أحدث %lld"; "podcast_search_episodes_prompt" = "البحث في الحلقات"; +"podcast_smart_playlists_title" = "قوائم ذكية"; +"podcast_smart_playlists_empty_title" = "إنشاء قائمة ذكية"; +"podcast_smart_playlists_empty_subtitle" = "رتّب الحلقات تلقائيًا حسب البرنامج والأولوية والحالة والمدة."; +"podcast_smart_episode_count_format" = "%lld حلقة"; +"podcast_smart_duration_limit" = "الحد الأقصى للمدة"; +"podcast_smart_duration_any" = "أي مدة"; +"podcast_smart_duration_limit_format" = "≤ %lld د"; +"podcast_smart_priority_count_format" = "%lld أولوية"; +"podcast_smart_rules_section" = "القواعد"; +"podcast_smart_sort_title" = "الترتيب"; +"podcast_sort_shortest" = "الأقصر أولًا"; +"podcast_sort_longest" = "الأطول أولًا"; +"podcast_smart_shows_section" = "البرامج"; +"podcast_smart_shows_scope" = "نطاق البرامج"; +"podcast_smart_shows_all" = "كل البرامج"; +"podcast_smart_shows_include" = "البرامج المحددة فقط"; +"podcast_smart_shows_exclude" = "الكل عدا المحددة"; +"podcast_smart_priority_shows" = "البرامج ذات الأولوية"; +"podcast_smart_priority_shows_footer" = "تظهر حلقات البرامج ذات الأولوية دائمًا في الأعلى بهذا الترتيب."; +"podcast_smart_add_priority_show" = "إضافة برنامج ذي أولوية"; diff --git a/Primuse/Resources/de.lproj/Localizable.strings b/Primuse/Resources/de.lproj/Localizable.strings index 0bee6eb1d..a9aa461f7 100644 --- a/Primuse/Resources/de.lproj/Localizable.strings +++ b/Primuse/Resources/de.lproj/Localizable.strings @@ -8471,3 +8471,23 @@ "podcast_keep_episodes_all" = "Alle Folgen"; "podcast_keep_episodes_count_format" = "Neueste %lld"; "podcast_search_episodes_prompt" = "Folgen durchsuchen"; +"podcast_smart_playlists_title" = "Intelligente Playlists"; +"podcast_smart_playlists_empty_title" = "Intelligente Playlist erstellen"; +"podcast_smart_playlists_empty_subtitle" = "Warteschlangen automatisch nach Show, Priorität, Status und Dauer zusammenstellen."; +"podcast_smart_episode_count_format" = "%lld Folgen"; +"podcast_smart_duration_limit" = "Max. Dauer"; +"podcast_smart_duration_any" = "Beliebige Länge"; +"podcast_smart_duration_limit_format" = "≤ %lld Min."; +"podcast_smart_priority_count_format" = "%lld priorisiert"; +"podcast_smart_rules_section" = "Regeln"; +"podcast_smart_sort_title" = "Sortierung"; +"podcast_sort_shortest" = "Kürzeste zuerst"; +"podcast_sort_longest" = "Längste zuerst"; +"podcast_smart_shows_section" = "Shows"; +"podcast_smart_shows_scope" = "Enthaltene Shows"; +"podcast_smart_shows_all" = "Alle Shows"; +"podcast_smart_shows_include" = "Nur ausgewählte Shows"; +"podcast_smart_shows_exclude" = "Alle außer ausgewählten"; +"podcast_smart_priority_shows" = "Priorisierte Shows"; +"podcast_smart_priority_shows_footer" = "Folgen priorisierter Shows erscheinen in dieser Reihenfolge immer ganz oben."; +"podcast_smart_add_priority_show" = "Priorisierte Show hinzufügen"; diff --git a/Primuse/Resources/en.lproj/Localizable.strings b/Primuse/Resources/en.lproj/Localizable.strings index cadac9ebc..2798155f0 100644 --- a/Primuse/Resources/en.lproj/Localizable.strings +++ b/Primuse/Resources/en.lproj/Localizable.strings @@ -8233,3 +8233,23 @@ "podcast_keep_episodes_all" = "All Episodes"; "podcast_keep_episodes_count_format" = "Latest %lld"; "podcast_search_episodes_prompt" = "Search episodes"; +"podcast_smart_playlists_title" = "Smart Playlists"; +"podcast_smart_playlists_empty_title" = "Create a Smart Playlist"; +"podcast_smart_playlists_empty_subtitle" = "Auto-build listening queues by show, priority order, status, and duration."; +"podcast_smart_episode_count_format" = "%lld episodes"; +"podcast_smart_duration_limit" = "Max Duration"; +"podcast_smart_duration_any" = "Any Length"; +"podcast_smart_duration_limit_format" = "≤ %lld min"; +"podcast_smart_priority_count_format" = "%lld priority"; +"podcast_smart_rules_section" = "Rules"; +"podcast_smart_sort_title" = "Sort Order"; +"podcast_sort_shortest" = "Shortest First"; +"podcast_sort_longest" = "Longest First"; +"podcast_smart_shows_section" = "Shows"; +"podcast_smart_shows_scope" = "Include Shows"; +"podcast_smart_shows_all" = "All Shows"; +"podcast_smart_shows_include" = "Selected Shows Only"; +"podcast_smart_shows_exclude" = "All Except Selected"; +"podcast_smart_priority_shows" = "Priority Shows"; +"podcast_smart_priority_shows_footer" = "Episodes from priority shows always appear at the top of this playlist in the order listed."; +"podcast_smart_add_priority_show" = "Add Priority Show"; diff --git a/Primuse/Resources/es-MX.lproj/Localizable.strings b/Primuse/Resources/es-MX.lproj/Localizable.strings index 528c7d8a1..aa7c44884 100644 --- a/Primuse/Resources/es-MX.lproj/Localizable.strings +++ b/Primuse/Resources/es-MX.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "Todos los episodios"; "podcast_keep_episodes_count_format" = "Últimos %lld"; "podcast_search_episodes_prompt" = "Buscar episodios"; +"podcast_smart_playlists_title" = "Listas inteligentes"; +"podcast_smart_playlists_empty_title" = "Crear lista inteligente"; +"podcast_smart_playlists_empty_subtitle" = "Crea colas automáticas según programas, prioridad, estado y duración."; +"podcast_smart_episode_count_format" = "%lld episodios"; +"podcast_smart_duration_limit" = "Duración máxima"; +"podcast_smart_duration_any" = "Cualquier duración"; +"podcast_smart_duration_limit_format" = "≤ %lld min"; +"podcast_smart_priority_count_format" = "%lld prioritarios"; +"podcast_smart_rules_section" = "Reglas"; +"podcast_smart_sort_title" = "Orden"; +"podcast_sort_shortest" = "Más cortos primero"; +"podcast_sort_longest" = "Más largos primero"; +"podcast_smart_shows_section" = "Programas"; +"podcast_smart_shows_scope" = "Programas incluidos"; +"podcast_smart_shows_all" = "Todos los programas"; +"podcast_smart_shows_include" = "Solo los seleccionados"; +"podcast_smart_shows_exclude" = "Todos excepto los seleccionados"; +"podcast_smart_priority_shows" = "Programas prioritarios"; +"podcast_smart_priority_shows_footer" = "Los episodios de los programas prioritarios siempre aparecen primero en este orden."; +"podcast_smart_add_priority_show" = "Agregar programa prioritario"; diff --git a/Primuse/Resources/fr.lproj/Localizable.strings b/Primuse/Resources/fr.lproj/Localizable.strings index 36df585a3..300350681 100644 --- a/Primuse/Resources/fr.lproj/Localizable.strings +++ b/Primuse/Resources/fr.lproj/Localizable.strings @@ -8471,3 +8471,23 @@ "podcast_keep_episodes_all" = "Tous les épisodes"; "podcast_keep_episodes_count_format" = "%lld derniers"; "podcast_search_episodes_prompt" = "Rechercher des épisodes"; +"podcast_smart_playlists_title" = "Listes intelligentes"; +"podcast_smart_playlists_empty_title" = "Créer une liste intelligente"; +"podcast_smart_playlists_empty_subtitle" = "Composez des files d’écoute selon les émissions, priorités, statuts et durées."; +"podcast_smart_episode_count_format" = "%lld épisodes"; +"podcast_smart_duration_limit" = "Durée maximale"; +"podcast_smart_duration_any" = "Toutes durées"; +"podcast_smart_duration_limit_format" = "≤ %lld min"; +"podcast_smart_priority_count_format" = "%lld prioritaires"; +"podcast_smart_rules_section" = "Règles"; +"podcast_smart_sort_title" = "Tri"; +"podcast_sort_shortest" = "Plus courts d’abord"; +"podcast_sort_longest" = "Plus longs d’abord"; +"podcast_smart_shows_section" = "Émissions"; +"podcast_smart_shows_scope" = "Émissions incluses"; +"podcast_smart_shows_all" = "Toutes les émissions"; +"podcast_smart_shows_include" = "Sélection uniquement"; +"podcast_smart_shows_exclude" = "Toutes sauf la sélection"; +"podcast_smart_priority_shows" = "Émissions prioritaires"; +"podcast_smart_priority_shows_footer" = "Les épisodes des émissions prioritaires apparaissent toujours en haut dans cet ordre."; +"podcast_smart_add_priority_show" = "Ajouter une émission prioritaire"; diff --git a/Primuse/Resources/hi.lproj/Localizable.strings b/Primuse/Resources/hi.lproj/Localizable.strings index 87b470f50..a6cea1fee 100644 --- a/Primuse/Resources/hi.lproj/Localizable.strings +++ b/Primuse/Resources/hi.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "सभी एपिसोड"; "podcast_keep_episodes_count_format" = "नवीनतम %lld"; "podcast_search_episodes_prompt" = "एपिसोड खोजें"; +"podcast_smart_playlists_title" = "स्मार्ट प्लेलिस्ट"; +"podcast_smart_playlists_empty_title" = "स्मार्ट प्लेलिस्ट बनाएँ"; +"podcast_smart_playlists_empty_subtitle" = "शो, प्राथमिकता, स्थिति और अवधि के अनुसार अपने-आप कतार बनाएँ।"; +"podcast_smart_episode_count_format" = "%lld एपिसोड"; +"podcast_smart_duration_limit" = "अधिकतम अवधि"; +"podcast_smart_duration_any" = "कोई भी अवधि"; +"podcast_smart_duration_limit_format" = "≤ %lld मि."; +"podcast_smart_priority_count_format" = "%lld प्राथमिकता"; +"podcast_smart_rules_section" = "नियम"; +"podcast_smart_sort_title" = "क्रमबद्धता"; +"podcast_sort_shortest" = "सबसे छोटा पहले"; +"podcast_sort_longest" = "सबसे लंबा पहले"; +"podcast_smart_shows_section" = "शो"; +"podcast_smart_shows_scope" = "शामिल शो"; +"podcast_smart_shows_all" = "सभी शो"; +"podcast_smart_shows_include" = "केवल चुने गए शो"; +"podcast_smart_shows_exclude" = "चुने गए शो छोड़कर"; +"podcast_smart_priority_shows" = "प्राथमिकता वाले शो"; +"podcast_smart_priority_shows_footer" = "प्राथमिकता वाले शो के एपिसोड इस क्रम में हमेशा सबसे ऊपर रहेंगे।"; +"podcast_smart_add_priority_show" = "प्राथमिकता शो जोड़ें"; diff --git a/Primuse/Resources/ja.lproj/Localizable.strings b/Primuse/Resources/ja.lproj/Localizable.strings index dff419cbd..c11adeda7 100644 --- a/Primuse/Resources/ja.lproj/Localizable.strings +++ b/Primuse/Resources/ja.lproj/Localizable.strings @@ -8472,3 +8472,23 @@ "podcast_keep_episodes_all" = "すべてのエピソード"; "podcast_keep_episodes_count_format" = "最新 %lld 件"; "podcast_search_episodes_prompt" = "エピソードを検索"; +"podcast_smart_playlists_title" = "スマートプレイリスト"; +"podcast_smart_playlists_empty_title" = "スマートプレイリストを作成"; +"podcast_smart_playlists_empty_subtitle" = "番組、優先順位、再生状態、長さの上限からキューを自動作成します。"; +"podcast_smart_episode_count_format" = "%lld エピソード"; +"podcast_smart_duration_limit" = "長さの上限"; +"podcast_smart_duration_any" = "制限なし"; +"podcast_smart_duration_limit_format" = "%lld 分以内"; +"podcast_smart_priority_count_format" = "優先 %lld 件"; +"podcast_smart_rules_section" = "ルール"; +"podcast_smart_sort_title" = "並び順"; +"podcast_sort_shortest" = "短い順"; +"podcast_sort_longest" = "長い順"; +"podcast_smart_shows_section" = "番組"; +"podcast_smart_shows_scope" = "対象番組"; +"podcast_smart_shows_all" = "すべての番組"; +"podcast_smart_shows_include" = "選択した番組のみ"; +"podcast_smart_shows_exclude" = "選択した番組を除外"; +"podcast_smart_priority_shows" = "優先番組"; +"podcast_smart_priority_shows_footer" = "優先番組のエピソードは常にこの順序でプレイリストの先頭に表示されます。"; +"podcast_smart_add_priority_show" = "優先番組を追加"; diff --git a/Primuse/Resources/ko.lproj/Localizable.strings b/Primuse/Resources/ko.lproj/Localizable.strings index d1a6cc832..93cc87582 100644 --- a/Primuse/Resources/ko.lproj/Localizable.strings +++ b/Primuse/Resources/ko.lproj/Localizable.strings @@ -8471,3 +8471,23 @@ "podcast_keep_episodes_all" = "모든 에피소드"; "podcast_keep_episodes_count_format" = "최신 %lld개"; "podcast_search_episodes_prompt" = "에피소드 검색"; +"podcast_smart_playlists_title" = "스마트 재생목록"; +"podcast_smart_playlists_empty_title" = "스마트 재생목록 만들기"; +"podcast_smart_playlists_empty_subtitle" = "프로그램, 우선순위, 재생 상태, 길이 제한으로 대기열을 자동 구성합니다."; +"podcast_smart_episode_count_format" = "%lld개 에피소드"; +"podcast_smart_duration_limit" = "최대 길이"; +"podcast_smart_duration_any" = "제한 없음"; +"podcast_smart_duration_limit_format" = "%lld분 이하"; +"podcast_smart_priority_count_format" = "우선 %lld개"; +"podcast_smart_rules_section" = "규칙"; +"podcast_smart_sort_title" = "정렬 순서"; +"podcast_sort_shortest" = "짧은 순"; +"podcast_sort_longest" = "긴 순"; +"podcast_smart_shows_section" = "프로그램"; +"podcast_smart_shows_scope" = "포함할 프로그램"; +"podcast_smart_shows_all" = "모든 프로그램"; +"podcast_smart_shows_include" = "선택한 프로그램만"; +"podcast_smart_shows_exclude" = "선택한 프로그램 제외"; +"podcast_smart_priority_shows" = "우선 프로그램"; +"podcast_smart_priority_shows_footer" = "우선 프로그램의 에피소드는 여기에 나열된 순서대로 항상 맨 위에 배치됩니다."; +"podcast_smart_add_priority_show" = "우선 프로그램 추가"; diff --git a/Primuse/Resources/pl.lproj/Localizable.strings b/Primuse/Resources/pl.lproj/Localizable.strings index 4e71c4a6f..9d7889cce 100644 --- a/Primuse/Resources/pl.lproj/Localizable.strings +++ b/Primuse/Resources/pl.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "Wszystkie odcinki"; "podcast_keep_episodes_count_format" = "Ostatnie %lld"; "podcast_search_episodes_prompt" = "Szukaj odcinków"; +"podcast_smart_playlists_title" = "Inteligentne listy"; +"podcast_smart_playlists_empty_title" = "Utwórz inteligentną listę"; +"podcast_smart_playlists_empty_subtitle" = "Automatycznie układaj kolejkę według audycji, priorytetu, statusu i długości."; +"podcast_smart_episode_count_format" = "%lld odc."; +"podcast_smart_duration_limit" = "Maks. długość"; +"podcast_smart_duration_any" = "Dowolna długość"; +"podcast_smart_duration_limit_format" = "≤ %lld min"; +"podcast_smart_priority_count_format" = "%lld priorytetowych"; +"podcast_smart_rules_section" = "Reguły"; +"podcast_smart_sort_title" = "Sortowanie"; +"podcast_sort_shortest" = "Najkrótsze najpierw"; +"podcast_sort_longest" = "Najdłuższe najpierw"; +"podcast_smart_shows_section" = "Audycje"; +"podcast_smart_shows_scope" = "Zakres audycji"; +"podcast_smart_shows_all" = "Wszystkie audycje"; +"podcast_smart_shows_include" = "Tylko wybrane"; +"podcast_smart_shows_exclude" = "Wszystkie oprócz wybranych"; +"podcast_smart_priority_shows" = "Audycje priorytetowe"; +"podcast_smart_priority_shows_footer" = "Odcinki audycji priorytetowych zawsze pojawiają się na górze w tej kolejności."; +"podcast_smart_add_priority_show" = "Dodaj audycję priorytetową"; diff --git a/Primuse/Resources/pt-BR.lproj/Localizable.strings b/Primuse/Resources/pt-BR.lproj/Localizable.strings index 87a5d25bc..c7ff55adb 100644 --- a/Primuse/Resources/pt-BR.lproj/Localizable.strings +++ b/Primuse/Resources/pt-BR.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "Todos os episódios"; "podcast_keep_episodes_count_format" = "Últimos %lld"; "podcast_search_episodes_prompt" = "Buscar episódios"; +"podcast_smart_playlists_title" = "Playlists Inteligentes"; +"podcast_smart_playlists_empty_title" = "Criar Playlist Inteligente"; +"podcast_smart_playlists_empty_subtitle" = "Monte filas automáticas por programa, prioridade, status e duração."; +"podcast_smart_episode_count_format" = "%lld episódios"; +"podcast_smart_duration_limit" = "Duração máxima"; +"podcast_smart_duration_any" = "Qualquer duração"; +"podcast_smart_duration_limit_format" = "≤ %lld min"; +"podcast_smart_priority_count_format" = "%lld prioritários"; +"podcast_smart_rules_section" = "Regras"; +"podcast_smart_sort_title" = "Ordenação"; +"podcast_sort_shortest" = "Mais curtos primeiro"; +"podcast_sort_longest" = "Mais longos primeiro"; +"podcast_smart_shows_section" = "Programas"; +"podcast_smart_shows_scope" = "Programas incluídos"; +"podcast_smart_shows_all" = "Todos os programas"; +"podcast_smart_shows_include" = "Apenas selecionados"; +"podcast_smart_shows_exclude" = "Todos exceto selecionados"; +"podcast_smart_priority_shows" = "Programas prioritários"; +"podcast_smart_priority_shows_footer" = "Episódios de programas prioritários aparecem sempre no topo nesta ordem."; +"podcast_smart_add_priority_show" = "Adicionar programa prioritário"; diff --git a/Primuse/Resources/ru.lproj/Localizable.strings b/Primuse/Resources/ru.lproj/Localizable.strings index cf16712b6..1a1757925 100644 --- a/Primuse/Resources/ru.lproj/Localizable.strings +++ b/Primuse/Resources/ru.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "Все выпуски"; "podcast_keep_episodes_count_format" = "Последние %lld"; "podcast_search_episodes_prompt" = "Поиск выпусков"; +"podcast_smart_playlists_title" = "Умные плейлисты"; +"podcast_smart_playlists_empty_title" = "Создать умный плейлист"; +"podcast_smart_playlists_empty_subtitle" = "Автосборка очереди по шоу, приоритету, статусу и длительности."; +"podcast_smart_episode_count_format" = "%lld вып."; +"podcast_smart_duration_limit" = "Макс. длительность"; +"podcast_smart_duration_any" = "Любая длина"; +"podcast_smart_duration_limit_format" = "≤ %lld мин"; +"podcast_smart_priority_count_format" = "%lld в приоритете"; +"podcast_smart_rules_section" = "Правила"; +"podcast_smart_sort_title" = "Сортировка"; +"podcast_sort_shortest" = "Сначала короткие"; +"podcast_sort_longest" = "Сначала длинные"; +"podcast_smart_shows_section" = "Шоу"; +"podcast_smart_shows_scope" = "Выбор шоу"; +"podcast_smart_shows_all" = "Все шоу"; +"podcast_smart_shows_include" = "Только выбранные"; +"podcast_smart_shows_exclude" = "Все, кроме выбранных"; +"podcast_smart_priority_shows" = "Приоритетные шоу"; +"podcast_smart_priority_shows_footer" = "Выпуски приоритетных шоу всегда отображаются вверху в указанном порядке."; +"podcast_smart_add_priority_show" = "Добавить приоритетное шоу"; diff --git a/Primuse/Resources/th.lproj/Localizable.strings b/Primuse/Resources/th.lproj/Localizable.strings index 2b329f3ab..3a117eae9 100644 --- a/Primuse/Resources/th.lproj/Localizable.strings +++ b/Primuse/Resources/th.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "ทุกตอน"; "podcast_keep_episodes_count_format" = "%lld ตอนล่าสุด"; "podcast_search_episodes_prompt" = "ค้นหาตอน"; +"podcast_smart_playlists_title" = "เพลย์ลิสต์อัจฉริยะ"; +"podcast_smart_playlists_empty_title" = "สร้างเพลย์ลิสต์อัจฉริยะ"; +"podcast_smart_playlists_empty_subtitle" = "จัดคิวอัตโนมัติตามรายการ ลำดับความสำคัญ สถานะ และความยาว"; +"podcast_smart_episode_count_format" = "%lld ตอน"; +"podcast_smart_duration_limit" = "ความยาวสูงสุด"; +"podcast_smart_duration_any" = "ไม่จำกัดความยาว"; +"podcast_smart_duration_limit_format" = "≤ %lld นาที"; +"podcast_smart_priority_count_format" = "ลำดับแรก %lld รายการ"; +"podcast_smart_rules_section" = "เงื่อนไข"; +"podcast_smart_sort_title" = "การเรียงลำดับ"; +"podcast_sort_shortest" = "สั้นที่สุดก่อน"; +"podcast_sort_longest" = "ยาวที่สุดก่อน"; +"podcast_smart_shows_section" = "รายการ"; +"podcast_smart_shows_scope" = "รายการที่รวม"; +"podcast_smart_shows_all" = "ทุกรายการ"; +"podcast_smart_shows_include" = "เฉพาะที่เลือก"; +"podcast_smart_shows_exclude" = "ทั้งหมดยกเว้นที่เลือก"; +"podcast_smart_priority_shows" = "รายการสำคัญลำดับแรก"; +"podcast_smart_priority_shows_footer" = "ตอนจากรายการสำคัญจะอยู่ด้านบนสุดของเพลย์ลิสต์ตามลำดับนี้เสมอ"; +"podcast_smart_add_priority_show" = "เพิ่มรายการสำคัญ"; diff --git a/Primuse/Resources/tr.lproj/Localizable.strings b/Primuse/Resources/tr.lproj/Localizable.strings index 631a985b1..153b820ac 100644 --- a/Primuse/Resources/tr.lproj/Localizable.strings +++ b/Primuse/Resources/tr.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "Tüm Bölümler"; "podcast_keep_episodes_count_format" = "Son %lld"; "podcast_search_episodes_prompt" = "Bölümlerde ara"; +"podcast_smart_playlists_title" = "Akıllı Listeler"; +"podcast_smart_playlists_empty_title" = "Akıllı Liste Oluştur"; +"podcast_smart_playlists_empty_subtitle" = "Program, öncelik, durum ve süre sınırına göre otomatik sıra oluşturun."; +"podcast_smart_episode_count_format" = "%lld bölüm"; +"podcast_smart_duration_limit" = "En Uzun Süre"; +"podcast_smart_duration_any" = "Herhangi Bir Süre"; +"podcast_smart_duration_limit_format" = "≤ %lld dk"; +"podcast_smart_priority_count_format" = "%lld öncelikli"; +"podcast_smart_rules_section" = "Kurallar"; +"podcast_smart_sort_title" = "Sıralama"; +"podcast_sort_shortest" = "En Kısa Önce"; +"podcast_sort_longest" = "En Uzun Önce"; +"podcast_smart_shows_section" = "Programlar"; +"podcast_smart_shows_scope" = "Dahil Edilenler"; +"podcast_smart_shows_all" = "Tüm Programlar"; +"podcast_smart_shows_include" = "Yalnızca Seçilenler"; +"podcast_smart_shows_exclude" = "Seçilenler Hariç"; +"podcast_smart_priority_shows" = "Öncelikli Programlar"; +"podcast_smart_priority_shows_footer" = "Öncelikli programların bölümleri her zaman bu sırayla en üstte yer alır."; +"podcast_smart_add_priority_show" = "Öncelikli Program Ekle"; diff --git a/Primuse/Resources/uk.lproj/Localizable.strings b/Primuse/Resources/uk.lproj/Localizable.strings index d402effc9..a0726a113 100644 --- a/Primuse/Resources/uk.lproj/Localizable.strings +++ b/Primuse/Resources/uk.lproj/Localizable.strings @@ -8377,3 +8377,23 @@ "podcast_keep_episodes_all" = "Усі випуски"; "podcast_keep_episodes_count_format" = "Останні %lld"; "podcast_search_episodes_prompt" = "Пошук випусків"; +"podcast_smart_playlists_title" = "Розумні списки"; +"podcast_smart_playlists_empty_title" = "Створити розумний список"; +"podcast_smart_playlists_empty_subtitle" = "Автоматична черга за шоу, пріоритетом, статусом і тривалістю."; +"podcast_smart_episode_count_format" = "%lld вип."; +"podcast_smart_duration_limit" = "Макс. тривалість"; +"podcast_smart_duration_any" = "Будь-яка тривалість"; +"podcast_smart_duration_limit_format" = "≤ %lld хв"; +"podcast_smart_priority_count_format" = "%lld пріоритетних"; +"podcast_smart_rules_section" = "Правила"; +"podcast_smart_sort_title" = "Сортування"; +"podcast_sort_shortest" = "Спочатку коротші"; +"podcast_sort_longest" = "Спочатку довші"; +"podcast_smart_shows_section" = "Шоу"; +"podcast_smart_shows_scope" = "Вибір шоу"; +"podcast_smart_shows_all" = "Усі шоу"; +"podcast_smart_shows_include" = "Лише вибрані"; +"podcast_smart_shows_exclude" = "Усі, крім вибраних"; +"podcast_smart_priority_shows" = "Пріоритетні шоу"; +"podcast_smart_priority_shows_footer" = "Випуски пріоритетних шоу завжди будуть на початку у вказаному порядку."; +"podcast_smart_add_priority_show" = "Додати пріоритетне шоу"; diff --git a/Primuse/Resources/zh-Hans.lproj/Localizable.strings b/Primuse/Resources/zh-Hans.lproj/Localizable.strings index 96ad803c5..09fe0ec56 100644 --- a/Primuse/Resources/zh-Hans.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hans.lproj/Localizable.strings @@ -8564,3 +8564,23 @@ "podcast_keep_episodes_all" = "全部单集"; "podcast_keep_episodes_count_format" = "最近 %lld 集"; "podcast_search_episodes_prompt" = "搜索单集"; +"podcast_smart_playlists_title" = "智能列表"; +"podcast_smart_playlists_empty_title" = "创建播客智能列表"; +"podcast_smart_playlists_empty_subtitle" = "按节目范围、优先置顶顺序、收听状态与时长上限自动编排队列。"; +"podcast_smart_episode_count_format" = "%lld 集"; +"podcast_smart_duration_limit" = "单集时长上限"; +"podcast_smart_duration_any" = "不限时长"; +"podcast_smart_duration_limit_format" = "≤ %lld 分钟"; +"podcast_smart_priority_count_format" = "%lld 档优先"; +"podcast_smart_rules_section" = "筛选与排序"; +"podcast_smart_sort_title" = "排序方式"; +"podcast_sort_shortest" = "最短优先"; +"podcast_sort_longest" = "最长优先"; +"podcast_smart_shows_section" = "节目范围"; +"podcast_smart_shows_scope" = "包含节目"; +"podcast_smart_shows_all" = "全部订阅节目"; +"podcast_smart_shows_include" = "仅包含所选节目"; +"podcast_smart_shows_exclude" = "排除所选节目"; +"podcast_smart_priority_shows" = "优先置顶节目"; +"podcast_smart_priority_shows_footer" = "优先节目的单集将按此处顺序始终排在智能列表最前面。"; +"podcast_smart_add_priority_show" = "添加优先节目"; diff --git a/Primuse/Resources/zh-Hant.lproj/Localizable.strings b/Primuse/Resources/zh-Hant.lproj/Localizable.strings index b38fcab9b..18d9b2886 100644 --- a/Primuse/Resources/zh-Hant.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hant.lproj/Localizable.strings @@ -8448,3 +8448,23 @@ "podcast_keep_episodes_all" = "全部單集"; "podcast_keep_episodes_count_format" = "最近 %lld 集"; "podcast_search_episodes_prompt" = "搜尋單集"; +"podcast_smart_playlists_title" = "智慧播放列表"; +"podcast_smart_playlists_empty_title" = "建立 Podcast 智慧列表"; +"podcast_smart_playlists_empty_subtitle" = "依節目範圍、優先置頂順序、收聽狀態與時長上限自動編排佇列。"; +"podcast_smart_episode_count_format" = "%lld 集"; +"podcast_smart_duration_limit" = "單集時長上限"; +"podcast_smart_duration_any" = "不限時長"; +"podcast_smart_duration_limit_format" = "≤ %lld 分鐘"; +"podcast_smart_priority_count_format" = "%lld 檔優先"; +"podcast_smart_rules_section" = "篩選與排序"; +"podcast_smart_sort_title" = "排序方式"; +"podcast_sort_shortest" = "最短優先"; +"podcast_sort_longest" = "最長優先"; +"podcast_smart_shows_section" = "節目範圍"; +"podcast_smart_shows_scope" = "包含節目"; +"podcast_smart_shows_all" = "全部訂閱節目"; +"podcast_smart_shows_include" = "僅包含所選節目"; +"podcast_smart_shows_exclude" = "排除所選節目"; +"podcast_smart_priority_shows" = "優先置頂節目"; +"podcast_smart_priority_shows_footer" = "優先節目的單集將依此處順序始終排在智慧列表最前面。"; +"podcast_smart_add_priority_show" = "加入優先節目"; diff --git a/Primuse/Services/Podcast/PodcastSmartPlaylistStore.swift b/Primuse/Services/Podcast/PodcastSmartPlaylistStore.swift new file mode 100644 index 000000000..e5122c400 --- /dev/null +++ b/Primuse/Services/Podcast/PodcastSmartPlaylistStore.swift @@ -0,0 +1,124 @@ +import Foundation +import Observation +import PrimuseKit + +extension CloudKVSKey { + static let podcastSmartPlaylists = "primuse_podcast_smart_playlists_v1" +} + +extension Notification.Name { + static let primusePodcastSmartPlaylistsDidChange = Notification.Name("primusePodcastSmartPlaylistsDidChange") +} + +/// 播客智能列表仓库:本地持久化 + CloudKVS 墓碑合并同步,供 iOS、macOS 与 CarPlay 共用。 +@MainActor +@Observable +final class PodcastSmartPlaylistStore { + private(set) var document: PodcastSmartPlaylistDocument + @ObservationIgnored private let defaults: UserDefaults + @ObservationIgnored private let syncsWithCloud: Bool + + init(defaults: UserDefaults = .standard, syncsWithCloud: Bool? = nil) { + self.defaults = defaults + let shouldSync = syncsWithCloud ?? (defaults === UserDefaults.standard) + self.syncsWithCloud = shouldSync + self.document = PodcastSmartPlaylistDocument.decode( + defaults.string(forKey: CloudKVSKey.podcastSmartPlaylists) + ) ?? PodcastSmartPlaylistDocument() + if shouldSync { + CloudKVSSync.shared.registerMerging(key: CloudKVSKey.podcastSmartPlaylists) { [weak self] in + Task { @MainActor [weak self] in self?.mergeFromCloud() } + } + } + } +} + +extension PodcastSmartPlaylistStore { + static let shared = PodcastSmartPlaylistStore() + + var playlists: [PodcastSmartPlaylist] { + document.activePlaylists + } + + func playlist(id: String) -> PodcastSmartPlaylist? { + playlists.first { $0.id == id } + } + + func save(_ playlist: PodcastSmartPlaylist, now: Date = Date()) { + var next = playlist + next.name = playlist.name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !next.name.isEmpty else { return } + next.isDeleted = false + next.updatedAt = now + if let index = document.items.firstIndex(where: { $0.id == next.id }) { + document.items[index] = next + } else { + next.sortOrderIndex = (playlists.map(\.sortOrderIndex).max() ?? -1) + 1 + document.items.append(next) + } + persistAndNotify() + } + + func delete(id: String, now: Date = Date()) { + guard let index = document.items.firstIndex(where: { $0.id == id }) else { return } + document.items[index].isDeleted = true + document.items[index].updatedAt = now + persistAndNotify() + } + + func move(fromOffsets source: IndexSet, toOffset destination: Int, now: Date = Date()) { + var ordered = playlists + let moving = source.sorted().compactMap { ordered.indices.contains($0) ? ordered[$0] : nil } + guard !moving.isEmpty else { return } + let insertAt = destination - source.filter { $0 < destination }.count + for idx in source.sorted(by: >) where ordered.indices.contains(idx) { + ordered.remove(at: idx) + } + ordered.insert(contentsOf: moving, at: min(max(0, insertAt), ordered.count)) + for (newIndex, playlist) in ordered.enumerated() { + if let idx = document.items.firstIndex(where: { $0.id == playlist.id }), + document.items[idx].sortOrderIndex != newIndex { + document.items[idx].sortOrderIndex = newIndex + document.items[idx].updatedAt = now + } + } + persistAndNotify() + } + + func episodes( + for playlist: PodcastSmartPlaylist, + in store: PodcastStore = .shared, + limit: Int = PodcastSmartPlaylistPolicy.defaultEpisodeLimit + ) -> [PodcastEpisode] { + let allEpisodes = store.shows.flatMap { store.episodes(forShowID: $0.id) } + return PodcastSmartPlaylistPolicy.episodes( + for: playlist, + from: allEpisodes, + state: store.state(for:), + limit: limit + ) + } + + func mergeFromCloud() { + guard let remote = PodcastSmartPlaylistDocument.decode( + defaults.string(forKey: CloudKVSKey.podcastSmartPlaylists) + ) else { return } + let merged = document.merged(with: remote) + guard merged != document else { return } + document = merged + if let encoded = merged.encoded() { + defaults.set(encoded, forKey: CloudKVSKey.podcastSmartPlaylists) + } + NotificationCenter.default.post(name: .primusePodcastSmartPlaylistsDidChange, object: nil) + } + + private func persistAndNotify() { + if let encoded = document.encoded() { + defaults.set(encoded, forKey: CloudKVSKey.podcastSmartPlaylists) + if syncsWithCloud { + CloudKVSSync.shared.markChanged(key: CloudKVSKey.podcastSmartPlaylists) + } + } + NotificationCenter.default.post(name: .primusePodcastSmartPlaylistsDidChange, object: nil) + } +} diff --git a/Primuse/Views/Podcast/PodcastLibraryView.swift b/Primuse/Views/Podcast/PodcastLibraryView.swift index 32148d66d..85125e824 100644 --- a/Primuse/Views/Podcast/PodcastLibraryView.swift +++ b/Primuse/Views/Podcast/PodcastLibraryView.swift @@ -109,9 +109,11 @@ final class PodcastNavigationModel { var showsSettings = false var showsSectionEditor = false var showsOPMLImporter = false + var showsNewSmartPlaylist = false var importMessage: String? var pushedShowID: String? var pushedEpisodeID: String? + var pushedSmartPlaylistID: String? var pushedAllEpisodes = false var pushedLikedEpisodes = false /// 本机下载的播客文件按节目分组后的那一档(`SpokenWordBook.id`)。 @@ -178,6 +180,7 @@ private struct PodcastNavigationDestinations: ViewModifier { .sheet(isPresented: $navigation.showsSectionEditor) { PodcastSectionsEditor() } + .podcastSmartPlaylistNavigation(navigation) .podcastShowOrganizerAlerts(navigation.organizer) .fileImporter( isPresented: $navigation.showsOPMLImporter, @@ -244,36 +247,6 @@ struct PodcastLibraryToolbar: ToolbarContent { } #endif -/// 「+」:发现、按地址添加、导入 OPML。工具栏与极简页头共用。 -struct PodcastAddMenu: View { - let navigation: PodcastNavigationModel - - private var availability: PodcastAvailabilityService { PodcastAvailabilityService.shared } - - var body: some View { - Menu { - Button { navigation.showsDiscover = true } label: { - Label("podcast_discover", systemImage: "magnifyingglass") - } - if availability.allowsCustomFeeds { - Button { - navigation.showsAddFeed = true - } label: { - Label("podcast_add_by_url", systemImage: "link") - } - Button { - navigation.showsOPMLImporter = true - } label: { - Label("podcast_import_opml", systemImage: "square.and.arrow.down") - } - } - } label: { - Label("podcast_add", systemImage: "plus") - } - .accessibilityIdentifier("podcast.add") - } -} - struct PodcastShareMenu: View { let navigation: PodcastNavigationModel #if os(macOS) @@ -390,6 +363,9 @@ struct PodcastLibraryContent: View { // 没有喜欢的)画不出东西也照样占一份 28,挪到中间的区块下面就空出两倍。 // 区块只有几块,里面的节目网格自己是惰性的。 VStack(alignment: .leading, spacing: 28) { + if onManageShows == nil || !PodcastSmartPlaylistStore.shared.playlists.isEmpty { + PodcastSmartPlaylistsSection(navigation: navigation) + } // 先后与显隐由「…›调整区块」定。 ForEach(sections, id: \.self) { section in sectionContent(section) diff --git a/Primuse/Views/Podcast/PodcastSmartPlaylistsViews.swift b/Primuse/Views/Podcast/PodcastSmartPlaylistsViews.swift new file mode 100644 index 000000000..79a2ad092 --- /dev/null +++ b/Primuse/Views/Podcast/PodcastSmartPlaylistsViews.swift @@ -0,0 +1,624 @@ +import PrimuseKit +import SwiftUI + +/// 播客主页顶部的智能列表横排卡片区:展示自定义智能列表的单集数、剩余时长与一键播放入口。 +struct PodcastSmartPlaylistsSection: View { + let navigation: PodcastNavigationModel + + @Environment(AudioPlayerService.self) private var player + @State private var editingPlaylist: PodcastSmartPlaylist? + @State private var pendingInsecureHost: String? + @State private var pendingPlayEpisodes: [PodcastEpisode] = [] + + private var playlistStore: PodcastSmartPlaylistStore { PodcastSmartPlaylistStore.shared } + private var podcastStore: PodcastStore { PodcastStore.shared } + private var tint: Color { ListeningSpace.podcast.tint } + + var body: some View { + let playlists = playlistStore.playlists + if !podcastStore.shows.isEmpty { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .firstTextBaseline) { + Text("podcast_smart_playlists_title") + .font(.title3.weight(.bold)) + .accessibilityAddTraits(.isHeader) + Spacer() + Button { + navigation.showsNewSmartPlaylist = true + } label: { + Label("new_smart_playlist", systemImage: "plus") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(tint) + } + .buttonStyle(.plain) + .accessibilityIdentifier("podcast.smartPlaylists.add") + } + .padding(.horizontal, 16) + + if playlists.isEmpty { + emptyPromptRow + .padding(.horizontal, 16) + } else { + ScrollView(.horizontal, showsIndicators: false) { + LazyHStack(spacing: 12) { + ForEach(playlists) { playlist in + playlistCard(playlist) + } + } + .padding(.horizontal, 16) + } + } + } + .sheet(item: $editingPlaylist) { playlist in + PodcastSmartPlaylistEditorSheet(existing: playlist) + } + .podcastInsecureHTTPAlert(host: $pendingInsecureHost, onCancel: { pendingPlayEpisodes = [] }) { + if let first = pendingPlayEpisodes.first { + let rest = Array(pendingPlayEpisodes.dropFirst().prefix(50)) + PodcastPlaybackLauncher.play(first, continuing: rest, player: player) { _ in } + } + pendingPlayEpisodes = [] + } + } + } + + private var emptyPromptRow: some View { + Button { + navigation.showsNewSmartPlaylist = true + } label: { + HStack(spacing: 12) { + Image(systemName: "sparkles.rectangle.stack") + .font(.title3.weight(.semibold)) + .foregroundStyle(tint) + .frame(width: 36, height: 36) + .background(tint.opacity(0.12), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + VStack(alignment: .leading, spacing: 2) { + Text("podcast_smart_playlists_empty_title") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + Text("podcast_smart_playlists_empty_subtitle") + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + Spacer(minLength: 8) + Image(systemName: "plus.circle.fill") + .font(.title3) + .foregroundStyle(tint) + } + .padding(12) + .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } + .buttonStyle(.plain) + } + + private func playlistCard(_ playlist: PodcastSmartPlaylist) -> some View { + let episodes = playlistStore.episodes(for: playlist, in: podcastStore) + let remaining = PodcastSmartPlaylistPolicy.totalRemainingSeconds( + for: episodes, + state: podcastStore.state(for:) + ) + return HStack(spacing: 10) { + Button { + navigation.pushedSmartPlaylistID = playlist.id + } label: { + HStack(spacing: 10) { + Image(systemName: playlist.symbol) + .font(.body.weight(.semibold)) + .foregroundStyle(tint) + .frame(width: 36, height: 36) + .background(tint.opacity(0.14), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + VStack(alignment: .leading, spacing: 2) { + Text(playlist.name) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + Text(verbatim: cardSubtitle(count: episodes.count, remaining: remaining)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .frame(minWidth: 96, alignment: .leading) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + Button { + playAll(episodes) + } label: { + Image(systemName: "play.fill") + .font(.caption.weight(.bold)) + .foregroundStyle(.white) + .frame(width: 28, height: 28) + .background(episodes.isEmpty ? Color.secondary.opacity(0.35) : tint, in: Circle()) + } + .buttonStyle(.plain) + .disabled(episodes.isEmpty) + .accessibilityLabel(Text("play_all")) + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: 14, style: .continuous) + .strokeBorder(tint.opacity(0.14), lineWidth: 0.5) + } + .contextMenu { + Button { + playAll(episodes) + } label: { + Label("play_all", systemImage: "play.fill") + } + .disabled(episodes.isEmpty) + Button { + editingPlaylist = playlist + } label: { + Label("smart_playlist_edit", systemImage: "pencil") + } + Button(role: .destructive) { + playlistStore.delete(id: playlist.id) + } label: { + Label("delete", systemImage: "trash") + } + } + } + + private func cardSubtitle(count: Int, remaining: TimeInterval) -> String { + let countText = String(format: String(localized: "podcast_smart_episode_count_format"), count) + guard remaining > 0 else { return countText } + return "\(countText) · \(SpokenWordListeningStatsPolicy.formattedDuration(remaining))" + } + + private func playAll(_ episodes: [PodcastEpisode]) { + guard let first = episodes.first else { return } + let rest = Array(episodes.dropFirst().prefix(50)) + PodcastPlaybackLauncher.play(first, continuing: rest, player: player) { host in + pendingPlayEpisodes = episodes + pendingInsecureHost = host + } + } +} + +/// 单个播客智能列表详情页:展示规则摘要、一键顺序播完队列,以及匹配单集列表。 +struct PodcastSmartPlaylistDetailView: View { + let playlistID: String + + @Environment(AudioPlayerService.self) private var player + @State private var showsEditor = false + @State private var pushedEpisodeID: String? + @State private var pushedShowID: String? + @State private var pendingInsecureHost: String? + @State private var pendingPlayEpisodes: [PodcastEpisode] = [] + + private var playlistStore: PodcastSmartPlaylistStore { PodcastSmartPlaylistStore.shared } + private var podcastStore: PodcastStore { PodcastStore.shared } + private var tint: Color { ListeningSpace.podcast.tint } + + var body: some View { + Group { + if let playlist = playlistStore.playlist(id: playlistID) { + let episodes = playlistStore.episodes(for: playlist, in: podcastStore) + let remaining = PodcastSmartPlaylistPolicy.totalRemainingSeconds( + for: episodes, + state: podcastStore.state(for:) + ) + List { + #if os(macOS) + PodcastInlineBackButton() + .listRowSeparator(.hidden) + #endif + Section { + header(playlist, episodes: episodes, remaining: remaining) + .listRowSeparator(.hidden) + } + if episodes.isEmpty { + Text("podcast_no_matching_episodes") + .font(.subheadline) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 30) + .listRowSeparator(.hidden) + } + ForEach(Array(episodes.enumerated()), id: \.element.id) { index, episode in + let continuing = Array(episodes.dropFirst(index + 1).prefix(50)) + PodcastEpisodeRow( + episode: episode, + show: podcastStore.show(id: episode.showID), + showsArtwork: true, + continuing: continuing + ) { + pushedEpisodeID = episode.id + } + .podcastEpisodeContextMenu(episode, continuing: continuing, openShow: { pushedShowID = $0 }) + .swipeActions(edge: .leading, allowsFullSwipe: true) { + let finished = podcastStore.state(for: episode).isFinished + Button { + podcastStore.setPlayed(!finished, episode: episode) + } label: { + Label( + finished ? "podcast_mark_unplayed" : "podcast_mark_played", + systemImage: finished ? "circle" : "checkmark.circle" + ) + } + .tint(tint) + } + } + } + .listStyle(.plain) + #if os(iOS) + .navigationTitle(playlist.name) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button("edit") { showsEditor = true } + .tint(tint) + } + } + #endif + .sheet(isPresented: $showsEditor) { + PodcastSmartPlaylistEditorSheet(existing: playlist) + } + } else { + ContentUnavailableView("smart_playlist_unavailable", systemImage: "list.bullet.rectangle") + } + } + .podcastPushedPageChrome() + .navigationDestination(item: $pushedEpisodeID) { PodcastEpisodeDetailView(episodeID: $0) } + .navigationDestination(item: $pushedShowID) { PodcastShowDetailView(source: .show($0)) } + .podcastInsecureHTTPAlert(host: $pendingInsecureHost, onCancel: { pendingPlayEpisodes = [] }) { + if let first = pendingPlayEpisodes.first { + let rest = Array(pendingPlayEpisodes.dropFirst().prefix(50)) + PodcastPlaybackLauncher.play(first, continuing: rest, player: player) { _ in } + } + pendingPlayEpisodes = [] + } + } + + private func header( + _ playlist: PodcastSmartPlaylist, + episodes: [PodcastEpisode], + remaining: TimeInterval + ) -> some View { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 12) { + Image(systemName: playlist.symbol) + .font(.title2.weight(.semibold)) + .foregroundStyle(tint) + .frame(width: 52, height: 52) + .background(tint.opacity(0.14), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + VStack(alignment: .leading, spacing: 4) { + Text(playlist.name) + .font(.title3.weight(.bold)) + Text(verbatim: ruleSummary(playlist, count: episodes.count, remaining: remaining)) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + Spacer(minLength: 0) + } + + HStack(spacing: 10) { + Button { + guard let first = episodes.first else { return } + let rest = Array(episodes.dropFirst().prefix(50)) + PodcastPlaybackLauncher.play(first, continuing: rest, player: player) { host in + pendingPlayEpisodes = episodes + pendingInsecureHost = host + } + } label: { + Label("play_all", systemImage: "play.fill") + .font(.subheadline.weight(.semibold)) + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .tint(tint) + .disabled(episodes.isEmpty) + + #if os(macOS) + Button { + showsEditor = true + } label: { + Label("edit", systemImage: "slider.horizontal.3") + .font(.subheadline.weight(.medium)) + } + .buttonStyle(.bordered) + #endif + } + } + .padding(.vertical, 6) + } + + private func ruleSummary(_ playlist: PodcastSmartPlaylist, count: Int, remaining: TimeInterval) -> String { + var parts = [String(format: String(localized: "podcast_smart_episode_count_format"), count)] + if remaining > 0 { + parts.append(SpokenWordListeningStatsPolicy.formattedDuration(remaining)) + } + if let maxMinutes = playlist.maxDurationMinutes { + parts.append(String(format: String(localized: "podcast_smart_duration_limit_format"), maxMinutes)) + } + if !playlist.priorityShowIDs.isEmpty { + parts.append(String(format: String(localized: "podcast_smart_priority_count_format"), playlist.priorityShowIDs.count)) + } + return parts.joined(separator: " · ") + } +} + +/// 创建与编辑播客智能列表(节目范围、优先置顶节目、状态筛选、时长上限、排序方式)。 +struct PodcastSmartPlaylistEditorSheet: View { + var existing: PodcastSmartPlaylist? + + @Environment(\.dismiss) private var dismiss + @State private var name: String + @State private var symbol: String + @State private var filter: PodcastEpisodeFilter + @State private var sort: PodcastSmartPlaylist.SortOrder + @State private var maxDurationMinutes: Int? + @State private var showScopeMode: PodcastSmartPlaylist.ShowScopeMode + @State private var selectedShowIDs: Set + @State private var priorityShowIDs: [String] + + private var podcastStore: PodcastStore { PodcastStore.shared } + private var tint: Color { ListeningSpace.podcast.tint } + + init(existing: PodcastSmartPlaylist? = nil) { + self.existing = existing + _name = State(initialValue: existing?.name ?? "") + _symbol = State(initialValue: existing?.symbol ?? "list.bullet.rectangle") + _filter = State(initialValue: existing?.filter ?? .unplayed) + _sort = State(initialValue: existing?.sort ?? .newestFirst) + _maxDurationMinutes = State(initialValue: existing?.maxDurationMinutes) + _showScopeMode = State(initialValue: existing?.showScopeMode ?? .all) + _selectedShowIDs = State(initialValue: Set(existing?.selectedShowIDs ?? [])) + _priorityShowIDs = State(initialValue: existing?.priorityShowIDs ?? []) + } + + private var canSave: Bool { + !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private func saveDraft() { + let draft = PodcastSmartPlaylist( + id: existing?.id ?? UUID().uuidString, + name: name, + symbol: symbol, + showScopeMode: showScopeMode, + selectedShowIDs: Array(selectedShowIDs).sorted(), + priorityShowIDs: priorityShowIDs, + filter: filter, + sort: sort, + maxDurationMinutes: maxDurationMinutes, + sortOrderIndex: existing?.sortOrderIndex ?? 0 + ) + PodcastSmartPlaylistStore.shared.save(draft) + dismiss() + } + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + #if os(macOS) + HStack { + Button("cancel") { dismiss() } + .keyboardShortcut(.cancelAction) + Spacer() + Text(existing == nil ? "new_smart_playlist" : "smart_playlist_edit") + .font(.headline) + Spacer() + Button("save") { saveDraft() } + .keyboardShortcut(.defaultAction) + .disabled(!canSave) + .tint(tint) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + Divider() + #endif + Form { + Section { + TextField("smart_playlist_name", text: $name) + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 10) { + ForEach(PodcastSmartPlaylist.symbolChoices, id: \.self) { choice in + let active = symbol == choice + Button { + symbol = choice + } label: { + Image(systemName: choice) + .font(.body.weight(.semibold)) + .foregroundStyle(active ? .white : tint) + .frame(width: 34, height: 34) + .background(active ? tint : tint.opacity(0.12), in: Circle()) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, 4) + } + } + + Section("podcast_smart_rules_section") { + Picker("podcast_filter", selection: $filter) { + Text("podcast_filter_unplayed").tag(PodcastEpisodeFilter.unplayed) + Text("podcast_filter_in_progress").tag(PodcastEpisodeFilter.inProgress) + Text("podcast_filter_downloaded").tag(PodcastEpisodeFilter.downloaded) + Text("podcast_filter_all").tag(PodcastEpisodeFilter.all) + } + Picker("podcast_smart_sort_title", selection: $sort) { + Text("podcast_order_newest").tag(PodcastSmartPlaylist.SortOrder.newestFirst) + Text("podcast_order_oldest").tag(PodcastSmartPlaylist.SortOrder.oldestFirst) + Text("podcast_sort_shortest").tag(PodcastSmartPlaylist.SortOrder.shortestFirst) + Text("podcast_sort_longest").tag(PodcastSmartPlaylist.SortOrder.longestFirst) + } + Picker("podcast_smart_duration_limit", selection: $maxDurationMinutes) { + Text("podcast_smart_duration_any").tag(Optional.none) + ForEach([15, 30, 45, 60], id: \.self) { minutes in + Text(String(format: String(localized: "podcast_smart_duration_limit_format"), minutes)) + .tag(Optional(minutes)) + } + } + } + + Section("podcast_smart_shows_section") { + Picker("podcast_smart_shows_scope", selection: $showScopeMode) { + Text("podcast_smart_shows_all").tag(PodcastSmartPlaylist.ShowScopeMode.all) + Text("podcast_smart_shows_include").tag(PodcastSmartPlaylist.ShowScopeMode.include) + Text("podcast_smart_shows_exclude").tag(PodcastSmartPlaylist.ShowScopeMode.exclude) + } + if showScopeMode != .all { + ForEach(podcastStore.shows) { show in + let included = selectedShowIDs.contains(show.id) + Button { + if included { selectedShowIDs.remove(show.id) } else { selectedShowIDs.insert(show.id) } + } label: { + HStack { + Text(show.title).foregroundStyle(.primary).lineLimit(1) + Spacer() + if included { + Image(systemName: "checkmark") + .foregroundStyle(tint) + } + } + } + .buttonStyle(.plain) + } + } + } + + if !podcastStore.shows.isEmpty { + Section { + ForEach(priorityShowIDs, id: \.self) { showID in + if let show = podcastStore.show(id: showID) { + HStack(spacing: 8) { + Image(systemName: "arrow.up.to.line") + .font(.caption.weight(.semibold)) + .foregroundStyle(tint) + Text(show.title).lineLimit(1) + Spacer() + let idx = priorityShowIDs.firstIndex(of: showID) ?? 0 + Button { + guard idx > 0 else { return } + priorityShowIDs.swapAt(idx, idx - 1) + } label: { + Image(systemName: "chevron.up") + } + .buttonStyle(.plain) + .disabled(idx == 0) + Button { + priorityShowIDs.removeAll { $0 == showID } + } label: { + Image(systemName: "minus.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + } + } + } + let available = podcastStore.shows.filter { !priorityShowIDs.contains($0.id) } + if !available.isEmpty { + Menu { + ForEach(available) { show in + Button(show.title) { + priorityShowIDs.append(show.id) + } + } + } label: { + Label("podcast_smart_add_priority_show", systemImage: "plus.circle") + .foregroundStyle(tint) + } + } + } header: { + Text("podcast_smart_priority_shows") + } footer: { + Text("podcast_smart_priority_shows_footer") + } + } + + if let existing { + Section { + Button("delete", role: .destructive) { + PodcastSmartPlaylistStore.shared.delete(id: existing.id) + dismiss() + } + } + } + } + #if os(macOS) + .formStyle(.grouped) + #endif + } + #if os(macOS) + .frame(minWidth: 460, idealWidth: 500, minHeight: 500, idealHeight: 560) + #endif + #if os(iOS) + .navigationTitle(Text(existing == nil ? "new_smart_playlist" : "smart_playlist_edit")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("save") { saveDraft() } + .disabled(!canSave) + .tint(tint) + } + } + #endif + } + } +} + +/// 「+」:发现、新建智能列表、按地址添加、导入 OPML。工具栏与极简页头共用。 +struct PodcastAddMenu: View { + let navigation: PodcastNavigationModel + + private var availability: PodcastAvailabilityService { PodcastAvailabilityService.shared } + + var body: some View { + Menu { + Button { navigation.showsDiscover = true } label: { + Label("podcast_discover", systemImage: "magnifyingglass") + } + if !PodcastStore.shared.shows.isEmpty { + Button { navigation.showsNewSmartPlaylist = true } label: { + Label("new_smart_playlist", systemImage: "sparkles.rectangle.stack") + } + } + if availability.allowsCustomFeeds { + Button { + navigation.showsAddFeed = true + } label: { + Label("podcast_add_by_url", systemImage: "link") + } + Button { + navigation.showsOPMLImporter = true + } label: { + Label("podcast_import_opml", systemImage: "square.and.arrow.down") + } + } + } label: { + Label("podcast_add", systemImage: "plus") + } + .accessibilityIdentifier("podcast.add") + } +} + +extension View { + func podcastSmartPlaylistNavigation(_ navigation: PodcastNavigationModel) -> some View { + modifier(PodcastSmartPlaylistNavigationModifier(navigation: navigation)) + } +} + +private struct PodcastSmartPlaylistNavigationModifier: ViewModifier { + @Bindable var navigation: PodcastNavigationModel + + func body(content: Content) -> some View { + content + .navigationDestination(item: $navigation.pushedSmartPlaylistID) { playlistID in + PodcastSmartPlaylistDetailView(playlistID: playlistID) + } + .sheet(isPresented: $navigation.showsNewSmartPlaylist) { + PodcastSmartPlaylistEditorSheet() + } + } +} diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift index 0fcf203be..bf69fd00b 100644 --- a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastLibraryPolicy.swift @@ -155,7 +155,7 @@ public struct PodcastEpisodeState: Sendable, Hashable { public static let untouched = PodcastEpisodeState() } -public enum PodcastEpisodeFilter: String, CaseIterable, Sendable { +public enum PodcastEpisodeFilter: String, Codable, CaseIterable, Sendable { case all case unplayed case inProgress diff --git a/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSmartPlaylist.swift b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSmartPlaylist.swift new file mode 100644 index 000000000..294d4b664 --- /dev/null +++ b/PrimuseKit/Sources/PrimuseKit/Podcast/PodcastSmartPlaylist.swift @@ -0,0 +1,237 @@ +import Foundation + +/// 参考 Overcast Smart Playlists 的播客智能列表定义: +/// 支持按节目范围(全部 / 仅包含 / 排除)、置顶优先节目顺序、收听状态筛选、 +/// 时长上限以及最新/最旧/最短/最长排序自动编排单集队列,并以墓碑标记支持跨设备无冲突合并。 +public struct PodcastSmartPlaylist: Identifiable, Codable, Equatable, Hashable, Sendable { + public enum ShowScopeMode: String, Codable, CaseIterable, Sendable { + case all + case include + case exclude + } + + public enum SortOrder: String, Codable, CaseIterable, Sendable { + case newestFirst + case oldestFirst + case shortestFirst + case longestFirst + } + + public static let symbolChoices: [String] = [ + "list.bullet.rectangle", + "sun.max", + "car", + "sparkles", + "bolt", + "headphones", + "clock", + "newspaper", + "flame", + "moon.stars", + ] + + public static let maxDurationChoices: [Int?] = [nil, 15, 30, 45, 60] + + public var id: String + public var name: String + public var symbol: String + public var showScopeMode: ShowScopeMode + public var selectedShowIDs: [String] + /// 按置顶优先级排列的节目 ID(排在前面的节目在列表中始终优先出现)。 + public var priorityShowIDs: [String] + public var filter: PodcastEpisodeFilter + public var sort: SortOrder + /// 可选单集时长上限(分钟);例如通勤列表设为 30 分钟。 + public var maxDurationMinutes: Int? + public var sortOrderIndex: Int + public var updatedAt: Date + public var isDeleted: Bool + + public init( + id: String = UUID().uuidString, + name: String, + symbol: String = "list.bullet.rectangle", + showScopeMode: ShowScopeMode = .all, + selectedShowIDs: [String] = [], + priorityShowIDs: [String] = [], + filter: PodcastEpisodeFilter = .unplayed, + sort: SortOrder = .newestFirst, + maxDurationMinutes: Int? = nil, + sortOrderIndex: Int = 0, + updatedAt: Date = Date(), + isDeleted: Bool = false + ) { + self.id = id + self.name = name + self.symbol = symbol + self.showScopeMode = showScopeMode + self.selectedShowIDs = selectedShowIDs + self.priorityShowIDs = priorityShowIDs + self.filter = filter + self.sort = sort + self.maxDurationMinutes = maxDurationMinutes.flatMap { $0 > 0 ? $0 : nil } + self.sortOrderIndex = sortOrderIndex + self.updatedAt = updatedAt + self.isDeleted = isDeleted + } +} + +/// 带墓碑时间戳的智能列表文档,用于本地存档与 CloudKVS 双向无冲突合并。 +public struct PodcastSmartPlaylistDocument: Codable, Equatable, Sendable { + public static let currentVersion = 1 + + public var version: Int + public var items: [PodcastSmartPlaylist] + + public init(version: Int = currentVersion, items: [PodcastSmartPlaylist] = []) { + self.version = version + self.items = items + } + + public var activePlaylists: [PodcastSmartPlaylist] { + items + .filter { !$0.isDeleted } + .sorted { lhs, rhs in + if lhs.sortOrderIndex != rhs.sortOrderIndex { return lhs.sortOrderIndex < rhs.sortOrderIndex } + if lhs.updatedAt != rhs.updatedAt { return lhs.updatedAt < rhs.updatedAt } + return lhs.id < rhs.id + } + } + + /// 逐项按 `updatedAt` 最后写入获胜合并,保留已删除墓碑以免跨设备复活。 + public func merged(with other: Self) -> Self { + var byID: [String: PodcastSmartPlaylist] = Dictionary( + items.map { ($0.id, $0) }, + uniquingKeysWith: { lhs, rhs in Self.newer(lhs, rhs) } + ) + for incoming in other.items { + if let existing = byID[incoming.id] { + byID[incoming.id] = Self.newer(existing, incoming) + } else { + byID[incoming.id] = incoming + } + } + let sorted = byID.values.sorted { $0.id < $1.id } + return Self(version: max(version, other.version), items: sorted) + } + + private static func newer(_ lhs: PodcastSmartPlaylist, _ rhs: PodcastSmartPlaylist) -> PodcastSmartPlaylist { + if lhs.updatedAt != rhs.updatedAt { + return lhs.updatedAt > rhs.updatedAt ? lhs : rhs + } + if lhs.isDeleted != rhs.isDeleted { + return lhs.isDeleted ? lhs : rhs + } + return lhs + } + + public func encoded() -> String? { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + encoder.dateEncodingStrategy = .millisecondsSince1970 + guard let data = try? encoder.encode(self) else { return nil } + return String(data: data, encoding: .utf8) + } + + public static func decode(_ raw: String?) -> Self? { + guard let raw, !raw.isEmpty, let data = raw.data(using: .utf8) else { return nil } + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .millisecondsSince1970 + return try? decoder.decode(Self.self, from: data) + } +} + +public enum PodcastSmartPlaylistPolicy { + public static let defaultEpisodeLimit = 200 + + /// 按智能列表规则筛选并排序单集:优先节目按指定顺序置顶,其余节目按列表排序规则排列。 + public static func episodes( + for playlist: PodcastSmartPlaylist, + from episodes: [PodcastEpisode], + state: (PodcastEpisode) -> PodcastEpisodeState, + limit: Int = defaultEpisodeLimit + ) -> [PodcastEpisode] { + guard !playlist.isDeleted, limit > 0 else { return [] } + let selectedSet = Set(playlist.selectedShowIDs) + let maxSeconds = playlist.maxDurationMinutes.map { TimeInterval($0 * 60) } + + let matched = episodes.filter { episode in + switch playlist.showScopeMode { + case .all: + break + case .include: + guard selectedSet.contains(episode.showID) else { return false } + case .exclude: + guard !selectedSet.contains(episode.showID) else { return false } + } + + let episodeState = state(episode) + guard playlist.filter.includes(episodeState) else { return false } + + if let maxSeconds { + guard let total = effectiveDuration(of: episode), total > 0, total <= maxSeconds else { return false } + } + return true + } + + var priorityRank: [String: Int] = [:] + for (index, showID) in playlist.priorityShowIDs.enumerated() where priorityRank[showID] == nil { + priorityRank[showID] = index + } + + let sorted = matched.sorted { lhs, rhs in + let leftRank = priorityRank[lhs.showID] ?? Int.max + let rightRank = priorityRank[rhs.showID] ?? Int.max + if leftRank != rightRank { return leftRank < rightRank } + return compare(lhs, rhs, by: playlist.sort) + } + return Array(sorted.prefix(limit)) + } + + public static func totalRemainingSeconds( + for episodes: [PodcastEpisode], + state: (PodcastEpisode) -> PodcastEpisodeState + ) -> TimeInterval { + episodes.reduce(0) { sum, episode in + let epState = state(episode) + if epState.isFinished { return sum } + guard let total = effectiveDuration(of: episode), total > 0 else { return sum } + let remaining = max(0, total - max(0, epState.position ?? 0)) + return sum + remaining + } + } + + private static func effectiveDuration(of episode: PodcastEpisode) -> TimeInterval? { + if let listed = episode.duration, listed.isFinite, listed > 0 { return listed } + return nil + } + + private static func compare( + _ lhs: PodcastEpisode, + _ rhs: PodcastEpisode, + by sort: PodcastSmartPlaylist.SortOrder + ) -> Bool { + switch sort { + case .newestFirst: + let ld = lhs.publishedAt ?? lhs.firstSeenAt + let rd = rhs.publishedAt ?? rhs.firstSeenAt + if ld != rd { return ld > rd } + return lhs.id < rhs.id + case .oldestFirst: + let ld = lhs.publishedAt ?? lhs.firstSeenAt + let rd = rhs.publishedAt ?? rhs.firstSeenAt + if ld != rd { return ld < rd } + return lhs.id < rhs.id + case .shortestFirst: + let ld = effectiveDuration(of: lhs) ?? .greatestFiniteMagnitude + let rd = effectiveDuration(of: rhs) ?? .greatestFiniteMagnitude + if ld != rd { return ld < rd } + return (lhs.publishedAt ?? lhs.firstSeenAt) > (rhs.publishedAt ?? rhs.firstSeenAt) + case .longestFirst: + let ld = effectiveDuration(of: lhs) ?? -1 + let rd = effectiveDuration(of: rhs) ?? -1 + if ld != rd { return ld > rd } + return (lhs.publishedAt ?? lhs.firstSeenAt) > (rhs.publishedAt ?? rhs.firstSeenAt) + } + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift new file mode 100644 index 000000000..76c97104a --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift @@ -0,0 +1,115 @@ +import Foundation +import PrimuseKit +import Testing + +@Suite("Podcast Smart Playlists Policy and Merge") +struct PodcastSmartPlaylistTests { + + private func makeEpisode( + id: String, + showID: String, + publishedAt: Date, + duration: TimeInterval? = 1800 + ) -> PodcastEpisode { + PodcastEpisode( + id: id, + showID: showID, + guid: id, + title: id, + publishedAt: publishedAt, + duration: duration, + enclosureURL: URL(string: "https://example.com/\(id).mp3")!, + firstSeenAt: publishedAt + ) + } + + @Test("Priority shows sort ahead of non-priority shows in exact priority order") + func priorityShowOrderingAndScope() { + let base = Date(timeIntervalSince1970: 1_700_000_000) + let episodes = [ + makeEpisode(id: "reg-newest", showID: "show-regular", publishedAt: base.addingTimeInterval(300), duration: 2400), + makeEpisode(id: "p2-old", showID: "show-p2", publishedAt: base.addingTimeInterval(100), duration: 1200), + makeEpisode(id: "p1-old", showID: "show-p1", publishedAt: base.addingTimeInterval(50), duration: 900), + makeEpisode(id: "p1-new", showID: "show-p1", publishedAt: base.addingTimeInterval(200), duration: 1000), + makeEpisode(id: "excluded", showID: "show-excluded", publishedAt: base.addingTimeInterval(500), duration: 600), + ] + + let playlist = PodcastSmartPlaylist( + name: "Morning Commute", + showScopeMode: .exclude, + selectedShowIDs: ["show-excluded"], + priorityShowIDs: ["show-p1", "show-p2"], + filter: .unplayed, + sort: .newestFirst + ) + + let resolved = PodcastSmartPlaylistPolicy.episodes( + for: playlist, + from: episodes, + state: { _ in PodcastEpisodeState() } + ) + + #expect(resolved.map(\.id) == ["p1-new", "p1-old", "p2-old", "reg-newest"]) + } + + @Test("Duration cap, shortest sort, downloaded filter, and remaining time work together") + func durationCapAndFilters() { + let base = Date(timeIntervalSince1970: 1_700_000_000) + let episodes = [ + makeEpisode(id: "short-10m", showID: "s1", publishedAt: base, duration: 600), + makeEpisode(id: "med-25m", showID: "s1", publishedAt: base.addingTimeInterval(60), duration: 1500), + makeEpisode(id: "long-45m", showID: "s1", publishedAt: base.addingTimeInterval(120), duration: 2700), + makeEpisode(id: "unknown", showID: "s1", publishedAt: base.addingTimeInterval(180), duration: nil), + ] + + let playlist = PodcastSmartPlaylist( + name: "Quick", + showScopeMode: .include, + selectedShowIDs: ["s1"], + filter: .downloaded, + sort: .shortestFirst, + maxDurationMinutes: 30 + ) + + let downloaded: Set = ["short-10m", "med-25m", "long-45m", "unknown"] + let stateProvider: (PodcastEpisode) -> PodcastEpisodeState = { ep in + PodcastEpisodeState( + position: ep.id == "med-25m" ? 300 : nil, + isFinished: false, + isDownloaded: downloaded.contains(ep.id) + ) + } + let resolved = PodcastSmartPlaylistPolicy.episodes( + for: playlist, + from: episodes, + state: stateProvider + ) + + #expect(resolved.map(\.id) == ["short-10m", "med-25m"]) + let remaining = PodcastSmartPlaylistPolicy.totalRemainingSeconds(for: resolved, state: stateProvider) + #expect(abs(remaining - 1800) < 0.01) + } + + @Test("Document merge honors tombstones and newer edits without resurrection") + func tombstoneMergeRoundTrip() throws { + let t1 = Date(timeIntervalSince1970: 1_700_000_000) + let t2 = Date(timeIntervalSince1970: 1_700_000_100) + let local = PodcastSmartPlaylistDocument(items: [ + PodcastSmartPlaylist(id: "a", name: "Local Old", updatedAt: t1), + PodcastSmartPlaylist(id: "b", name: "Deleted Local", updatedAt: t2, isDeleted: true), + ]) + let remote = PodcastSmartPlaylistDocument(items: [ + PodcastSmartPlaylist(id: "a", name: "Remote New", sortOrderIndex: 0, updatedAt: t2), + PodcastSmartPlaylist(id: "b", name: "Still Alive On Old Device", sortOrderIndex: 1, updatedAt: t1, isDeleted: false), + PodcastSmartPlaylist(id: "c", name: "Remote Added", sortOrderIndex: 2, updatedAt: t1), + ]) + + let merged = local.merged(with: remote) + let encoded = try #require(merged.encoded()) + let decoded = try #require(PodcastSmartPlaylistDocument.decode(encoded)) + + #expect(decoded.activePlaylists.map(\.id) == ["a", "c"]) + #expect(decoded.activePlaylists.first(where: { $0.id == "a" })?.name == "Remote New") + #expect(decoded.items.first(where: { $0.id == "b" })?.isDeleted == true) + } +} diff --git a/PrimuseTests/PodcastReliabilityTests.swift b/PrimuseTests/PodcastReliabilityTests.swift index bb854faaf..90b7f9758 100644 --- a/PrimuseTests/PodcastReliabilityTests.swift +++ b/PrimuseTests/PodcastReliabilityTests.swift @@ -244,6 +244,40 @@ final class PodcastReliabilityTests: XCTestCase { XCTAssertGreaterThanOrEqual(reloadCount, 1) XCTAssertEqual(defaults.string(forKey: key), "remote-copy") } + + func testPodcastSmartPlaylistStorePersistsMergesAndDeletesWithoutResurrection() throws { + let defaults = try makeDefaults() + let store = PodcastSmartPlaylistStore(defaults: defaults, syncsWithCloud: false) + let t1 = Date(timeIntervalSince1970: 1_700_000_000) + let t2 = Date(timeIntervalSince1970: 1_700_000_200) + + let commute = PodcastSmartPlaylist( + id: "pl-commute", + name: "Commute", + symbol: "car", + priorityShowIDs: ["show-news"], + filter: .unplayed, + sort: .shortestFirst, + maxDurationMinutes: 30 + ) + store.save(commute, now: t1) + XCTAssertEqual(store.playlists.map(\.id), ["pl-commute"]) + + let reloaded = PodcastSmartPlaylistStore(defaults: defaults, syncsWithCloud: false) + XCTAssertEqual(reloaded.playlist(id: "pl-commute")?.maxDurationMinutes, 30) + + store.delete(id: "pl-commute", now: t2) + XCTAssertTrue(store.playlists.isEmpty) + + // Simulate older remote device pushing pre-delete copy + a brand-new playlist. + let remoteDoc = PodcastSmartPlaylistDocument(items: [ + PodcastSmartPlaylist(id: "pl-commute", name: "Commute Old", updatedAt: t1, isDeleted: false), + PodcastSmartPlaylist(id: "pl-deep", name: "Deep Dives", updatedAt: t2, isDeleted: false), + ]) + defaults.set(remoteDoc.encoded(), forKey: CloudKVSKey.podcastSmartPlaylists) + store.mergeFromCloud() + XCTAssertEqual(store.playlists.map(\.id), ["pl-deep"]) + } } private final class InMemoryCloudKVSStore: CloudKeyValueStore, @unchecked Sendable { From 52751608538b2e1483f3dc90b4dc687f364a8452 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Tue, 1 Dec 2026 23:38:13 -0500 Subject: [PATCH 13/15] =?UTF-8?q?=E4=B8=BA=20CarPlay=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E6=92=AD=E5=AE=A2=E6=99=BA=E8=83=BD=E5=88=97=E8=A1=A8=E3=80=81?= =?UTF-8?q?=E9=98=9F=E5=88=97=E8=AE=B0=E5=BF=86=E6=81=A2=E5=A4=8D=E3=80=81?= =?UTF-8?q?=E7=9B=B4=E6=92=AD=E7=94=B5=E5=8F=B0=E4=B8=80=E9=94=AE=E4=BA=BA?= =?UTF-8?q?=E5=A3=B0=E5=A2=9E=E5=BC=BA=E4=B8=8E=E6=9C=89=E5=A3=B0=E9=9F=B3?= =?UTF-8?q?=E6=95=88/=E4=B9=A6=E7=AD=BE=E6=8E=A7=E5=88=B6=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 6 + ...CarPlaySceneDelegate+ListeningSpaces.swift | 196 ++++++++++++++++++ Primuse/App/CarPlaySceneDelegate.swift | 33 ++- .../Audio/AudioPlayerService+SmartSpeed.swift | 36 ++++ .../SpokenWord/SpokenWordSmartSpeed.swift | 19 ++ .../Podcast/PodcastSmartPlaylistTests.swift | 9 + .../ListeningSpacesReliabilityTests.swift | 66 ++++++ 7 files changed, 358 insertions(+), 7 deletions(-) create mode 100644 Primuse/App/CarPlaySceneDelegate+ListeningSpaces.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index e29d399f5..3d3975653 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -544,6 +544,7 @@ 2884064E4D5F393C6BEAC90D /* LibNFSSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C398182E0EA26C9CA640A99 /* LibNFSSession.swift */; }; 288F5BD3EBB2A4FC33A36598 /* SongCommentService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C5D6431B58D2FF9990F9ECF /* SongCommentService.swift */; }; 28E1B2A67479842A55E70EEC /* DetailPagesCatalogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62142525A0636EE88FFFA8EB /* DetailPagesCatalogTests.swift */; }; + 28EFBB8DFAA298E54A5A21C3 /* CarPlaySceneDelegate+ListeningSpaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 397F28BE5BC47AB01F06D5F5 /* CarPlaySceneDelegate+ListeningSpaces.swift */; }; 28F4B34022CC7F173A4DE8A9 /* LyricPosterMotionPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3880989AB3DC0D23E77E1C60 /* LyricPosterMotionPolicy.swift */; }; 2909C090AE7676CE1E7903A9 /* ArtistCatalogPagesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 432CBD1FDBCD7D8E8FD7916B /* ArtistCatalogPagesTests.swift */; }; 2911D48A97542DBBFEE96888 /* BackfillWorkerWithoutTheModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C2B61ACA694B9534CD07D7 /* BackfillWorkerWithoutTheModelTests.swift */; }; @@ -1002,6 +1003,7 @@ 49C04C8ECE526F33E1822F24 /* SearchExperienceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 502D5EFB720F730676C38919 /* SearchExperienceTests.swift */; }; 4A03D49C98F63571EC90657A /* EQCalibrationCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 214AB159477133357ECE8B9E /* EQCalibrationCatalog.swift */; }; 4A3C82CAB29786A4927140E7 /* AnimatedArtworkDataView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F44E04BAF67DF37C98C9FDAF /* AnimatedArtworkDataView.swift */; }; + 4A467C075BAA971B0218C943 /* CarPlaySceneDelegate+ListeningSpaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 397F28BE5BC47AB01F06D5F5 /* CarPlaySceneDelegate+ListeningSpaces.swift */; }; 4A5B4E2125342594307BFB12 /* BatchAddToPlaylistSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06924D96CB41F49216C2FF95 /* BatchAddToPlaylistSheet.swift */; }; 4A5B658C21A8F1A058CA8FA3 /* MacSourceWaterfallLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1B47E14BA841CF9E5C9D2B /* MacSourceWaterfallLayout.swift */; }; 4A7B8B04C112A5A32DE12EEB /* SubsonicPlaylistCreateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A0009FEE3F7B9452AFE010B /* SubsonicPlaylistCreateTests.swift */; }; @@ -4278,6 +4280,7 @@ 38FB8C7B3EA4A58B80265EDC /* Playlist.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Playlist.swift; sourceTree = ""; }; 391F3BAAC021423CF12BFC5B /* ScrapeReview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrapeReview.swift; sourceTree = ""; }; 392ED1C12D986BAB8D2A1EBD /* LyricsWriteback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyricsWriteback.swift; sourceTree = ""; }; + 397F28BE5BC47AB01F06D5F5 /* CarPlaySceneDelegate+ListeningSpaces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CarPlaySceneDelegate+ListeningSpaces.swift"; sourceTree = ""; }; 39E5A5955F4B02D9288BF3C9 /* CatalogViewsAndAppShellCleanupTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatalogViewsAndAppShellCleanupTests.swift; sourceTree = ""; }; 39F6AE35FC2EC095FBF1EA0E /* AudioEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioEngine.swift; sourceTree = ""; }; 39F7526DBC953AFA235E549F /* EmbeddedTagMetadataParser+ISOBaseMedia.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EmbeddedTagMetadataParser+ISOBaseMedia.swift"; sourceTree = ""; }; @@ -7569,6 +7572,7 @@ 67E4F3BB9F1CA9822640185B /* CarPlayCatalogLists.swift */, 7C8D0CD987CACC83D845497B /* CarPlaySceneDelegate.swift */, EAA9F51698118F20BD37ABB5 /* CarPlaySceneDelegate+AudioQualityPopup.swift */, + 397F28BE5BC47AB01F06D5F5 /* CarPlaySceneDelegate+ListeningSpaces.swift */, 01373844CF5793D3A12004C8 /* CarPlaySceneDelegate+WholePlaylist.swift */, DFDA98C86E579C0ADE094ADA /* CarPlaySearchMatches.swift */, 8ECFDEED1E57CE52C2B071B5 /* DebugAccessibilityScript.swift */, @@ -11449,6 +11453,7 @@ FA1E5972AEC597561FDCD6F9 /* CarPlayHomeContent.swift in Sources */, 9E7BF48E5665AAC363F681D5 /* CarPlayModuleInspector.swift in Sources */, A6E6CE7B5B20F37C0AC317A0 /* CarPlaySceneDelegate+AudioQualityPopup.swift in Sources */, + 4A467C075BAA971B0218C943 /* CarPlaySceneDelegate+ListeningSpaces.swift in Sources */, B8B21B05FFF23E7D0E3F93B1 /* CarPlaySceneDelegate+WholePlaylist.swift in Sources */, BD0BDF735869A9109E313E0E /* CarPlaySceneDelegate.swift in Sources */, 6181A1A66CDB6ED9DC9B75CA /* CarPlaySearchMatches.swift in Sources */, @@ -12678,6 +12683,7 @@ 45D03F8EAB0160FC97F2221A /* CarPlayHomeContent.swift in Sources */, C617397EE2A39A6E64FD6A92 /* CarPlayModuleInspector.swift in Sources */, 4760452E65ABD40929A63842 /* CarPlaySceneDelegate+AudioQualityPopup.swift in Sources */, + 28EFBB8DFAA298E54A5A21C3 /* CarPlaySceneDelegate+ListeningSpaces.swift in Sources */, 2483F35F9CAFE8C45A8D28A5 /* CarPlaySceneDelegate+WholePlaylist.swift in Sources */, 5BFA0F2DB7AF20E3D70CD55C /* CarPlaySceneDelegate.swift in Sources */, 44A0CB2C79127C05EEDB4471 /* CarPlaySearchMatches.swift in Sources */, diff --git a/Primuse/App/CarPlaySceneDelegate+ListeningSpaces.swift b/Primuse/App/CarPlaySceneDelegate+ListeningSpaces.swift new file mode 100644 index 000000000..d94d98ada --- /dev/null +++ b/Primuse/App/CarPlaySceneDelegate+ListeningSpaces.swift @@ -0,0 +1,196 @@ +#if os(iOS) +@preconcurrency import CarPlay +import PrimuseKit +import UIKit + +/// CarPlay 有声空间扩展:播客队列记忆一键续播、播客智能列表(含一键播完)、 +/// 直播电台一键人声增强以及有声内容「更多」里的音效与书签快捷项。 +extension CarPlaySceneDelegate { + func makeSmartPlaylistChangesObserver(generation: Int) -> NSObjectProtocol { + NotificationCenter.default.addObserver( + forName: .primusePodcastSmartPlaylistsDidChange, + object: nil, + queue: .main + ) { [weak self] _ in + Task { @MainActor [weak self] in + guard let self, self.isConnected(generation: generation) else { return } + self.refreshPodcastListsIfVisible() + } + } + } + + /// 播客页顶部附加区块:跨空间记住的播客队列(一键恢复)与播客智能列表。 + func podcastQueueAndSmartPlaylistSections(budget: inout Int) -> [CPListSection] { + var sections: [CPListSection] = [] + let player = AppServices.shared.playerService + + if budget > 0, let summary = player.rememberedPodcastQueueSummary { + let detail = "\(String(localized: "up_next")) · \(summary.remainingCount)" + let item = CPListItem( + text: summary.lead.title, + detailText: detail, + image: Self.symbolImage("text.line.first.and.arrowtriangle.forward") + ) + item.handler = { [weak self] _, completion in + Task { @MainActor in + let resumed = await AppServices.shared.playerService.resumeRememberedPodcastQueue() + if resumed { self?.pushNowPlayingIfNeeded() } + completion() + } + } + budget -= 1 + sections.append(CPListSection( + items: [item], + header: String(localized: "podcast_continue"), + sectionIndexTitle: nil + )) + } + + let playlists = PodcastSmartPlaylistStore.shared.playlists + if !playlists.isEmpty, budget > 0 { + let podcastStore = PodcastStore.shared + let items = playlists.prefix(budget).map { playlist -> CPListItem in + let episodes = PodcastSmartPlaylistStore.shared.episodes(for: playlist, in: podcastStore) + let remaining = PodcastSmartPlaylistPolicy.totalRemainingSeconds( + for: episodes, + state: podcastStore.state(for:) + ) + let countText = String(format: String(localized: "podcast_smart_episode_count_format"), episodes.count) + let detail = remaining > 0 + ? "\(countText) · \(SpokenWordListeningStatsPolicy.formattedDuration(remaining))" + : countText + let item = CPListItem( + text: playlist.name, + detailText: detail, + image: Self.symbolImage(playlist.symbol) + ) + item.accessoryType = .disclosureIndicator + item.handler = { [weak self] _, completion in + self?.pushPodcastSmartPlaylist(playlist) + completion() + } + return item + } + budget -= items.count + sections.append(CPListSection( + items: Array(items), + header: String(localized: "podcast_smart_playlists_title"), + sectionIndexTitle: nil + )) + } + return sections + } + + func pushPodcastSmartPlaylist(_ playlist: PodcastSmartPlaylist) { + let podcastStore = PodcastStore.shared + let episodes = PodcastSmartPlaylistStore.shared.episodes(for: playlist, in: podcastStore) + var sections: [CPListSection] = [] + let maxItems = CPListTemplate.maximumItemCount + if !episodes.isEmpty { + let playAll = CPListItem( + text: String(localized: "carplay_play_all"), + detailText: String(format: String(localized: "podcast_smart_episode_count_format"), episodes.count), + image: Self.symbolImage("play.fill") + ) + playAll.handler = { [weak self] _, completion in + Task { @MainActor in + if let first = episodes.first { + let rest = Array(episodes.dropFirst().prefix(50)) + await AppServices.shared.playerService.playPodcast(first, continuing: rest) + self?.pushNowPlayingIfNeeded() + } + completion() + } + } + sections.append(CPListSection(items: [playAll])) + + let episodeBudget = max(0, maxItems - 1) + let items = episodes.prefix(episodeBudget).enumerated().map { index, episode in + podcastEpisodeItem( + episode, + show: podcastStore.show(id: episode.showID), + continuing: Array(episodes.dropFirst(index + 1).prefix(50)), + showsShowTitle: true, + loadsArtwork: CarPlayArtworkLoadPolicy.shouldLoad(index: index) + ) + } + sections.append(CPListSection(items: items)) + } + let template = CPListTemplate(title: playlist.name, sections: sections) + template.emptyViewTitleVariants = [String(localized: "podcast_no_matching_episodes")] + safePush(template, label: "PodcastSmartPlaylist") + } + + /// 直播电台正在播放时的 CarPlay 一键人声增强按钮(支持非 HLS 电台流,与手机端共享按电台覆盖)。 + func liveRadioNowPlayingButtons(minimal: Bool) -> [CPNowPlayingButton] { + let player = AppServices.shared.playerService + guard !minimal, player.isLiveRadio, player.canToggleCurrentRadioVoiceBoost else { return [] } + let active = player.currentEffectiveVoiceBoostEnabled + let button = CPNowPlayingImageButton(image: Self.symbolImage(active ? "waveform.circle.fill" : "waveform")) { [weak self] _ in + Task { @MainActor in + AppServices.shared.playerService.toggleVoiceBoostForCurrentItem() + self?.refreshNowPlayingButtons() + } + } + button.isSelected = active + button.accessibilityLabel = String(localized: "spoken_word_voice_boost") + ", " + + String(localized: active ? "a11y_value_on" : "a11y_value_off") + return [button] + } + + /// 有声书与播客在 CarPlay「更多」页里的音效与书签快捷区:人声增强、智能速度档位循环与一键加书签。 + func nowPlayingListeningSpaceEffectsSections() -> [CPListSection] { + let player = AppServices.shared.playerService + guard player.currentItemIsSpokenWord, !player.isLiveRadio else { return [] } + var items: [CPListItem] = [] + + let voiceBoostOn = player.currentEffectiveVoiceBoostEnabled + let voiceItem = CPListItem( + text: String(localized: "spoken_word_voice_boost"), + detailText: String(localized: voiceBoostOn ? "a11y_value_on" : "a11y_value_off"), + image: Self.symbolImage(voiceBoostOn ? "waveform.circle.fill" : "waveform") + ) + voiceItem.handler = { [weak self] _, completion in + Task { @MainActor in + AppServices.shared.playerService.toggleVoiceBoostForCurrentItem() + self?.refreshNowPlayingButtons() + completion() + } + } + items.append(voiceItem) + + let smartLevel = player.currentEffectiveSmartSpeedLevel + let smartItem = CPListItem( + text: String(localized: "spoken_word_smart_speed"), + detailText: NSLocalizedString(smartLevel.titleKey, comment: ""), + image: Self.symbolImage(smartLevel.isEnabled ? "gauge.with.dots.needle.67percent" : "gauge.with.dots.needle.0percent") + ) + smartItem.handler = { [weak self] _, completion in + Task { @MainActor in + _ = AppServices.shared.playerService.cycleSmartSpeedLevelForCurrentItem() + self?.refreshNowPlayingButtons() + completion() + } + } + items.append(smartItem) + + let bookmarkItem = CPListItem( + text: String(localized: "spoken_word_add_bookmark"), + detailText: nil, + image: Self.symbolImage("bookmark.fill") + ) + bookmarkItem.handler = { [weak self] _, completion in + Task { @MainActor in + let added = AppServices.shared.playerService.addSpokenWordBookmark() + self?.presentMessage(String(localized: added + ? "transcript_reader_bookmark_added" + : "transcript_reader_bookmark_exists")) + completion() + } + } + items.append(bookmarkItem) + + return [CPListSection(items: items)] + } +} +#endif diff --git a/Primuse/App/CarPlaySceneDelegate.swift b/Primuse/App/CarPlaySceneDelegate.swift index f63736e29..563255263 100644 --- a/Primuse/App/CarPlaySceneDelegate.swift +++ b/Primuse/App/CarPlaySceneDelegate.swift @@ -80,8 +80,10 @@ final class CarPlaySceneDelegate: UIResponder { private var likeChangesObserver: NSObjectProtocol? private var spokenWordChangesObserver: NSObjectProtocol? private var podcastChangesObserver: NSObjectProtocol? + private var smartPlaylistChangesObserver: NSObjectProtocol? var layout: CarPlayLayoutConfiguration { CarPlaySettingsStore.shared.configuration } + func isConnected(generation: Int) -> Bool { interfaceController != nil && connectionGeneration == generation } } // MARK: - Scene lifecycle @@ -239,6 +241,8 @@ extension CarPlaySceneDelegate: CPTemplateApplicationSceneDelegate { self.spokenWordChangesObserver = nil if let observer = self.podcastChangesObserver { NotificationCenter.default.removeObserver(observer) } self.podcastChangesObserver = nil + if let observer = self.smartPlaylistChangesObserver { NotificationCenter.default.removeObserver(observer) } + self.smartPlaylistChangesObserver = nil } } } @@ -471,7 +475,7 @@ extension CarPlaySceneDelegate { /// Serializes navigation and makes room before the five-level framework /// limit. A completion handler alone is insufficient: recent CarPlay builds /// can raise `clientExceededHierarchyDepthLimit` before returning an error. - private func safePush(_ template: CPTemplate, label: String) { + func safePush(_ template: CPTemplate, label: String) { if let list = template as? CPListTemplate { configureNavigation(on: list) } guard let ic = interfaceController else { return } guard !navigationTransitionInFlight, !isNowPlayingTransitionInFlight else { @@ -1769,7 +1773,7 @@ extension CarPlaySceneDelegate { let store = PodcastStore.shared var budget = CPListTemplate.maximumItemCount var artworkIndex = 0 - var sections: [CPListSection] = [] + var sections = podcastQueueAndSmartPlaylistSections(budget: &budget) let inProgress = Array(store.inProgressEpisodes(limit: 6).prefix(budget)) if !inProgress.isEmpty { @@ -1885,7 +1889,7 @@ extension CarPlaySceneDelegate { safePush(template, label: "PodcastShow") } - private func podcastEpisodeItem( + func podcastEpisodeItem( _ episode: PodcastEpisode, show: PodcastShow?, continuing: [PodcastEpisode], @@ -2084,7 +2088,7 @@ extension CarPlaySceneDelegate { presentMessage(String(format: String(localized: "carplay_play_failed_format"), songTitle)) } - private func presentMessage(_ title: String) { + func presentMessage(_ title: String) { guard let controller = interfaceController, controller.presentedTemplate == nil else { return } let alert = CPAlertTemplate( titleVariants: [title], @@ -2171,6 +2175,9 @@ extension CarPlaySceneDelegate { let repeatMode: RepeatMode let liked: Bool let rate: Float + let voiceBoostEnabled: Bool + let smartSpeedLevel: SmartSpeedLevel + let canToggleRadioVoiceBoost: Bool let skipBackward: Int let skipForward: Int let qualityDetails: String? @@ -2209,6 +2216,9 @@ extension CarPlaySceneDelegate { repeatMode: player.repeatMode, liked: isCurrentSongLiked(song), rate: player.currentSpokenWordRate, + voiceBoostEnabled: player.currentEffectiveVoiceBoostEnabled, + smartSpeedLevel: player.currentEffectiveSmartSpeedLevel, + canToggleRadioVoiceBoost: player.canToggleCurrentRadioVoiceBoost, skipBackward: player.spokenWordSkipBackwardSeconds, skipForward: player.spokenWordSkipForwardSeconds, qualityDetails: song.map { CarPlayAudioQualityText(song: $0, transcodePlan: player.activeTranscodePlan).details }, @@ -2242,7 +2252,10 @@ extension CarPlaySceneDelegate { && (topAction != .album || signature.hasAlbum) template.isAlbumArtistButtonEnabled = !player.isLiveRadio && !signature.minimal && (signature.hasAlbum || signature.hasArtist) - template.updateNowPlayingButtons(signature.actions.map { makeNowPlayingButton($0) }) + let nowPlayingButtons = player.isLiveRadio + ? liveRadioNowPlayingButtons(minimal: signature.minimal) + : signature.actions.map { makeNowPlayingButton($0) } + template.updateNowPlayingButtons(nowPlayingButtons) if let controller = interfaceController, let sheet = controller.presentedTemplate as? CPActionSheetTemplate, let songID = sheet.userInfo as? String, songID != player.currentSong?.id || player.isLiveRadio || player.currentItemIsSpokenWord { @@ -2614,7 +2627,7 @@ extension CarPlaySceneDelegate { } return item } - return [CPListSection(items: items)] + return [CPListSection(items: items)] + nowPlayingListeningSpaceEffectsSections() } /// Resolves an SF Symbol name to a `UIImage`, returning a 1x1 blank @@ -2796,9 +2809,10 @@ extension CarPlaySceneDelegate { self.refreshPodcastListsIfVisible() } } + smartPlaylistChangesObserver = makeSmartPlaylistChangesObserver(generation: generation) } - private func refreshPodcastListsIfVisible() { + func refreshPodcastListsIfVisible() { let top = interfaceController?.topTemplate as? CPListTemplate if let top, top.userInfo as? String == Self.podcastListUserInfo { top.updateSections(podcastSections()) @@ -2922,6 +2936,11 @@ extension CarPlaySceneDelegate { _ = player.playbackSettings.spokenWordPlaybackRate _ = SpokenWordStore.shared.bookRates } + _ = SpokenWordAudioEffectsPreferences.shared.revision + _ = player.playbackSettings.spokenWordVoiceBoostEnabled + _ = player.playbackSettings.radioVoiceBoostEnabled + _ = player.playbackSettings.spokenWordSmartSpeedEnabled + _ = player.playbackSettings.spokenWordSmartSpeedLevel _ = player.spokenWordSkipForwardSeconds _ = player.spokenWordSkipBackwardSeconds _ = player.currentIndex diff --git a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift index e1592903f..b723d86f3 100644 --- a/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift +++ b/Primuse/Services/Audio/AudioPlayerService+SmartSpeed.swift @@ -232,6 +232,42 @@ extension AudioPlayerService { return effectiveVoiceBoostActive(for: currentSong) } + /// 跨空间一键切换当前条目的人声增强(电台复用按电台覆盖,播客/有声书按节目或按书覆盖),供 CarPlay 等快捷入口复用。 + func toggleVoiceBoostForCurrentItem() { + if isLiveRadio { + toggleCurrentRadioVoiceBoost() + return + } + guard let song = currentSong else { return } + let target = !effectiveVoiceBoostActive(for: song) + if let scopeID = audioEffectsScopeID(for: song) { + let stored = SpokenWordAudioEffectsPolicy.storedVoiceBoostOverride( + for: target, + global: playbackSettings.spokenWordVoiceBoostEnabled + ) + SpokenWordAudioEffectsPreferences.shared.setVoiceBoostEnabled(stored, forScopeID: scopeID) + } else { + playbackSettings.spokenWordVoiceBoostEnabled = target + } + } + + /// 跨空间单键循环切换当前有声条目的智能速度档位(关 → 轻柔 → 标准 → 强力 → 关),优先写入按节目/按书覆盖。 + @discardableResult + func cycleSmartSpeedLevelForCurrentItem() -> SmartSpeedLevel { + guard let song = currentSong, !isLiveRadio else { return .off } + let next = effectiveSmartSpeedLevel(for: song).nextCycled + if let scopeID = audioEffectsScopeID(for: song) { + let stored = SpokenWordAudioEffectsPolicy.storedSmartSpeedOverride( + for: next, + global: globalSmartSpeedLevel + ) + SpokenWordAudioEffectsPreferences.shared.setSmartSpeedLevel(stored, forScopeID: scopeID) + } else { + setGlobalSmartSpeedLevel(next) + } + return next + } + /// 开启智能速度且当前条目已实际缩短停顿时,估算当前等效倍速(例如 1.5× → 1.72×)。 var currentSmartSpeedEffectiveRate: Float? { guard currentItemIsSpokenWord, diff --git a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift index b77609e88..1e0817008 100644 --- a/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift +++ b/PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordSmartSpeed.swift @@ -536,6 +536,25 @@ public enum SmartSpeedLevel: String, Codable, CaseIterable, Hashable, Sendable, case .strong: return .strong } } + + /// 供 CarPlay / 快捷开关单键循环切换智能速度档位:关 → 轻柔 → 标准 → 强力 → 关。 + public var nextCycled: SmartSpeedLevel { + switch self { + case .off: return .mild + case .mild: return .standard + case .standard: return .strong + case .strong: return .off + } + } + + public var titleKey: String { + switch self { + case .off: return "smart_speed_level_off" + case .mild: return "smart_speed_level_mild" + case .standard: return "smart_speed_level_standard" + case .strong: return "smart_speed_level_strong" + } + } } /// 实时估算开启智能速度后的等效倍速(例如基准 1.5× 且已跳过 12% 停顿 → 等效约 1.7×)。 diff --git a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift index 76c97104a..875d74ee4 100644 --- a/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift +++ b/PrimuseKit/Tests/PrimuseKitTests/Podcast/PodcastSmartPlaylistTests.swift @@ -112,4 +112,13 @@ struct PodcastSmartPlaylistTests { #expect(decoded.activePlaylists.first(where: { $0.id == "a" })?.name == "Remote New") #expect(decoded.items.first(where: { $0.id == "b" })?.isDeleted == true) } + + @Test("SmartSpeedLevel cycles through all four intensities and provides localized title keys") + func smartSpeedLevelCycleAndTitleKeys() { + #expect(SmartSpeedLevel.off.nextCycled == .mild) + #expect(SmartSpeedLevel.mild.nextCycled == .standard) + #expect(SmartSpeedLevel.standard.nextCycled == .strong) + #expect(SmartSpeedLevel.strong.nextCycled == .off) + #expect(SmartSpeedLevel.allCases.allSatisfy { $0.titleKey.hasPrefix("smart_speed_level_") }) + } } diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index 8cb0ebba9..2521e22fd 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -650,4 +650,70 @@ final class ListeningSpacesReliabilityTests: XCTestCase { XCTAssertEqual(player.pendingSpokenWordSeekOverride?.songID, audiobook.id) XCTAssertEqual(player.pendingSpokenWordSeekOverride?.position ?? -1, 1_800, accuracy: 0.1) } + + func testToggleVoiceBoostAndCycleSmartSpeedForCurrentItemAcrossSpaces() { + let player = AudioPlayerService() + let prevVoice = player.playbackSettings.spokenWordVoiceBoostEnabled + let prevRadioVoice = player.playbackSettings.radioVoiceBoostEnabled + let prevSmartEnabled = player.playbackSettings.spokenWordSmartSpeedEnabled + let prevSmartLevel = player.playbackSettings.spokenWordSmartSpeedLevel + cleanups.append { + player.playbackSettings.spokenWordVoiceBoostEnabled = prevVoice + player.playbackSettings.radioVoiceBoostEnabled = prevRadioVoice + player.playbackSettings.spokenWordSmartSpeedEnabled = prevSmartEnabled + player.playbackSettings.spokenWordSmartSpeedLevel = prevSmartLevel + } + player.playbackSettings.spokenWordVoiceBoostEnabled = false + player.playbackSettings.radioVoiceBoostEnabled = false + player.setGlobalSmartSpeedLevel(.off) + + let bookSong = Song( + id: "cycle-book-\(UUID().uuidString)", + title: "Cycle Chapter", + artistName: "Narrator", + duration: 1_800, + fileFormat: .m4a, + filePath: "/books/cycle.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + let bookScope = player.spokenWordBookID(for: bookSong) + cleanups.append { SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: bookScope) } + + player.currentSong = bookSong + player.handleSpokenWordItemChange(to: bookSong) + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + player.toggleVoiceBoostForCurrentItem() + XCTAssertTrue(player.currentEffectiveVoiceBoostEnabled) + player.toggleVoiceBoostForCurrentItem() + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + XCTAssertFalse(SpokenWordAudioEffectsPreferences.shared.hasOverride(forScopeID: bookScope)) + + XCTAssertEqual(player.cycleSmartSpeedLevelForCurrentItem(), .mild) + XCTAssertEqual(player.currentEffectiveSmartSpeedLevel, .mild) + XCTAssertEqual(player.cycleSmartSpeedLevelForCurrentItem(), .standard) + XCTAssertEqual(player.cycleSmartSpeedLevelForCurrentItem(), .strong) + XCTAssertEqual(player.cycleSmartSpeedLevelForCurrentItem(), .off) + XCTAssertFalse(SpokenWordAudioEffectsPreferences.shared.hasOverride(forScopeID: bookScope)) + + let station = RadioStation( + id: "carplay-talk-\(UUID().uuidString)", + name: "CarPlay Talk FM", + streamURL: "https://radio.example.com/talk.aac", + streamFormat: .aac + ) + let radioScope = SpokenWordAudioEffectsPolicy.radioScopeID(forStationID: station.id) + cleanups.append { SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: radioScope) } + player.playbackKind = .liveRadio + player.currentRadioStation = station + player.currentSong = station.playbackSong + player.radioStreamFormat = .aac + player.radioResolvedStreamURL = URL(string: station.streamURL) + + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + player.toggleVoiceBoostForCurrentItem() + XCTAssertTrue(player.currentEffectiveVoiceBoostEnabled) + player.toggleVoiceBoostForCurrentItem() + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + } } From 1c77e77ddb1dd6d50f44ec439152978a88d49518 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Wed, 2 Dec 2026 01:59:54 -0500 Subject: [PATCH 14/15] =?UTF-8?q?=E4=B8=BA=20Apple=20Watch=20=E4=B8=8E?= =?UTF-8?q?=E5=BF=AB=E6=8D=B7=E6=8C=87=E4=BB=A4=E8=A1=A5=E9=BD=90=E6=9C=89?= =?UTF-8?q?=E5=A3=B0=E4=B9=A6/=E6=92=AD=E5=AE=A2/=E7=94=B5=E5=8F=B0?= =?UTF-8?q?=E9=9F=B3=E6=95=88=E3=80=81=E4=B9=A6=E7=AD=BE=E4=B8=8E=E6=99=BA?= =?UTF-8?q?=E8=83=BD=E5=88=97=E8=A1=A8=E6=8E=A7=E5=88=B6=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Primuse.xcodeproj/project.pbxproj | 16 ++ .../Resources/ar.lproj/Localizable.strings | 20 ++ .../Resources/de.lproj/Localizable.strings | 20 ++ .../Resources/en.lproj/Localizable.strings | 20 ++ .../Resources/es-MX.lproj/Localizable.strings | 20 ++ .../Resources/fr.lproj/Localizable.strings | 20 ++ .../Resources/hi.lproj/Localizable.strings | 20 ++ .../Resources/ja.lproj/Localizable.strings | 20 ++ .../Resources/ko.lproj/Localizable.strings | 20 ++ .../Resources/pl.lproj/Localizable.strings | 20 ++ .../Resources/pt-BR.lproj/Localizable.strings | 20 ++ .../Resources/ru.lproj/Localizable.strings | 20 ++ .../Resources/th.lproj/Localizable.strings | 20 ++ .../Resources/tr.lproj/Localizable.strings | 20 ++ .../Resources/uk.lproj/Localizable.strings | 20 ++ .../zh-Hans.lproj/Localizable.strings | 20 ++ .../zh-Hant.lproj/Localizable.strings | 20 ++ .../Intents/PrimusePodcastSmartIntents.swift | 165 +++++++++++++++++ .../WatchSessionBridge+ListeningSpaces.swift | 136 ++++++++++++++ .../Services/Watch/WatchSessionBridge.swift | 79 +------- .../ListeningSpacesReliabilityTests.swift | 80 ++++++++ .../WatchPlayerStore+ListeningSpaces.swift | 173 ++++++++++++++++++ PrimuseWatch/Stores/WatchPlayerStore.swift | 90 ++------- .../Views/PlaybackOptionsWatchView.swift | 86 +++++++++ .../WatchOfflineLocalization.swift | 47 +++-- 25 files changed, 1023 insertions(+), 169 deletions(-) create mode 100644 Primuse/Services/Intents/PrimusePodcastSmartIntents.swift create mode 100644 Primuse/Services/Watch/WatchSessionBridge+ListeningSpaces.swift create mode 100644 PrimuseWatch/Stores/WatchPlayerStore+ListeningSpaces.swift diff --git a/Primuse.xcodeproj/project.pbxproj b/Primuse.xcodeproj/project.pbxproj index 3d3975653..1f09d6f0f 100644 --- a/Primuse.xcodeproj/project.pbxproj +++ b/Primuse.xcodeproj/project.pbxproj @@ -740,6 +740,7 @@ 384C1E6C267650A993BDAF4F /* MusicScraperProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9081DDAD5B33D4D005479E15 /* MusicScraperProtocol.swift */; }; 3870ED1EB775CD09AE8BDFF5 /* LocalLyricsTranslationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9E592DD1CCF41B16100DA36 /* LocalLyricsTranslationService.swift */; }; 387AB3C002EF89D0A282EAF5 /* ScrollingControlSurfacePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BD044925450676CA0647C4E /* ScrollingControlSurfacePolicy.swift */; }; + 387F05C1C3BC004A1D49C57F /* WatchSessionBridge+ListeningSpaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F29BD8E3D5DE15C5227270C /* WatchSessionBridge+ListeningSpaces.swift */; }; 38880CDB964A3E0FE9035019 /* KaraokeSeparationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08FFC4385F8728673FC14C44 /* KaraokeSeparationService.swift */; }; 389FD71E5AB9C4E87852B1FB /* SourcesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6723FC0B92EDA2CC1B5E3C83 /* SourcesView.swift */; }; 38A135AAC750CAF0DE89773E /* CueSheetParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0039D9169F515627C5A4C159 /* CueSheetParser.swift */; }; @@ -832,6 +833,7 @@ 3E76208357B72B12BA9F6F7B /* SceneTransitionScanQuiescePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFF67A5436EA1ED5A1E95EB1 /* SceneTransitionScanQuiescePolicy.swift */; }; 3E893D9D77CFCCB6346364E9 /* LyricPosterStylesConcept.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85C0A8B48185041965BAAEAB /* LyricPosterStylesConcept.swift */; }; 3E8A172723FC1BFACC79B1EA /* MotionCoverStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16D263F16FC43B6E68540049 /* MotionCoverStore.swift */; }; + 3EAD1D6DBB36AD5FBDB404FC /* PrimusePodcastSmartIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = D97CBB28235F105F24B3DEDB /* PrimusePodcastSmartIntents.swift */; }; 3EB87E282D89AAD20DCC556E /* MacFullScreenPlayerPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 652457500A05BA279B755BB1 /* MacFullScreenPlayerPolicy.swift */; }; 3EDD8F0535AFFCAD9E9F864C /* SongListView+SortOrder.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A4C59FD3210930058B4945 /* SongListView+SortOrder.swift */; }; 3EF3F2C9F771CE3099925035 /* LibraryCatalog+PlaylistMatching.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF6BC8D847F0762C91917394 /* LibraryCatalog+PlaylistMatching.swift */; }; @@ -1394,6 +1396,7 @@ 676F7EB2A047E4F94C71BEB6 /* HTTPByteRangeResponsePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = F68DBC58EDE7C37F62AF8D0B /* HTTPByteRangeResponsePolicy.swift */; }; 677455302ECA84391764846D /* LibrarySnapshotSync+LongLivedTransfer.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB3C0CC8B4A92851654ABFBF /* LibrarySnapshotSync+LongLivedTransfer.swift */; }; 677769AB511D06F3889FB970 /* NowPlayingStylePreviewScreens.swift in Sources */ = {isa = PBXBuildFile; fileRef = F27A05589D788FC47B4394B1 /* NowPlayingStylePreviewScreens.swift */; }; + 678EB4A719AF3137D62735B1 /* PrimusePodcastSmartIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = D97CBB28235F105F24B3DEDB /* PrimusePodcastSmartIntents.swift */; }; 6792A3FA5C148C38B1A0336E /* QueueRowIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2BAE3560D34292CB5DB2E61 /* QueueRowIdentity.swift */; }; 67AD2125DA2834D6C40DE63D /* ListeningWidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 704D629527CC26A59E4AA639 /* ListeningWidgetSnapshot.swift */; }; 67AEEE1A153834ABE46FE36B /* PodcastSmartPlaylistStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = F48A908A854913A9BCAF15CB /* PodcastSmartPlaylistStore.swift */; }; @@ -1705,6 +1708,7 @@ 7CC510CFB7AE45C4AF720D0E /* ID3SynchronizedLyricsParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25F35F3F45A8184ACB596613 /* ID3SynchronizedLyricsParser.swift */; }; 7CCBBAC5687F575024E99733 /* TVStore+SleepTimer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D6DFB2A327EAB97BC58ADC8 /* TVStore+SleepTimer.swift */; }; 7D0832BD21EB9CCBD63E37FD /* ScanTLSTrustRetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 288A55230618464469979B71 /* ScanTLSTrustRetryPolicy.swift */; }; + 7D0A920A15915D655FC0C956 /* WatchSessionBridge+ListeningSpaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F29BD8E3D5DE15C5227270C /* WatchSessionBridge+ListeningSpaces.swift */; }; 7D0C759614CAB0E41E588E71 /* SleepTimerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D95C407321BB61F2AE5D951 /* SleepTimerSheet.swift */; }; 7D15AAD78D3B79FCA6E228D3 /* MusicLibrary+BoundedCollectionSongs.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9C9AE48EA362E6FF04D6A3D /* MusicLibrary+BoundedCollectionSongs.swift */; }; 7D8736FFAAE20B2823E60C34 /* PodcastLibraryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAA2748845933B33CC78DD5D /* PodcastLibraryPolicy.swift */; }; @@ -2107,6 +2111,7 @@ 9A71AD89902B836B881679B9 /* LyricsTimingRulerPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BF67FB805D219CB05569A7F /* LyricsTimingRulerPanel.swift */; }; 9AA975D697F427D30D97DD8E /* OnboardingGuidePages.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43B6CF7C99E84C479BDF4E07 /* OnboardingGuidePages.swift */; }; 9AC9936D841B3A6F4672E1DD /* AmbientSoundPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 235122E305AC082B17512648 /* AmbientSoundPolicy.swift */; }; + 9B01561F772307D199D93C48 /* WatchPlayerStore+ListeningSpaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46C33F08181B6DCCE7F699C5 /* WatchPlayerStore+ListeningSpaces.swift */; }; 9B0FF6C713B28745C9803FCC /* ArtistListView+Catalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2304CCF4FC3D27D9F5B62B /* ArtistListView+Catalog.swift */; }; 9B223B3B6785F1662108A483 /* ScraperSourceConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8945701E14DEF0FF55A668F /* ScraperSourceConfig.swift */; }; 9B2A49C180BA29D56A74D9CD /* QueueView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D2741FA5052447F5E1B27A4 /* QueueView.swift */; }; @@ -4433,6 +4438,7 @@ 468B591338AFB244373E6B36 /* SpokenWordCurrentBookCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenWordCurrentBookCache.swift; sourceTree = ""; }; 469C4286C25415EAE0219FA8 /* LibraryCatalogQueries.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryCatalogQueries.swift; sourceTree = ""; }; 46B4770726E29791F888A4D9 /* LifecycleSnapshotUploadCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifecycleSnapshotUploadCoordinator.swift; sourceTree = ""; }; + 46C33F08181B6DCCE7F699C5 /* WatchPlayerStore+ListeningSpaces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WatchPlayerStore+ListeningSpaces.swift"; sourceTree = ""; }; 46C5C019C73B5CFBA4CDA203 /* ru */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ru; path = ru.lproj/AudioCalibration.strings; sourceTree = ""; }; 46DC5D9C0CEEFCAB2641CA6C /* ImmersiveAlbumFlowRack.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImmersiveAlbumFlowRack.swift; sourceTree = ""; }; 46DD90C9F3AA2B20A38B6103 /* SongsPageTieOrderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SongsPageTieOrderTests.swift; sourceTree = ""; }; @@ -4996,6 +5002,7 @@ 7E6DA1E83197A47D0EF1A5B9 /* ShufflePreferencePolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShufflePreferencePolicy.swift; sourceTree = ""; }; 7EB55526D319838714D7C435 /* ListeningRecap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListeningRecap.swift; sourceTree = ""; }; 7F1A2B6733CA4871B9249585 /* CloudTokenRefreshPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudTokenRefreshPolicy.swift; sourceTree = ""; }; + 7F29BD8E3D5DE15C5227270C /* WatchSessionBridge+ListeningSpaces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WatchSessionBridge+ListeningSpaces.swift"; sourceTree = ""; }; 7F7C2378FE56B1D39121906B /* MetadataBackfillService+CatalogStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MetadataBackfillService+CatalogStatus.swift"; sourceTree = ""; }; 7F8400DFE2C41A6E11DFE290 /* MacLyricsVisibilityPreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacLyricsVisibilityPreferences.swift; sourceTree = ""; }; 7F86C6D958CA04391FE7C90F /* LibraryScale.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryScale.swift; sourceTree = ""; }; @@ -5804,6 +5811,7 @@ D912476C9E5410EBD7E8E619 /* HomeSpaceFilterBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSpaceFilterBar.swift; sourceTree = ""; }; D93AE5188C6309FF8F86DC80 /* DirectoryBrowserNavigationState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectoryBrowserNavigationState.swift; sourceTree = ""; }; D967C992538A3FB39D581F7A /* ExternalPlaylistFiles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalPlaylistFiles.swift; sourceTree = ""; }; + D97CBB28235F105F24B3DEDB /* PrimusePodcastSmartIntents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimusePodcastSmartIntents.swift; sourceTree = ""; }; D9CC779608BF4A84958AE7BA /* LyricsLiveActivityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyricsLiveActivityService.swift; sourceTree = ""; }; D9E592DD1CCF41B16100DA36 /* LocalLyricsTranslationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalLyricsTranslationService.swift; sourceTree = ""; }; D9F75A584A7C52C5D317FFBA /* RadioSubscription.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RadioSubscription.swift; sourceTree = ""; }; @@ -6550,6 +6558,7 @@ children = ( 1F3348B436BFF62FC99E649F /* WatchOfflinePlayer.swift */, 9FE14B295320AA20C02A9BB3 /* WatchPlayerStore.swift */, + 46C33F08181B6DCCE7F699C5 /* WatchPlayerStore+ListeningSpaces.swift */, ); path = Stores; sourceTree = ""; @@ -7181,6 +7190,7 @@ children = ( 1949B8417ED490628653C570 /* WatchFileTransferService.swift */, 1729792F7E0AC649901171B8 /* WatchSessionBridge.swift */, + 7F29BD8E3D5DE15C5227270C /* WatchSessionBridge+ListeningSpaces.swift */, ); path = Watch; sourceTree = ""; @@ -8094,6 +8104,7 @@ 4ECCDD80F05FA4A71FA0CB32 /* PrimuseAppIntents.swift */, 62D6E69627D9C8F06B3BC8AC /* PrimuseListeningAppIntents.swift */, 9709657B491DB695120A3B5C /* PrimuseListeningAppIntents+PodcastCatalog.swift */, + D97CBB28235F105F24B3DEDB /* PrimusePodcastSmartIntents.swift */, DC58680E103085AFD9B2E909 /* PrimuseRadioAppIntents.swift */, 465B35F98B45AB86C0B0080B /* PrimuseSettingsIntents.swift */, 76107490232E93C8F013BFE4 /* PrimuseSongAppIntents.swift */, @@ -10355,6 +10366,7 @@ 13634D89E919EBB65E6AA37A /* WatchOfflineLocalization.swift in Sources */, C9D20B390B8FBE049BC9ED3D /* WatchOfflineMedia.swift in Sources */, 18FAA957B504123DF596C3C9 /* WatchOfflinePlayer.swift in Sources */, + 9B01561F772307D199D93C48 /* WatchPlayerStore+ListeningSpaces.swift in Sources */, B4919DB98A38031DE3CB8C9E /* WatchPlayerStore.swift in Sources */, 669DEACD4680B40A4E738608 /* WatchSeekDialDrag.swift in Sources */, ); @@ -11962,6 +11974,7 @@ 792835F98B1AABE297CC5D22 /* PrimuseAppIntents.swift in Sources */, 969E2DA3B69C7A6BB08FDACB /* PrimuseListeningAppIntents+PodcastCatalog.swift in Sources */, 4E9B1239B522245AD24305D4 /* PrimuseListeningAppIntents.swift in Sources */, + 678EB4A719AF3137D62735B1 /* PrimusePodcastSmartIntents.swift in Sources */, EE6D78AE8A6BAC03DAEBF824 /* PrimuseRadioAppIntents.swift in Sources */, 5A5D5C6FBB0B1D5F481DCB96 /* PrimuseSettingsIntents.swift in Sources */, CC9810AB4FC4533D20BA3FCD /* PrimuseSongAppIntents.swift in Sources */, @@ -12177,6 +12190,7 @@ 7B26E8F040692D1549C7F486 /* VisualizerBarsView.swift in Sources */, FA3D0D432FDFD3CBEFF22BCC /* WatchFileTransferService.swift in Sources */, CA55B96EE25ACCD3CACD0D85 /* WatchOfflineLocalization.swift in Sources */, + 387F05C1C3BC004A1D49C57F /* WatchSessionBridge+ListeningSpaces.swift in Sources */, D8F2DE031EB6C1683C409E59 /* WatchSessionBridge.swift in Sources */, C2A580459ECE4BEDAEE0A928 /* WebDAVBrowserView.swift in Sources */, 462EB6494C4E9ECD2E2C6E97 /* WebDAVMultistatusParser.swift in Sources */, @@ -13193,6 +13207,7 @@ 448D9C545A04EA47EFC97B60 /* PrimuseAppIntents.swift in Sources */, E453669FFE336AFE0C43E156 /* PrimuseListeningAppIntents+PodcastCatalog.swift in Sources */, 77A1B66E6E6D1D8635C17190 /* PrimuseListeningAppIntents.swift in Sources */, + 3EAD1D6DBB36AD5FBDB404FC /* PrimusePodcastSmartIntents.swift in Sources */, F7146B96978777BFCFB56832 /* PrimuseRadioAppIntents.swift in Sources */, F9049DEBC46D78EB9137EB7D /* PrimuseSettingsIntents.swift in Sources */, 40705BE3DF7AC38D352AF350 /* PrimuseSongAppIntents.swift in Sources */, @@ -13409,6 +13424,7 @@ 89072781A9BD6098D66B57AC /* WatchFileTransferService.swift in Sources */, C990FCB0107093483DF9521D /* WatchOfflineLocalization.swift in Sources */, 19D71EE11967694ED835972F /* WatchOfflineMedia.swift in Sources */, + 7D0A920A15915D655FC0C956 /* WatchSessionBridge+ListeningSpaces.swift in Sources */, 7BA8162CFA252E94A19ADF03 /* WatchSessionBridge.swift in Sources */, 87FF2436F5492C7D7D1D1A26 /* WebDAVBrowserView.swift in Sources */, 1B537578523C58B637F9B820 /* WebDAVMultistatusParser.swift in Sources */, diff --git a/Primuse/Resources/ar.lproj/Localizable.strings b/Primuse/Resources/ar.lproj/Localizable.strings index 3235dada1..9b83a80e3 100644 --- a/Primuse/Resources/ar.lproj/Localizable.strings +++ b/Primuse/Resources/ar.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "البرامج ذات الأولوية"; "podcast_smart_priority_shows_footer" = "تظهر حلقات البرامج ذات الأولوية دائمًا في الأعلى بهذا الترتيب."; "podcast_smart_add_priority_show" = "إضافة برنامج ذي أولوية"; +"intent_podcast_smart_playlist_title" = "تشغيل قائمة بودكاست ذكية"; +"intent_podcast_smart_playlist_description" = "يشغّل قائمة بودكاست ذكية وفق الأولوية والتصفية والترتيب."; +"intent_podcast_smart_playlist_playing_format" = "جارٍ تشغيل القائمة الذكية %@."; +"intent_resume_podcast_queue_title" = "استئناف قائمة البودكاست"; +"intent_resume_podcast_queue_description" = "يستأنف قائمة البودكاست المحفوظة قبل الانتقال إلى الموسيقى أو الراديو."; +"intent_resume_podcast_queue_empty" = "لا توجد قائمة بودكاست محفوظة للاستئناف."; +"intent_resume_podcast_queue_playing_format" = "جارٍ استئناف قائمة البودكاست بدءًا من %@."; +"intent_toggle_voice_boost_title" = "تبديل تعزيز الصوت"; +"intent_toggle_voice_boost_description" = "يشغّل أو يوقف تعزيز الصوت للبودكاست أو الكتاب الصوتي أو الراديو الحالي."; +"intent_listening_nothing_playing" = "لا يوجد شيء قيد التشغيل الآن."; +"intent_voice_boost_unavailable" = "تعزيز الصوت غير متاح لهذا البث."; +"intent_voice_boost_enabled" = "تم تشغيل تعزيز الصوت."; +"intent_voice_boost_disabled" = "تم إيقاف تعزيز الصوت."; +"intent_cycle_smart_speed_title" = "تبديل مستوى السرعة الذكية"; +"intent_cycle_smart_speed_description" = "يبدّل شدة السرعة الذكية للبودكاست أو الكتاب الصوتي الحالي."; +"intent_smart_speed_unavailable" = "السرعة الذكية متاحة فقط أثناء تشغيل بودكاست أو كتاب صوتي."; +"intent_smart_speed_set_format" = "تم ضبط السرعة الذكية على %@."; +"intent_add_bookmark_title" = "إضافة إشارة صوتية"; +"intent_add_bookmark_description" = "يحفظ إشارة مرجعية عند موضع التشغيل الحالي للبودكاست أو الكتاب الصوتي."; +"intent_bookmark_unavailable" = "شغّل بودكاست أو كتابًا صوتيًا أولًا لإضافة إشارة."; diff --git a/Primuse/Resources/de.lproj/Localizable.strings b/Primuse/Resources/de.lproj/Localizable.strings index a9aa461f7..296e04054 100644 --- a/Primuse/Resources/de.lproj/Localizable.strings +++ b/Primuse/Resources/de.lproj/Localizable.strings @@ -8491,3 +8491,23 @@ "podcast_smart_priority_shows" = "Priorisierte Shows"; "podcast_smart_priority_shows_footer" = "Folgen priorisierter Shows erscheinen in dieser Reihenfolge immer ganz oben."; "podcast_smart_add_priority_show" = "Priorisierte Show hinzufügen"; +"intent_podcast_smart_playlist_title" = "Intelligente Podcast-Playlist abspielen"; +"intent_podcast_smart_playlist_description" = "Spielt eine intelligente Podcast-Playlist nach Priorität, Filter und Sortierung ab."; +"intent_podcast_smart_playlist_playing_format" = "Intelligente Podcast-Playlist „%@“ wird abgespielt."; +"intent_resume_podcast_queue_title" = "Podcast-Warteschlange fortsetzen"; +"intent_resume_podcast_queue_description" = "Setzt die vor dem Wechsel zu Musik oder Radio gemerkte Podcast-Warteschlange fort."; +"intent_resume_podcast_queue_empty" = "Es gibt keine gemerkte Podcast-Warteschlange."; +"intent_resume_podcast_queue_playing_format" = "Podcast-Warteschlange wird mit „%@“ fortgesetzt."; +"intent_toggle_voice_boost_title" = "Stimmverstärkung umschalten"; +"intent_toggle_voice_boost_description" = "Schaltet die Stimmverstärkung für aktuellen Podcast, Hörbuch oder Radiosender um."; +"intent_listening_nothing_playing" = "Derzeit wird nichts abgespielt."; +"intent_voice_boost_unavailable" = "Stimmverstärkung ist für diesen Stream nicht verfügbar."; +"intent_voice_boost_enabled" = "Stimmverstärkung aktiviert."; +"intent_voice_boost_disabled" = "Stimmverstärkung deaktiviert."; +"intent_cycle_smart_speed_title" = "Smart Speed umschalten"; +"intent_cycle_smart_speed_description" = "Wechselt die Smart-Speed-Stufe für aktuellen Podcast oder Hörbuch."; +"intent_smart_speed_unavailable" = "Smart Speed ist nur bei Podcasts oder Hörbüchern verfügbar."; +"intent_smart_speed_set_format" = "Smart Speed auf %@ gestellt."; +"intent_add_bookmark_title" = "Hör-Lesezeichen hinzufügen"; +"intent_add_bookmark_description" = "Speichert ein Lesezeichen an der aktuellen Stelle von Podcast oder Hörbuch."; +"intent_bookmark_unavailable" = "Spiele zuerst einen Podcast oder ein Hörbuch ab."; diff --git a/Primuse/Resources/en.lproj/Localizable.strings b/Primuse/Resources/en.lproj/Localizable.strings index 2798155f0..de103bcb0 100644 --- a/Primuse/Resources/en.lproj/Localizable.strings +++ b/Primuse/Resources/en.lproj/Localizable.strings @@ -8253,3 +8253,23 @@ "podcast_smart_priority_shows" = "Priority Shows"; "podcast_smart_priority_shows_footer" = "Episodes from priority shows always appear at the top of this playlist in the order listed."; "podcast_smart_add_priority_show" = "Add Priority Show"; +"intent_podcast_smart_playlist_title" = "Play Podcast Smart Playlist"; +"intent_podcast_smart_playlist_description" = "Plays a custom podcast smart playlist using its priority shows, filter, and sort order."; +"intent_podcast_smart_playlist_playing_format" = "Playing podcast smart playlist %@."; +"intent_resume_podcast_queue_title" = "Resume Podcast Queue"; +"intent_resume_podcast_queue_description" = "Resumes the podcast Up Next queue remembered before switching to music or radio."; +"intent_resume_podcast_queue_empty" = "There is no saved podcast queue to resume."; +"intent_resume_podcast_queue_playing_format" = "Resuming your podcast queue with %@."; +"intent_toggle_voice_boost_title" = "Toggle Voice Boost"; +"intent_toggle_voice_boost_description" = "Turns Voice Boost on or off for the current podcast, audiobook, or live radio station."; +"intent_listening_nothing_playing" = "Nothing is playing right now."; +"intent_voice_boost_unavailable" = "Voice Boost is not available for this stream."; +"intent_voice_boost_enabled" = "Voice Boost turned on."; +"intent_voice_boost_disabled" = "Voice Boost turned off."; +"intent_cycle_smart_speed_title" = "Cycle Smart Speed"; +"intent_cycle_smart_speed_description" = "Cycles Smart Speed intensity for the current podcast or audiobook."; +"intent_smart_speed_unavailable" = "Smart Speed is only available while playing a podcast or audiobook."; +"intent_smart_speed_set_format" = "Smart Speed set to %@."; +"intent_add_bookmark_title" = "Add Spoken-Word Bookmark"; +"intent_add_bookmark_description" = "Saves a bookmark at the current playback position of the playing podcast or audiobook."; +"intent_bookmark_unavailable" = "Play a podcast or audiobook first to add a bookmark."; diff --git a/Primuse/Resources/es-MX.lproj/Localizable.strings b/Primuse/Resources/es-MX.lproj/Localizable.strings index aa7c44884..06f999aea 100644 --- a/Primuse/Resources/es-MX.lproj/Localizable.strings +++ b/Primuse/Resources/es-MX.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "Programas prioritarios"; "podcast_smart_priority_shows_footer" = "Los episodios de los programas prioritarios siempre aparecen primero en este orden."; "podcast_smart_add_priority_show" = "Agregar programa prioritario"; +"intent_podcast_smart_playlist_title" = "Reproducir lista inteligente de podcasts"; +"intent_podcast_smart_playlist_description" = "Reproduce una lista inteligente de podcasts según prioridad, filtro y orden."; +"intent_podcast_smart_playlist_playing_format" = "Reproduciendo la lista inteligente %@."; +"intent_resume_podcast_queue_title" = "Reanudar cola de podcasts"; +"intent_resume_podcast_queue_description" = "Reanuda la cola de podcasts guardada antes de cambiar a música o radio."; +"intent_resume_podcast_queue_empty" = "No hay una cola de podcasts guardada para reanudar."; +"intent_resume_podcast_queue_playing_format" = "Reanudando tu cola de podcasts con %@."; +"intent_toggle_voice_boost_title" = "Alternar realce de voz"; +"intent_toggle_voice_boost_description" = "Activa o desactiva el realce de voz para el podcast, audiolibro o radio actual."; +"intent_listening_nothing_playing" = "No se está reproduciendo nada ahora."; +"intent_voice_boost_unavailable" = "El realce de voz no está disponible para esta transmisión."; +"intent_voice_boost_enabled" = "Realce de voz activado."; +"intent_voice_boost_disabled" = "Realce de voz desactivado."; +"intent_cycle_smart_speed_title" = "Cambiar velocidad inteligente"; +"intent_cycle_smart_speed_description" = "Alterna los niveles de velocidad inteligente del podcast o audiolibro actual."; +"intent_smart_speed_unavailable" = "La velocidad inteligente solo está disponible en podcasts y audiolibros."; +"intent_smart_speed_set_format" = "Velocidad inteligente ajustada a %@."; +"intent_add_bookmark_title" = "Agregar marcador de audio"; +"intent_add_bookmark_description" = "Guarda un marcador en la posición actual del podcast o audiolibro."; +"intent_bookmark_unavailable" = "Reproduce primero un podcast o audiolibro para agregar un marcador."; diff --git a/Primuse/Resources/fr.lproj/Localizable.strings b/Primuse/Resources/fr.lproj/Localizable.strings index 300350681..3d8843840 100644 --- a/Primuse/Resources/fr.lproj/Localizable.strings +++ b/Primuse/Resources/fr.lproj/Localizable.strings @@ -8491,3 +8491,23 @@ "podcast_smart_priority_shows" = "Émissions prioritaires"; "podcast_smart_priority_shows_footer" = "Les épisodes des émissions prioritaires apparaissent toujours en haut dans cet ordre."; "podcast_smart_add_priority_show" = "Ajouter une émission prioritaire"; +"intent_podcast_smart_playlist_title" = "Lire une liste intelligente de podcasts"; +"intent_podcast_smart_playlist_description" = "Lit une liste intelligente selon ses émissions prioritaires, filtres et tri."; +"intent_podcast_smart_playlist_playing_format" = "Lecture de la liste intelligente %@."; +"intent_resume_podcast_queue_title" = "Reprendre la file de podcasts"; +"intent_resume_podcast_queue_description" = "Reprend la file de podcasts mémorisée avant de passer à la musique ou la radio."; +"intent_resume_podcast_queue_empty" = "Aucune file de podcasts mémorisée à reprendre."; +"intent_resume_podcast_queue_playing_format" = "Reprise de la file de podcasts avec %@."; +"intent_toggle_voice_boost_title" = "Basculer l’amplification vocale"; +"intent_toggle_voice_boost_description" = "Active ou désactive l’amplification vocale pour le podcast, livre audio ou radio en cours."; +"intent_listening_nothing_playing" = "Aucune lecture en cours."; +"intent_voice_boost_unavailable" = "L’amplification vocale n’est pas disponible pour ce flux."; +"intent_voice_boost_enabled" = "Amplification vocale activée."; +"intent_voice_boost_disabled" = "Amplification vocale désactivée."; +"intent_cycle_smart_speed_title" = "Changer la vitesse intelligente"; +"intent_cycle_smart_speed_description" = "Fait défiler les niveaux de vitesse intelligente du podcast ou livre audio en cours."; +"intent_smart_speed_unavailable" = "La vitesse intelligente n’est disponible que pour les podcasts et livres audio."; +"intent_smart_speed_set_format" = "Vitesse intelligente réglée sur %@."; +"intent_add_bookmark_title" = "Ajouter un signet audio"; +"intent_add_bookmark_description" = "Enregistre un signet à la position actuelle du podcast ou livre audio."; +"intent_bookmark_unavailable" = "Lancez d’abord un podcast ou un livre audio pour ajouter un signet."; diff --git a/Primuse/Resources/hi.lproj/Localizable.strings b/Primuse/Resources/hi.lproj/Localizable.strings index a6cea1fee..9f96db666 100644 --- a/Primuse/Resources/hi.lproj/Localizable.strings +++ b/Primuse/Resources/hi.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "प्राथमिकता वाले शो"; "podcast_smart_priority_shows_footer" = "प्राथमिकता वाले शो के एपिसोड इस क्रम में हमेशा सबसे ऊपर रहेंगे।"; "podcast_smart_add_priority_show" = "प्राथमिकता शो जोड़ें"; +"intent_podcast_smart_playlist_title" = "पॉडकास्ट स्मार्ट प्लेलिस्ट चलाएँ"; +"intent_podcast_smart_playlist_description" = "प्राथमिकता, फ़िल्टर और क्रम के अनुसार कस्टम पॉडकास्ट स्मार्ट प्लेलिस्ट चलाता है।"; +"intent_podcast_smart_playlist_playing_format" = "स्मार्ट प्लेलिस्ट %@ चल रही है।"; +"intent_resume_podcast_queue_title" = "पॉडकास्ट कतार फिर शुरू करें"; +"intent_resume_podcast_queue_description" = "संगीत या रेडियो पर जाने से पहले सहेजी गई पॉडकास्ट कतार फिर शुरू करता है।"; +"intent_resume_podcast_queue_empty" = "फिर शुरू करने के लिए कोई सहेजी गई पॉडकास्ट कतार नहीं है।"; +"intent_resume_podcast_queue_playing_format" = "%@ के साथ पॉडकास्ट कतार फिर शुरू हो रही है।"; +"intent_toggle_voice_boost_title" = "वॉइस बूस्ट टॉगल करें"; +"intent_toggle_voice_boost_description" = "वर्तमान पॉडकास्ट, ऑडियोबुक या लाइव रेडियो के लिए वॉइस बूस्ट चालू या बंद करता है।"; +"intent_listening_nothing_playing" = "अभी कुछ भी नहीं चल रहा है।"; +"intent_voice_boost_unavailable" = "इस स्ट्रीम के लिए वॉइस बूस्ट उपलब्ध नहीं है।"; +"intent_voice_boost_enabled" = "वॉइस बूस्ट चालू किया गया।"; +"intent_voice_boost_disabled" = "वॉइस बूस्ट बंद किया गया।"; +"intent_cycle_smart_speed_title" = "स्मार्ट स्पीड स्तर बदलें"; +"intent_cycle_smart_speed_description" = "वर्तमान पॉडकास्ट या ऑडियोबुक की स्मार्ट स्पीड तीव्रता बदलता है।"; +"intent_smart_speed_unavailable" = "स्मार्ट स्पीड केवल पॉडकास्ट या ऑडियोबुक के दौरान उपलब्ध है।"; +"intent_smart_speed_set_format" = "स्मार्ट स्पीड %@ पर सेट की गई।"; +"intent_add_bookmark_title" = "ऑडियो बुकमार्क जोड़ें"; +"intent_add_bookmark_description" = "चल रहे पॉडकास्ट या ऑडियोबुक की वर्तमान स्थिति पर बुकमार्क सहेजता है।"; +"intent_bookmark_unavailable" = "बुकमार्क जोड़ने के लिए पहले पॉडकास्ट या ऑडियोबुक चलाएँ।"; diff --git a/Primuse/Resources/ja.lproj/Localizable.strings b/Primuse/Resources/ja.lproj/Localizable.strings index c11adeda7..5cbf5cbbb 100644 --- a/Primuse/Resources/ja.lproj/Localizable.strings +++ b/Primuse/Resources/ja.lproj/Localizable.strings @@ -8492,3 +8492,23 @@ "podcast_smart_priority_shows" = "優先番組"; "podcast_smart_priority_shows_footer" = "優先番組のエピソードは常にこの順序でプレイリストの先頭に表示されます。"; "podcast_smart_add_priority_show" = "優先番組を追加"; +"intent_podcast_smart_playlist_title" = "ポッドキャストのスマートプレイリストを再生"; +"intent_podcast_smart_playlist_description" = "優先番組やルールに従ってカスタムスマートプレイリストを再生します。"; +"intent_podcast_smart_playlist_playing_format" = "スマートプレイリスト「%@」を再生します。"; +"intent_resume_podcast_queue_title" = "ポッドキャストキューを再開"; +"intent_resume_podcast_queue_description" = "音楽やラジオへ切り替える前のポッドキャストキューを再開します。"; +"intent_resume_podcast_queue_empty" = "再開できるポッドキャストキューはありません。"; +"intent_resume_podcast_queue_playing_format" = "「%@」からポッドキャストキューを再開します。"; +"intent_toggle_voice_boost_title" = "ボイスブーストを切り替え"; +"intent_toggle_voice_boost_description" = "再生中のポッドキャスト、オーディオブック、ラジオのボイスブーストを切り替えます。"; +"intent_listening_nothing_playing" = "現在再生中の項目はありません。"; +"intent_voice_boost_unavailable" = "このストリームではボイスブーストを利用できません。"; +"intent_voice_boost_enabled" = "ボイスブーストをオンにしました。"; +"intent_voice_boost_disabled" = "ボイスブーストをオフにしました。"; +"intent_cycle_smart_speed_title" = "スマートスピードを切り替え"; +"intent_cycle_smart_speed_description" = "再生中のポッドキャストやオーディオブックのスマートスピード強度を切り替えます。"; +"intent_smart_speed_unavailable" = "スマートスピードはポッドキャストまたはオーディオブック再生中のみ利用できます。"; +"intent_smart_speed_set_format" = "スマートスピードを%@に設定しました。"; +"intent_add_bookmark_title" = "ブックマークを追加"; +"intent_add_bookmark_description" = "再生中のポッドキャストやオーディオブックの現在位置にブックマークを保存します。"; +"intent_bookmark_unavailable" = "ブックマークを追加するにはポッドキャストまたはオーディオブックを再生してください。"; diff --git a/Primuse/Resources/ko.lproj/Localizable.strings b/Primuse/Resources/ko.lproj/Localizable.strings index 93cc87582..824a9ad39 100644 --- a/Primuse/Resources/ko.lproj/Localizable.strings +++ b/Primuse/Resources/ko.lproj/Localizable.strings @@ -8491,3 +8491,23 @@ "podcast_smart_priority_shows" = "우선 프로그램"; "podcast_smart_priority_shows_footer" = "우선 프로그램의 에피소드는 여기에 나열된 순서대로 항상 맨 위에 배치됩니다."; "podcast_smart_add_priority_show" = "우선 프로그램 추가"; +"intent_podcast_smart_playlist_title" = "팟캐스트 스마트 재생목록 재생"; +"intent_podcast_smart_playlist_description" = "우선 프로그램, 필터 및 정렬 규칙에 따라 팟캐스트 스마트 재생목록을 재생합니다."; +"intent_podcast_smart_playlist_playing_format" = "팟캐스트 스마트 재생목록 %@을(를) 재생합니다."; +"intent_resume_podcast_queue_title" = "팟캐스트 대기열 재개"; +"intent_resume_podcast_queue_description" = "음악이나 라디오로 전환하기 전에 기억해 둔 팟캐스트 대기열을 재개합니다."; +"intent_resume_podcast_queue_empty" = "재개할 저장된 팟캐스트 대기열이 없습니다."; +"intent_resume_podcast_queue_playing_format" = "%@부터 팟캐스트 대기열을 재개합니다."; +"intent_toggle_voice_boost_title" = "음성 부스트 전환"; +"intent_toggle_voice_boost_description" = "현재 팟캐스트, 오디오북 또는 라이브 라디오의 음성 부스트를 켜거나 끕니다."; +"intent_listening_nothing_playing" = "현재 재생 중인 항목이 없습니다."; +"intent_voice_boost_unavailable" = "이 스트림에서는 음성 부스트를 사용할 수 없습니다."; +"intent_voice_boost_enabled" = "음성 부스트를 켰습니다."; +"intent_voice_boost_disabled" = "음성 부스트를 껐습니다."; +"intent_cycle_smart_speed_title" = "스마트 속도 단계 전환"; +"intent_cycle_smart_speed_description" = "현재 팟캐스트나 오디오북의 스마트 속도 강도를 순환 전환합니다."; +"intent_smart_speed_unavailable" = "스마트 속도는 팟캐스트 또는 오디오북 재생 중에만 사용할 수 있습니다."; +"intent_smart_speed_set_format" = "스마트 속도를 %@(으)로 설정했습니다."; +"intent_add_bookmark_title" = "오디오 북마크 추가"; +"intent_add_bookmark_description" = "재생 중인 팟캐스트 또는 오디오북의 현재 위치에 북마크를 저장합니다."; +"intent_bookmark_unavailable" = "북마크를 추가하려면 먼저 팟캐스트나 오디오북을 재생하세요."; diff --git a/Primuse/Resources/pl.lproj/Localizable.strings b/Primuse/Resources/pl.lproj/Localizable.strings index 9d7889cce..921b33a80 100644 --- a/Primuse/Resources/pl.lproj/Localizable.strings +++ b/Primuse/Resources/pl.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "Audycje priorytetowe"; "podcast_smart_priority_shows_footer" = "Odcinki audycji priorytetowych zawsze pojawiają się na górze w tej kolejności."; "podcast_smart_add_priority_show" = "Dodaj audycję priorytetową"; +"intent_podcast_smart_playlist_title" = "Odtwórz inteligentną listę podcastów"; +"intent_podcast_smart_playlist_description" = "Odtwarza inteligentną listę podcastów według priorytetu, filtra i sortowania."; +"intent_podcast_smart_playlist_playing_format" = "Odtwarzanie inteligentnej listy %@."; +"intent_resume_podcast_queue_title" = "Wznów kolejkę podcastów"; +"intent_resume_podcast_queue_description" = "Wznawia kolejkę podcastów zapamiętaną przed przełączeniem na muzykę lub radio."; +"intent_resume_podcast_queue_empty" = "Brak zapisanej kolejki podcastów do wznowienia."; +"intent_resume_podcast_queue_playing_format" = "Wznawianie kolejki podcastów od %@."; +"intent_toggle_voice_boost_title" = "Przełącz wzmocnienie głosu"; +"intent_toggle_voice_boost_description" = "Włącza lub wyłącza wzmocnienie głosu dla bieżącego podcastu, audiobooka lub radia."; +"intent_listening_nothing_playing" = "Obecnie nic nie jest odtwarzane."; +"intent_voice_boost_unavailable" = "Wzmocnienie głosu nie jest dostępne dla tego strumienia."; +"intent_voice_boost_enabled" = "Wzmocnienie głosu włączone."; +"intent_voice_boost_disabled" = "Wzmocnienie głosu wyłączone."; +"intent_cycle_smart_speed_title" = "Przełącz inteligentną prędkość"; +"intent_cycle_smart_speed_description" = "Przełącza poziomy inteligentnej prędkości dla bieżącego podcastu lub audiobooka."; +"intent_smart_speed_unavailable" = "Inteligentna prędkość jest dostępna tylko dla podcastów i audiobooków."; +"intent_smart_speed_set_format" = "Inteligentna prędkość ustawiona na %@."; +"intent_add_bookmark_title" = "Dodaj zakładkę audio"; +"intent_add_bookmark_description" = "Zapisuje zakładkę w bieżącym miejscu odtwarzanego podcastu lub audiobooka."; +"intent_bookmark_unavailable" = "Najpierw odtwórz podcast lub audiobook, aby dodać zakładkę."; diff --git a/Primuse/Resources/pt-BR.lproj/Localizable.strings b/Primuse/Resources/pt-BR.lproj/Localizable.strings index c7ff55adb..6919e39b4 100644 --- a/Primuse/Resources/pt-BR.lproj/Localizable.strings +++ b/Primuse/Resources/pt-BR.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "Programas prioritários"; "podcast_smart_priority_shows_footer" = "Episódios de programas prioritários aparecem sempre no topo nesta ordem."; "podcast_smart_add_priority_show" = "Adicionar programa prioritário"; +"intent_podcast_smart_playlist_title" = "Tocar playlist inteligente de podcasts"; +"intent_podcast_smart_playlist_description" = "Toca uma playlist inteligente de podcasts usando prioridade, filtro e ordem."; +"intent_podcast_smart_playlist_playing_format" = "Tocando a playlist inteligente %@."; +"intent_resume_podcast_queue_title" = "Retomar fila de podcasts"; +"intent_resume_podcast_queue_description" = "Retoma a fila de podcasts salva antes de mudar para música ou rádio."; +"intent_resume_podcast_queue_empty" = "Não há fila de podcasts salva para retomar."; +"intent_resume_podcast_queue_playing_format" = "Retomando sua fila de podcasts com %@."; +"intent_toggle_voice_boost_title" = "Alternar realce de voz"; +"intent_toggle_voice_boost_description" = "Ativa ou desativa o realce de voz para o podcast, audiolivro ou rádio atual."; +"intent_listening_nothing_playing" = "Nada está tocando no momento."; +"intent_voice_boost_unavailable" = "O realce de voz não está disponível para esta transmissão."; +"intent_voice_boost_enabled" = "Realce de voz ativado."; +"intent_voice_boost_disabled" = "Realce de voz desativado."; +"intent_cycle_smart_speed_title" = "Alternar velocidade inteligente"; +"intent_cycle_smart_speed_description" = "Alterna a intensidade da velocidade inteligente do podcast ou audiolivro atual."; +"intent_smart_speed_unavailable" = "A velocidade inteligente só está disponível em podcasts e audiolivros."; +"intent_smart_speed_set_format" = "Velocidade inteligente definida para %@."; +"intent_add_bookmark_title" = "Adicionar marcador de áudio"; +"intent_add_bookmark_description" = "Salva um marcador na posição atual do podcast ou audiolivro."; +"intent_bookmark_unavailable" = "Toque primeiro um podcast ou audiolivro para adicionar um marcador."; diff --git a/Primuse/Resources/ru.lproj/Localizable.strings b/Primuse/Resources/ru.lproj/Localizable.strings index 1a1757925..085d857ce 100644 --- a/Primuse/Resources/ru.lproj/Localizable.strings +++ b/Primuse/Resources/ru.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "Приоритетные шоу"; "podcast_smart_priority_shows_footer" = "Выпуски приоритетных шоу всегда отображаются вверху в указанном порядке."; "podcast_smart_add_priority_show" = "Добавить приоритетное шоу"; +"intent_podcast_smart_playlist_title" = "Включить умный плейлист подкастов"; +"intent_podcast_smart_playlist_description" = "Воспроизводит умный плейлист подкастов с учётом приоритета, фильтра и сортировки."; +"intent_podcast_smart_playlist_playing_format" = "Воспроизводится умный плейлист «%@»."; +"intent_resume_podcast_queue_title" = "Возобновить очередь подкастов"; +"intent_resume_podcast_queue_description" = "Возобновляет очередь подкастов, сохранённую перед переключением на музыку или радио."; +"intent_resume_podcast_queue_empty" = "Нет сохранённой очереди подкастов."; +"intent_resume_podcast_queue_playing_format" = "Возобновляем очередь подкастов с выпуска «%@»."; +"intent_toggle_voice_boost_title" = "Переключить усиление голоса"; +"intent_toggle_voice_boost_description" = "Включает или выключает усиление голоса для подкаста, аудиокниги или радио."; +"intent_listening_nothing_playing" = "Сейчас ничего не воспроизводится."; +"intent_voice_boost_unavailable" = "Усиление голоса недоступно для этого потока."; +"intent_voice_boost_enabled" = "Усиление голоса включено."; +"intent_voice_boost_disabled" = "Усиление голоса выключено."; +"intent_cycle_smart_speed_title" = "Переключить умную скорость"; +"intent_cycle_smart_speed_description" = "Переключает уровни умной скорости для подкаста или аудиокниги."; +"intent_smart_speed_unavailable" = "Умная скорость доступна только для подкастов и аудиокниг."; +"intent_smart_speed_set_format" = "Умная скорость: %@."; +"intent_add_bookmark_title" = "Добавить аудиозакладку"; +"intent_add_bookmark_description" = "Сохраняет закладку на текущей позиции подкаста или аудиокниги."; +"intent_bookmark_unavailable" = "Сначала включите подкаст или аудиокнигу."; diff --git a/Primuse/Resources/th.lproj/Localizable.strings b/Primuse/Resources/th.lproj/Localizable.strings index 3a117eae9..43e77a24a 100644 --- a/Primuse/Resources/th.lproj/Localizable.strings +++ b/Primuse/Resources/th.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "รายการสำคัญลำดับแรก"; "podcast_smart_priority_shows_footer" = "ตอนจากรายการสำคัญจะอยู่ด้านบนสุดของเพลย์ลิสต์ตามลำดับนี้เสมอ"; "podcast_smart_add_priority_show" = "เพิ่มรายการสำคัญ"; +"intent_podcast_smart_playlist_title" = "เล่นเพลย์ลิสต์อัจฉริยะของพอดแคสต์"; +"intent_podcast_smart_playlist_description" = "เล่นเพลย์ลิสต์อัจฉริยะตามลำดับความสำคัญ ตัวกรอง และการเรียงลำดับ"; +"intent_podcast_smart_playlist_playing_format" = "กำลังเล่นเพลย์ลิสต์อัจฉริยะ %@"; +"intent_resume_podcast_queue_title" = "เล่นคิวพอดแคสต์ต่อ"; +"intent_resume_podcast_queue_description" = "กลับมาเล่นคิวพอดแคสต์ที่จำไว้ก่อนสลับไปฟังเพลงหรือวิทยุ"; +"intent_resume_podcast_queue_empty" = "ไม่มีคิวพอดแคสต์ที่บันทึกไว้ให้เล่นต่อ"; +"intent_resume_podcast_queue_playing_format" = "กำลังเล่นคิวพอดแคสต์ต่อจาก %@"; +"intent_toggle_voice_boost_title" = "สลับการเร่งเสียงพูด"; +"intent_toggle_voice_boost_description" = "เปิดหรือปิดการเร่งเสียงพูดสำหรับพอดแคสต์ หนังสือเสียง หรือวิทยุสดที่กำลังเล่น"; +"intent_listening_nothing_playing" = "ไม่มีรายการที่กำลังเล่นอยู่ในขณะนี้"; +"intent_voice_boost_unavailable" = "สตรีมนี้ไม่รองรับการเร่งเสียงพูด"; +"intent_voice_boost_enabled" = "เปิดการเร่งเสียงพูดแล้ว"; +"intent_voice_boost_disabled" = "ปิดการเร่งเสียงพูดแล้ว"; +"intent_cycle_smart_speed_title" = "เปลี่ยนระดับความเร็วอัจฉริยะ"; +"intent_cycle_smart_speed_description" = "สลับระดับความเร็วอัจฉริยะสำหรับพอดแคสต์หรือหนังสือเสียงที่กำลังเล่น"; +"intent_smart_speed_unavailable" = "ความเร็วอัจฉริยะใช้ได้เฉพาะขณะเล่นพอดแคสต์หรือหนังสือเสียง"; +"intent_smart_speed_set_format" = "ตั้งค่าความเร็วอัจฉริยะเป็น %@"; +"intent_add_bookmark_title" = "เพิ่มบุ๊กมาร์กเสียง"; +"intent_add_bookmark_description" = "บันทึกบุ๊กมาร์กที่ตำแหน่งปัจจุบันของพอดแคสต์หรือหนังสือเสียง"; +"intent_bookmark_unavailable" = "กรุณาเล่นพอดแคสต์หรือหนังสือเสียงก่อนเพิ่มบุ๊กมาร์ก"; diff --git a/Primuse/Resources/tr.lproj/Localizable.strings b/Primuse/Resources/tr.lproj/Localizable.strings index 153b820ac..b6e9ae8a1 100644 --- a/Primuse/Resources/tr.lproj/Localizable.strings +++ b/Primuse/Resources/tr.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "Öncelikli Programlar"; "podcast_smart_priority_shows_footer" = "Öncelikli programların bölümleri her zaman bu sırayla en üstte yer alır."; "podcast_smart_add_priority_show" = "Öncelikli Program Ekle"; +"intent_podcast_smart_playlist_title" = "Akıllı Podcast Listesini Çal"; +"intent_podcast_smart_playlist_description" = "Öncelik, filtre ve sıralama kurallarına göre akıllı podcast listesini çalar."; +"intent_podcast_smart_playlist_playing_format" = "%@ akıllı podcast listesi çalınıyor."; +"intent_resume_podcast_queue_title" = "Podcast Sırasını Sürdür"; +"intent_resume_podcast_queue_description" = "Müzik veya radyoya geçmeden önce kaydedilen podcast sırasını sürdürür."; +"intent_resume_podcast_queue_empty" = "Sürdürülecek kayıtlı podcast sırası yok."; +"intent_resume_podcast_queue_playing_format" = "Podcast sırası %@ ile sürdürülüyor."; +"intent_toggle_voice_boost_title" = "Ses Güçlendirmeyi Değiştir"; +"intent_toggle_voice_boost_description" = "Geçerli podcast, sesli kitap veya canlı radyo için Ses Güçlendirmeyi açar veya kapatır."; +"intent_listening_nothing_playing" = "Şu anda çalan bir şey yok."; +"intent_voice_boost_unavailable" = "Bu yayın için Ses Güçlendirme kullanılamıyor."; +"intent_voice_boost_enabled" = "Ses Güçlendirme açıldı."; +"intent_voice_boost_disabled" = "Ses Güçlendirme kapatıldı."; +"intent_cycle_smart_speed_title" = "Akıllı Hız Seviyesini Değiştir"; +"intent_cycle_smart_speed_description" = "Geçerli podcast veya sesli kitap için Akıllı Hız seviyeleri arasında geçiş yapar."; +"intent_smart_speed_unavailable" = "Akıllı Hız yalnızca podcast veya sesli kitap çalarken kullanılabilir."; +"intent_smart_speed_set_format" = "Akıllı Hız %@ olarak ayarlandı."; +"intent_add_bookmark_title" = "Sesli Yer İmi Ekle"; +"intent_add_bookmark_description" = "Çalan podcast veya sesli kitabın geçerli konumuna yer imi ekler."; +"intent_bookmark_unavailable" = "Yer imi eklemek için önce bir podcast veya sesli kitap çalın."; diff --git a/Primuse/Resources/uk.lproj/Localizable.strings b/Primuse/Resources/uk.lproj/Localizable.strings index a0726a113..67386206d 100644 --- a/Primuse/Resources/uk.lproj/Localizable.strings +++ b/Primuse/Resources/uk.lproj/Localizable.strings @@ -8397,3 +8397,23 @@ "podcast_smart_priority_shows" = "Пріоритетні шоу"; "podcast_smart_priority_shows_footer" = "Випуски пріоритетних шоу завжди будуть на початку у вказаному порядку."; "podcast_smart_add_priority_show" = "Додати пріоритетне шоу"; +"intent_podcast_smart_playlist_title" = "Увімкнути розумний список подкастів"; +"intent_podcast_smart_playlist_description" = "Відтворює розумний список подкастів за пріоритетом, фільтром і сортуванням."; +"intent_podcast_smart_playlist_playing_format" = "Відтворюється розумний список «%@»."; +"intent_resume_podcast_queue_title" = "Відновити чергу подкастів"; +"intent_resume_podcast_queue_description" = "Відновлює чергу подкастів, збережену перед перемиканням на музику або радіо."; +"intent_resume_podcast_queue_empty" = "Немає збереженої черги подкастів."; +"intent_resume_podcast_queue_playing_format" = "Відновлюємо чергу подкастів із «%@»."; +"intent_toggle_voice_boost_title" = "Перемкнути підсилення голосу"; +"intent_toggle_voice_boost_description" = "Вмикає або вимикає підсилення голосу для подкасту, аудіокниги чи радіо."; +"intent_listening_nothing_playing" = "Зараз нічого не відтворюється."; +"intent_voice_boost_unavailable" = "Підсилення голосу недоступне для цього потоку."; +"intent_voice_boost_enabled" = "Підсилення голосу увімкнено."; +"intent_voice_boost_disabled" = "Підсилення голосу вимкнено."; +"intent_cycle_smart_speed_title" = "Перемкнути розумну швидкість"; +"intent_cycle_smart_speed_description" = "Перемикає рівні розумної швидкості для подкасту чи аудіокниги."; +"intent_smart_speed_unavailable" = "Розумна швидкість доступна лише для подкастів та аудіокниг."; +"intent_smart_speed_set_format" = "Розумна швидкість: %@."; +"intent_add_bookmark_title" = "Додати аудіозакладку"; +"intent_add_bookmark_description" = "Зберігає закладку на поточній позиції подкасту чи аудіокниги."; +"intent_bookmark_unavailable" = "Спочатку увімкніть подкаст або аудіокнигу."; diff --git a/Primuse/Resources/zh-Hans.lproj/Localizable.strings b/Primuse/Resources/zh-Hans.lproj/Localizable.strings index 09fe0ec56..35f7736eb 100644 --- a/Primuse/Resources/zh-Hans.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hans.lproj/Localizable.strings @@ -8584,3 +8584,23 @@ "podcast_smart_priority_shows" = "优先置顶节目"; "podcast_smart_priority_shows_footer" = "优先节目的单集将按此处顺序始终排在智能列表最前面。"; "podcast_smart_add_priority_show" = "添加优先节目"; +"intent_podcast_smart_playlist_title" = "播放播客智能列表"; +"intent_podcast_smart_playlist_description" = "按自定义播客智能列表的优先节目、筛选与排序规则排队播放。"; +"intent_podcast_smart_playlist_playing_format" = "正在播放播客智能列表「%@」。"; +"intent_resume_podcast_queue_title" = "恢复播客队列"; +"intent_resume_podcast_queue_description" = "恢复切去听音乐或电台前记住的播客待播队列。"; +"intent_resume_podcast_queue_empty" = "当前没有可恢复的播客队列。"; +"intent_resume_podcast_queue_playing_format" = "正在恢复播客队列,从「%@」继续播放。"; +"intent_toggle_voice_boost_title" = "切换人声增强"; +"intent_toggle_voice_boost_description" = "开启或关闭当前播客、有声书或直播电台的人声增强。"; +"intent_listening_nothing_playing" = "当前没有正在播放的内容。"; +"intent_voice_boost_unavailable" = "当前音频流不支持人声增强。"; +"intent_voice_boost_enabled" = "已开启人声增强。"; +"intent_voice_boost_disabled" = "已关闭人声增强。"; +"intent_cycle_smart_speed_title" = "切换智能速度档位"; +"intent_cycle_smart_speed_description" = "在关闭、轻柔、标准、强力之间循环切换当前有声内容的智能速度。"; +"intent_smart_speed_unavailable" = "仅在播放播客或有声书时可调整智能速度。"; +"intent_smart_speed_set_format" = "智能速度已设为%@。"; +"intent_add_bookmark_title" = "添加有声书签"; +"intent_add_bookmark_description" = "在当前播放的播客或有声书位置保存一条书签。"; +"intent_bookmark_unavailable" = "请先播放播客或有声书再添加书签。"; diff --git a/Primuse/Resources/zh-Hant.lproj/Localizable.strings b/Primuse/Resources/zh-Hant.lproj/Localizable.strings index 18d9b2886..8d46bad3b 100644 --- a/Primuse/Resources/zh-Hant.lproj/Localizable.strings +++ b/Primuse/Resources/zh-Hant.lproj/Localizable.strings @@ -8468,3 +8468,23 @@ "podcast_smart_priority_shows" = "優先置頂節目"; "podcast_smart_priority_shows_footer" = "優先節目的單集將依此處順序始終排在智慧列表最前面。"; "podcast_smart_add_priority_show" = "加入優先節目"; +"intent_podcast_smart_playlist_title" = "播放 Podcast 智慧列表"; +"intent_podcast_smart_playlist_description" = "依自訂 Podcast 智慧列表的優先節目、篩選與排序規則排隊播放。"; +"intent_podcast_smart_playlist_playing_format" = "正在播放 Podcast 智慧列表「%@」。"; +"intent_resume_podcast_queue_title" = "恢復 Podcast 佇列"; +"intent_resume_podcast_queue_description" = "恢復切去聽音樂或電台前記住的 Podcast 待播佇列。"; +"intent_resume_podcast_queue_empty" = "目前沒有可恢復的 Podcast 佇列。"; +"intent_resume_podcast_queue_playing_format" = "正在恢復 Podcast 佇列,從「%@」繼續播放。"; +"intent_toggle_voice_boost_title" = "切換人聲增強"; +"intent_toggle_voice_boost_description" = "開啟或關閉目前 Podcast、有聲書或直播電台的人聲增強。"; +"intent_listening_nothing_playing" = "目前沒有正在播放的內容。"; +"intent_voice_boost_unavailable" = "目前音訊串流不支援人聲增強。"; +"intent_voice_boost_enabled" = "已開啟人聲增強。"; +"intent_voice_boost_disabled" = "已關閉人聲增強。"; +"intent_cycle_smart_speed_title" = "切換智慧速度檔位"; +"intent_cycle_smart_speed_description" = "在關閉、輕柔、標準、強力之間循環切換目前有聲內容的智慧速度。"; +"intent_smart_speed_unavailable" = "僅在播放 Podcast 或有聲書時可調整智慧速度。"; +"intent_smart_speed_set_format" = "智慧速度已設為%@。"; +"intent_add_bookmark_title" = "加入有聲書籤"; +"intent_add_bookmark_description" = "在目前播放的 Podcast 或有聲書位置儲存一筆書籤。"; +"intent_bookmark_unavailable" = "請先播放 Podcast 或有聲書再加入書籤。"; diff --git a/Primuse/Services/Intents/PrimusePodcastSmartIntents.swift b/Primuse/Services/Intents/PrimusePodcastSmartIntents.swift new file mode 100644 index 000000000..b18b39bc1 --- /dev/null +++ b/Primuse/Services/Intents/PrimusePodcastSmartIntents.swift @@ -0,0 +1,165 @@ +import AppIntents +import Foundation +import PrimuseKit + +// MARK: - Podcast Smart Playlists + +struct PrimusePodcastSmartPlaylistEntity: AppEntity, Identifiable, Hashable { + static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "podcast_smart_playlists_title") + static let defaultQuery = PrimusePodcastSmartPlaylistQuery() + + let id: String + let name: String + let symbol: String + + init(_ playlist: PodcastSmartPlaylist) { + id = playlist.id + name = playlist.name + symbol = playlist.symbol + } + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation( + title: "\(name)", + image: .init(systemName: symbol) + ) + } +} + +struct PrimusePodcastSmartPlaylistQuery: EntityStringQuery { + @MainActor + func entities(for identifiers: [String]) async throws -> [PrimusePodcastSmartPlaylistEntity] { + let byID = Dictionary( + PodcastSmartPlaylistStore.shared.playlists.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } + ) + return identifiers.compactMap { byID[$0].map(PrimusePodcastSmartPlaylistEntity.init) } + } + + @MainActor + func entities(matching string: String) async throws -> [PrimusePodcastSmartPlaylistEntity] { + let query = string.trimmingCharacters(in: .whitespacesAndNewlines) + let playlists = PodcastSmartPlaylistStore.shared.playlists + guard !query.isEmpty else { return playlists.map(PrimusePodcastSmartPlaylistEntity.init) } + return playlists + .filter { $0.name.localizedCaseInsensitiveContains(query) } + .map(PrimusePodcastSmartPlaylistEntity.init) + } + + @MainActor + func suggestedEntities() async throws -> [PrimusePodcastSmartPlaylistEntity] { + PodcastSmartPlaylistStore.shared.playlists.map(PrimusePodcastSmartPlaylistEntity.init) + } +} + +/// 播放指定播客智能列表(按列表内设定的优先置顶与筛选排序规则自动排队播放)。 +struct PrimusePlayPodcastSmartPlaylistIntent: AudioPlaybackIntent { + static let title: LocalizedStringResource = "intent_podcast_smart_playlist_title" + static let description = IntentDescription("intent_podcast_smart_playlist_description") + + @Parameter(title: "podcast_smart_playlists_title") + var playlist: PrimusePodcastSmartPlaylistEntity + + init() {} + + @MainActor + func perform() async throws -> some IntentResult & ProvidesDialog { + let store = PodcastStore.shared + store.loadIfNeeded() + guard let resolved = PodcastSmartPlaylistStore.shared.playlist(id: playlist.id) else { + return .result(dialog: IntentDialog("smart_playlist_unavailable")) + } + let episodes = PodcastSmartPlaylistStore.shared.episodes(for: resolved, in: store) + guard let first = episodes.first else { + return .result(dialog: IntentDialog("podcast_no_matching_episodes")) + } + let continuing = Array(episodes.dropFirst().prefix(50)) + await AppServices.shared.playerService.playPodcast(first, continuing: continuing) + let message = String(format: String(localized: "intent_podcast_smart_playlist_playing_format"), resolved.name) + return .result(dialog: IntentDialog(LocalizedStringResource(stringLiteral: message))) + } +} + +/// 恢复跨空间离开播客时记住的 Up Next 队列(适合操作按钮与 CarPlay 自动化)。 +struct PrimuseResumePodcastQueueIntent: AudioPlaybackIntent { + static let title: LocalizedStringResource = "intent_resume_podcast_queue_title" + static let description = IntentDescription("intent_resume_podcast_queue_description") + + init() {} + + @MainActor + func perform() async throws -> some IntentResult & ProvidesDialog { + let player = AppServices.shared.playerService + guard let summary = player.rememberedPodcastQueueSummary, + await player.resumeRememberedPodcastQueue() else { + return .result(dialog: IntentDialog("intent_resume_podcast_queue_empty")) + } + let message = String(format: String(localized: "intent_resume_podcast_queue_playing_format"), summary.lead.title) + return .result(dialog: IntentDialog(LocalizedStringResource(stringLiteral: message))) + } +} + +// MARK: - Spoken Word & Radio Audio Effects / Bookmarks + +/// 切换当前播客、有声书或直播电台的人声增强(复用按项覆盖策略)。 +struct PrimuseToggleVoiceBoostIntent: AppIntent { + static let title: LocalizedStringResource = "intent_toggle_voice_boost_title" + static let description = IntentDescription("intent_toggle_voice_boost_description") + + init() {} + + @MainActor + func perform() async throws -> some IntentResult & ProvidesDialog { + let player = AppServices.shared.playerService + guard player.currentSong != nil else { + return .result(dialog: IntentDialog("intent_listening_nothing_playing")) + } + if player.isLiveRadio, !player.canToggleCurrentRadioVoiceBoost { + return .result(dialog: IntentDialog("intent_voice_boost_unavailable")) + } + player.toggleVoiceBoostForCurrentItem() + let key = player.currentEffectiveVoiceBoostEnabled + ? "intent_voice_boost_enabled" + : "intent_voice_boost_disabled" + return .result(dialog: IntentDialog(LocalizedStringResource(stringLiteral: String(localized: String.LocalizationValue(key))))) + } +} + +/// 单键循环切换当前播客或有声书的智能速度强度(关 → 轻柔 → 标准 → 强力 → 关)。 +struct PrimuseCycleSmartSpeedIntent: AppIntent { + static let title: LocalizedStringResource = "intent_cycle_smart_speed_title" + static let description = IntentDescription("intent_cycle_smart_speed_description") + + init() {} + + @MainActor + func perform() async throws -> some IntentResult & ProvidesDialog { + let player = AppServices.shared.playerService + guard player.currentItemIsSpokenWord, !player.isLiveRadio else { + return .result(dialog: IntentDialog("intent_smart_speed_unavailable")) + } + let next = player.cycleSmartSpeedLevelForCurrentItem() + let levelTitle = NSLocalizedString(next.titleKey, comment: "") + let message = String(format: String(localized: "intent_smart_speed_set_format"), levelTitle) + return .result(dialog: IntentDialog(LocalizedStringResource(stringLiteral: message))) + } +} + +/// 在当前播客或有声书播放位置添加书签(适合操作按钮或 Siri 语音记录金句)。 +struct PrimuseAddSpokenWordBookmarkIntent: AppIntent { + static let title: LocalizedStringResource = "intent_add_bookmark_title" + static let description = IntentDescription("intent_add_bookmark_description") + + init() {} + + @MainActor + func perform() async throws -> some IntentResult & ProvidesDialog { + let player = AppServices.shared.playerService + guard player.currentItemIsSpokenWord, !player.isLiveRadio else { + return .result(dialog: IntentDialog("intent_bookmark_unavailable")) + } + let added = player.addSpokenWordBookmark() + let text = String(localized: added ? "transcript_reader_bookmark_added" : "transcript_reader_bookmark_exists") + return .result(dialog: IntentDialog(LocalizedStringResource(stringLiteral: text))) + } +} diff --git a/Primuse/Services/Watch/WatchSessionBridge+ListeningSpaces.swift b/Primuse/Services/Watch/WatchSessionBridge+ListeningSpaces.swift new file mode 100644 index 000000000..946ae7119 --- /dev/null +++ b/Primuse/Services/Watch/WatchSessionBridge+ListeningSpaces.swift @@ -0,0 +1,136 @@ +#if os(iOS) +import Foundation +import PrimuseKit + +/// Sendable 命令载体 ── 把 WCSession 来的 `[String: Any]` 在 nonisolated +/// 上下文里立刻拆出标量字段。Swift 6 严格并发不允许跨 actor 传 Any。 +struct WatchCommand: Sendable { + let command: String + let time: Double? + let songID: String? + let liked: Bool? + let mode: String? + + init(_ message: [String: Any]) { + command = message["command"] as? String ?? "" + time = message["time"] as? Double + songID = message["songID"] as? String + liked = message["liked"] as? Bool + mode = message["mode"] as? String + } +} + +/// iPhone 现在把声音放到哪: kind 给手表挑图标, name 是系统给的设备名。 +struct WatchOutputRoute: Equatable { + let name: String + let kind: String +} + +/// 推给手表的附加状态, 跟着每条状态消息一起走。旧版手表不认这些键, 照常显示。 +struct WatchStateExtras: Equatable { + var canLike = false + var isLiked = false + var offersPlaybackModes = false + var playbackMode = PlaybackOrderMode.sequential.rawValue + var allowsShuffle = false + var skipBackwardSeconds = 0 + var skipForwardSeconds = 0 + var skipBackwardSymbol = "" + var skipForwardSymbol = "" + var canSwitchStation = false + var hasLyrics = false + var nextLyric = "" + var outputName = "" + var outputKind = "" + var playbackRate = 1.0 + var volumeChangedAt: TimeInterval = 0 + var canToggleVoiceBoost = false + var voiceBoostEnabled = false + var canCycleSmartSpeed = false + var smartSpeedLevel = SmartSpeedLevel.off.rawValue + var canCyclePlaybackRate = false + var canAddBookmark = false + + var withoutTransientFields: Self { + var copy = self + copy.nextLyric = "" + copy.volumeChangedAt = 0 + return copy + } + + var payload: [String: Any] { + [ + "canLike": canLike, + "isLiked": isLiked, + "offersPlaybackModes": offersPlaybackModes, + "playbackMode": playbackMode, + "allowsShuffle": allowsShuffle, + "skipBackwardSeconds": skipBackwardSeconds, + "skipForwardSeconds": skipForwardSeconds, + "skipBackwardSymbol": skipBackwardSymbol, + "skipForwardSymbol": skipForwardSymbol, + "canSwitchStation": canSwitchStation, + "hasLyrics": hasLyrics, + "nextLyric": nextLyric, + "outputName": outputName, + "outputKind": outputKind, + "playbackRate": playbackRate, + "volumeChangedAt": volumeChangedAt, + "canToggleVoiceBoost": canToggleVoiceBoost, + "voiceBoostEnabled": voiceBoostEnabled, + "canCycleSmartSpeed": canCycleSmartSpeed, + "smartSpeedLevel": smartSpeedLevel, + "canCyclePlaybackRate": canCyclePlaybackRate, + "canAddBookmark": canAddBookmark, + ] + } +} + +extension WatchSessionBridge { + /// 填充手表的跨空间有声与电台控制状态(人声增强、智能速度档位、语速循环、一键书签)。 + func populateListeningSpaceExtras(_ extras: inout WatchStateExtras, player: AudioPlayerService) { + if player.isLiveRadio { + extras.canToggleVoiceBoost = player.canToggleCurrentRadioVoiceBoost + extras.voiceBoostEnabled = player.currentEffectiveVoiceBoostEnabled + return + } + guard player.currentItemIsSpokenWord else { return } + extras.canToggleVoiceBoost = true + extras.voiceBoostEnabled = player.currentEffectiveVoiceBoostEnabled + extras.canCycleSmartSpeed = !player.isSystemAudioPlaybackActive + extras.smartSpeedLevel = player.currentEffectiveSmartSpeedLevel.rawValue + extras.canCyclePlaybackRate = true + extras.canAddBookmark = true + } + + /// 处理手表发来的跨空间有声/电台控制命令;命中返回 true。 + func handleListeningSpaceCommand(_ command: String, player: AudioPlayerService) -> Bool { + switch command { + case "toggleVoiceBoost": + if player.isLiveRadio { + guard player.canToggleCurrentRadioVoiceBoost else { return true } + } else { + guard player.currentItemIsSpokenWord else { return true } + } + player.toggleVoiceBoostForCurrentItem() + return true + case "cycleSmartSpeed": + guard player.currentItemIsSpokenWord, !player.isLiveRadio else { return true } + _ = player.cycleSmartSpeedLevelForCurrentItem() + return true + case "cyclePlaybackRate": + guard player.currentItemIsSpokenWord, !player.isLiveRadio else { return true } + player.setSpokenWordRateForCurrentBook( + SpokenWordPlaybackRatePolicy.cycledPreset(after: player.currentSpokenWordRate) + ) + return true + case "addBookmark": + guard player.currentItemIsSpokenWord, !player.isLiveRadio else { return true } + _ = player.addSpokenWordBookmark() + return true + default: + return false + } + } +} +#endif diff --git a/Primuse/Services/Watch/WatchSessionBridge.swift b/Primuse/Services/Watch/WatchSessionBridge.swift index 16dc81306..8f59d6560 100644 --- a/Primuse/Services/Watch/WatchSessionBridge.swift +++ b/Primuse/Services/Watch/WatchSessionBridge.swift @@ -558,6 +558,7 @@ final class WatchSessionBridge: NSObject { extras.volumeChangedAt = lastVolumeChangeSignal?.timeIntervalSince1970 ?? 0 guard let player, let song else { return extras } extras.canSwitchStation = player.canSwitchRadioStation + populateListeningSpaceExtras(&extras, player: player) guard !player.isLiveRadio else { return extras } // 倍速播放时手表按这个速度往前推进度, 表盘进度圈也按它算哪一刻放完。 // 走系统播放器时倍速不生效 (会先退回 PCM 引擎), 按 1 倍报。 @@ -768,78 +769,6 @@ final class WatchSessionBridge: NSObject { nonisolated private static let watchCoverPixelSize = 240 } -/// Sendable 命令载体 ── 把 WCSession 来的 `[String: Any]` 在 nonisolated -/// 上下文里立刻拆出标量字段。Swift 6 严格并发不允许跨 actor 传 Any。 -struct WatchCommand: Sendable { - let command: String - let time: Double? - let songID: String? - let liked: Bool? - let mode: String? - - init(_ message: [String: Any]) { - command = message["command"] as? String ?? "" - time = message["time"] as? Double - songID = message["songID"] as? String - liked = message["liked"] as? Bool - mode = message["mode"] as? String - } -} - -/// iPhone 现在把声音放到哪: kind 给手表挑图标, name 是系统给的设备名。 -struct WatchOutputRoute: Equatable { - let name: String - let kind: String -} - -/// 推给手表的附加状态, 跟着每条状态消息一起走。旧版手表不认这些键, 照常显示。 -struct WatchStateExtras: Equatable { - var canLike = false - var isLiked = false - var offersPlaybackModes = false - var playbackMode = PlaybackOrderMode.sequential.rawValue - var allowsShuffle = false - var skipBackwardSeconds = 0 - var skipForwardSeconds = 0 - var skipBackwardSymbol = "" - var skipForwardSymbol = "" - var canSwitchStation = false - var hasLyrics = false - var nextLyric = "" - var outputName = "" - var outputKind = "" - var playbackRate = 1.0 - var volumeChangedAt: TimeInterval = 0 - - var withoutTransientFields: Self { - var copy = self - copy.nextLyric = "" - copy.volumeChangedAt = 0 - return copy - } - - var payload: [String: Any] { - [ - "canLike": canLike, - "isLiked": isLiked, - "offersPlaybackModes": offersPlaybackModes, - "playbackMode": playbackMode, - "allowsShuffle": allowsShuffle, - "skipBackwardSeconds": skipBackwardSeconds, - "skipForwardSeconds": skipForwardSeconds, - "skipBackwardSymbol": skipBackwardSymbol, - "skipForwardSymbol": skipForwardSymbol, - "canSwitchStation": canSwitchStation, - "hasLyrics": hasLyrics, - "nextLyric": nextLyric, - "outputName": outputName, - "outputKind": outputKind, - "playbackRate": playbackRate, - "volumeChangedAt": volumeChangedAt, - ] - } -} - // MARK: - WCSessionDelegate extension WatchSessionBridge: WCSessionDelegate { @@ -1026,8 +955,10 @@ extension WatchSessionBridge: WCSessionDelegate { pushLibraryDigest() } default: - plog("⌚️ unknown command: \(cmd.command)") - return + if !handleListeningSpaceCommand(cmd.command, player: player) { + plog("⌚️ unknown command: \(cmd.command)") + return + } } // 控制类指令处理后立刻强推一次最新状态 (含新 currentTime, 让 watch // 校准外推基准), 不等 0.5s tick。 diff --git a/PrimuseTests/ListeningSpacesReliabilityTests.swift b/PrimuseTests/ListeningSpacesReliabilityTests.swift index 2521e22fd..2cd3c490c 100644 --- a/PrimuseTests/ListeningSpacesReliabilityTests.swift +++ b/PrimuseTests/ListeningSpacesReliabilityTests.swift @@ -716,4 +716,84 @@ final class ListeningSpacesReliabilityTests: XCTestCase { player.toggleVoiceBoostForCurrentItem() XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) } + + func testWatchLocalizationAndPodcastSmartIntentsExecuteAgainstSharedServices() async throws { + XCTAssertEqual(WatchOfflineLocalization.string("ext.watch.voiceBoost", language: "zh-Hans"), "人声增强") + XCTAssertEqual(WatchOfflineLocalization.string("ext.watch.voiceBoost", language: "en"), "Voice Boost") + XCTAssertEqual(WatchOfflineLocalization.string("ext.watch.smartSpeed.strong", language: "ja"), "強") + XCTAssertEqual(WatchOfflineLocalization.string("ext.watch.bookmark.add", language: "en"), "Add Bookmark") + + let playlistID = "intent-pl-\(UUID().uuidString)" + let playlist = PodcastSmartPlaylist(id: playlistID, name: "Morning Briefing", symbol: "sun.max") + PodcastSmartPlaylistStore.shared.save(playlist) + cleanups.append { PodcastSmartPlaylistStore.shared.delete(id: playlistID) } + + let query = PrimusePodcastSmartPlaylistQuery() + let matched = try await query.entities(matching: "Briefing") + XCTAssertTrue(matched.contains { $0.id == playlistID }) + let byID = try await query.entities(for: [playlistID]) + XCTAssertEqual(byID.map(\.name), ["Morning Briefing"]) + + let player = AppServices.shared.playerService + let prevSong = player.currentSong + let prevKind = player.playbackKind + let prevSpoken = player.currentItemIsSpokenWord + let prevTime = player.currentTime + let prevVoice = player.playbackSettings.spokenWordVoiceBoostEnabled + let prevSmartEnabled = player.playbackSettings.spokenWordSmartSpeedEnabled + let prevSmartLevel = player.playbackSettings.spokenWordSmartSpeedLevel + + let bookSong = Song( + id: "intent-book-\(UUID().uuidString)", + title: "Intent Chapter", + artistName: "Author", + duration: 1_800, + fileFormat: .m4a, + filePath: "/books/intent.m4b", + sourceID: "local-books", + genre: "Audiobook" + ) + let bookScope = player.spokenWordBookID(for: bookSong) + cleanups.append { + player.currentSong = prevSong + player.playbackKind = prevKind + player.currentItemIsSpokenWord = prevSpoken + player.currentTime = prevTime + player.playbackSettings.spokenWordVoiceBoostEnabled = prevVoice + player.playbackSettings.spokenWordSmartSpeedEnabled = prevSmartEnabled + player.playbackSettings.spokenWordSmartSpeedLevel = prevSmartLevel + SpokenWordAudioEffectsPreferences.shared.clear(forScopeID: bookScope) + for bm in SpokenWordStore.shared.bookmarks(forSongID: bookSong.id) { + SpokenWordStore.shared.removeBookmark(id: bm.id, songID: bookSong.id) + } + } + + player.playbackKind = .track + player.currentSong = bookSong + player.handleSpokenWordItemChange(to: bookSong) + player.currentTime = 240 + player.playbackSettings.spokenWordVoiceBoostEnabled = false + player.setGlobalSmartSpeedLevel(.off) + + _ = try await PrimuseToggleVoiceBoostIntent().perform() + XCTAssertTrue(player.currentEffectiveVoiceBoostEnabled) + + _ = try await PrimuseCycleSmartSpeedIntent().perform() + XCTAssertEqual(player.currentEffectiveSmartSpeedLevel, .mild) + + _ = try await PrimuseAddSpokenWordBookmarkIntent().perform() + XCTAssertEqual(SpokenWordStore.shared.bookmarks(forSongID: bookSong.id).count, 1) + + #if os(iOS) + var extras = WatchStateExtras() + WatchSessionBridge.shared.populateListeningSpaceExtras(&extras, player: player) + XCTAssertTrue(extras.canToggleVoiceBoost) + XCTAssertTrue(extras.voiceBoostEnabled) + XCTAssertTrue(extras.canCyclePlaybackRate) + XCTAssertTrue(extras.canAddBookmark) + XCTAssertEqual(extras.payload["smartSpeedLevel"] as? String, SmartSpeedLevel.mild.rawValue) + XCTAssertTrue(WatchSessionBridge.shared.handleListeningSpaceCommand("toggleVoiceBoost", player: player)) + XCTAssertFalse(player.currentEffectiveVoiceBoostEnabled) + #endif + } } diff --git a/PrimuseWatch/Stores/WatchPlayerStore+ListeningSpaces.swift b/PrimuseWatch/Stores/WatchPlayerStore+ListeningSpaces.swift new file mode 100644 index 000000000..ed5e25d1c --- /dev/null +++ b/PrimuseWatch/Stores/WatchPlayerStore+ListeningSpaces.swift @@ -0,0 +1,173 @@ +import Foundation +import WatchKit + +/// Sendable 状态快照 ── 把 WCSession 传过来的 `[String: Any]` 在 nonisolated +/// 上下文里立刻解包成具体类型, 再跨 actor 投递。Swift 6 严格并发下 [String: +/// Any] 不是 Sendable, 直接捕获会编译报错。 +struct ContextSnapshot: Sendable { + let songID: String + let title: String + let artist: String + let album: String + let isPlaying: Bool + let isLoading: Bool + let isLiveStream: Bool + let duration: TimeInterval + let currentTime: TimeInterval + let currentTimeAnchor: TimeInterval + let queueCount: Int + let currentLyric: String + let accentR: Double + let accentG: Double + let accentB: Double + let canLike: Bool + let isLiked: Bool + let offersPlaybackModes: Bool + let playbackMode: String + let allowsShuffle: Bool + let skipBackwardSeconds: Int + let skipForwardSeconds: Int + let skipBackwardSymbol: String + let skipForwardSymbol: String + let canSwitchStation: Bool + let hasLyrics: Bool + let nextLyric: String + let outputName: String + let outputKind: String + let playbackRate: Double + let volumeChangedAt: TimeInterval + let canToggleVoiceBoost: Bool + let voiceBoostEnabled: Bool + let canCycleSmartSpeed: Bool + let smartSpeedLevel: String + let canCyclePlaybackRate: Bool + let canAddBookmark: Bool + + init(_ ctx: [String: Any]) { + songID = ctx["songID"] as? String ?? "" + title = ctx["title"] as? String ?? "" + artist = ctx["artist"] as? String ?? "" + album = ctx["album"] as? String ?? "" + isPlaying = ctx["isPlaying"] as? Bool ?? false + isLoading = ctx["isLoading"] as? Bool ?? false + isLiveStream = ctx["isLiveStream"] as? Bool ?? false + duration = ctx["duration"] as? Double ?? 0 + currentTime = ctx["currentTime"] as? Double ?? 0 + currentTimeAnchor = ctx["currentTimeAnchor"] as? Double ?? Date().timeIntervalSince1970 + queueCount = ctx["queueCount"] as? Int ?? 0 + currentLyric = ctx["currentLyric"] as? String ?? "" + accentR = ctx["accentR"] as? Double ?? 0.078 + accentG = ctx["accentG"] as? Double ?? 0.490 + accentB = ctx["accentB"] as? Double ?? 0.541 + // 以下是后加的键, 旧版 iPhone 不带时按「没有这项」处理。 + canLike = ctx["canLike"] as? Bool ?? false + isLiked = ctx["isLiked"] as? Bool ?? false + offersPlaybackModes = ctx["offersPlaybackModes"] as? Bool ?? false + playbackMode = ctx["playbackMode"] as? String ?? "" + allowsShuffle = ctx["allowsShuffle"] as? Bool ?? false + skipBackwardSeconds = ctx["skipBackwardSeconds"] as? Int ?? 0 + skipForwardSeconds = ctx["skipForwardSeconds"] as? Int ?? 0 + skipBackwardSymbol = ctx["skipBackwardSymbol"] as? String ?? "" + skipForwardSymbol = ctx["skipForwardSymbol"] as? String ?? "" + canSwitchStation = ctx["canSwitchStation"] as? Bool ?? false + // 旧版 iPhone 不报这项: 有当前行就当作有歌词。 + hasLyrics = ctx["hasLyrics"] as? Bool ?? !currentLyric.isEmpty + nextLyric = ctx["nextLyric"] as? String ?? "" + outputName = ctx["outputName"] as? String ?? "" + outputKind = ctx["outputKind"] as? String ?? "" + let rate = ctx["playbackRate"] as? Double ?? 1 + playbackRate = rate.isFinite && rate > 0 ? rate : 1 + volumeChangedAt = ctx["volumeChangedAt"] as? Double ?? 0 + canToggleVoiceBoost = ctx["canToggleVoiceBoost"] as? Bool ?? false + voiceBoostEnabled = ctx["voiceBoostEnabled"] as? Bool ?? false + canCycleSmartSpeed = ctx["canCycleSmartSpeed"] as? Bool ?? false + smartSpeedLevel = ctx["smartSpeedLevel"] as? String ?? "off" + canCyclePlaybackRate = ctx["canCyclePlaybackRate"] as? Bool ?? false + canAddBookmark = ctx["canAddBookmark"] as? Bool ?? false + } +} + +extension WatchPlayerStore { + var offersListeningSpaceControls: Bool { + !isOfflinePlayback && (canToggleVoiceBoost || canCycleSmartSpeed || canCyclePlaybackRate || canAddBookmark) + } + + var formattedPlaybackRate: String { + let rounded = (playbackRate * 100).rounded() / 100 + if abs(rounded - rounded.rounded()) < 0.005 { + return "\(Int(rounded.rounded()))×" + } + let tenths = (rounded * 10).rounded() / 10 + if abs(rounded - tenths) < 0.005 { + return String(format: "%.1f×", rounded) + } + return String(format: "%.2f×", rounded) + } + + var smartSpeedTitleKey: String { + switch smartSpeedLevel { + case "mild": return "ext.watch.smartSpeed.mild" + case "standard": return "ext.watch.smartSpeed.standard" + case "strong": return "ext.watch.smartSpeed.strong" + default: return "ext.watch.smartSpeed.off" + } + } + + var smartSpeedIsActive: Bool { + smartSpeedLevel == "mild" || smartSpeedLevel == "standard" || smartSpeedLevel == "strong" + } + + func toggleVoiceBoost() { + guard canToggleVoiceBoost, !isOfflinePlayback else { return } + guard canSendRealtimeCommand else { + requestCurrentState() + return + } + WKInterfaceDevice.current().play(.click) + let previous = voiceBoostEnabled + voiceBoostEnabled.toggle() + send(["command": "toggleVoiceBoost"]) { [weak self] in + self?.voiceBoostEnabled = previous + } + } + + func cycleSmartSpeed() { + guard canCycleSmartSpeed, !isOfflinePlayback else { return } + guard canSendRealtimeCommand else { + requestCurrentState() + return + } + WKInterfaceDevice.current().play(.click) + let previous = smartSpeedLevel + switch smartSpeedLevel { + case "off": smartSpeedLevel = "mild" + case "mild": smartSpeedLevel = "standard" + case "standard": smartSpeedLevel = "strong" + default: smartSpeedLevel = "off" + } + send(["command": "cycleSmartSpeed"]) { [weak self] in + self?.smartSpeedLevel = previous + } + } + + func cyclePlaybackRate() { + guard canCyclePlaybackRate, !isOfflinePlayback else { return } + guard canSendRealtimeCommand else { + requestCurrentState() + return + } + WKInterfaceDevice.current().play(.click) + send(["command": "cyclePlaybackRate"]) + } + + func addBookmark() { + guard canAddBookmark, !isOfflinePlayback else { return } + guard canSendRealtimeCommand else { + requestCurrentState() + return + } + WKInterfaceDevice.current().play(.success) + lastBookmarkAddedAt = Date() + send(["command": "addBookmark"]) + } +} diff --git a/PrimuseWatch/Stores/WatchPlayerStore.swift b/PrimuseWatch/Stores/WatchPlayerStore.swift index cd4209719..a7c21d92b 100644 --- a/PrimuseWatch/Stores/WatchPlayerStore.swift +++ b/PrimuseWatch/Stores/WatchPlayerStore.swift @@ -76,7 +76,14 @@ final class WatchPlayerStore: NSObject, WCSessionDelegate { private var sentTimeAnchor: TimeInterval = 0 private var sentCurrentTime: TimeInterval = 0 /// iPhone 那边的实际倍速 (有声书常开 1.5、2 倍), 外推进度按它走。 - private var playbackRate: Double = 1 + var playbackRate: Double = 1 + var canToggleVoiceBoost: Bool = false + var voiceBoostEnabled: Bool = false + var canCycleSmartSpeed: Bool = false + var smartSpeedLevel: String = "off" + var canCyclePlaybackRate: Bool = false + var canAddBookmark: Bool = false + var lastBookmarkAddedAt: Date = .distantPast /// 用户最近一次主动 toggle play/pause 的时刻。1 秒内收到 iPhone 推过来 /// 跟乐观值矛盾的 isPlaying 时暂不采纳 (大概率是命令到达 iPhone 之前 @@ -505,12 +512,12 @@ extension WatchPlayerStore { } - private var canSendRealtimeCommand: Bool { + var canSendRealtimeCommand: Bool { guard let session else { return false } return session.activationState == .activated && session.isReachable } - private func send( + func send( _ message: [String: Any], rollback: (@MainActor @Sendable () -> Void)? = nil ) { @@ -727,6 +734,9 @@ extension WatchPlayerStore { if !snap.skipForwardSymbol.isEmpty { skipForwardSymbol = snap.skipForwardSymbol } canSwitchStation = snap.canSwitchStation outputName = snap.outputName; outputKind = snap.outputKind; playbackRate = snap.playbackRate + canToggleVoiceBoost = snap.canToggleVoiceBoost; voiceBoostEnabled = snap.voiceBoostEnabled + canCycleSmartSpeed = snap.canCycleSmartSpeed; smartSpeedLevel = snap.smartSpeedLevel + canCyclePlaybackRate = snap.canCyclePlaybackRate; canAddBookmark = snap.canAddBookmark if snap.volumeChangedAt > lastVolumeChangedAt { lastVolumeChangedAt = snap.volumeChangedAt if abs(now.timeIntervalSince1970 - snap.volumeChangedAt) < 3 { volumeActivity &+= 1 } @@ -838,80 +848,6 @@ extension WatchPlayerStore { } } -/// Sendable 状态快照 ── 把 WCSession 传过来的 `[String: Any]` 在 nonisolated -/// 上下文里立刻解包成具体类型, 再跨 actor 投递。Swift 6 严格并发下 [String: -/// Any] 不是 Sendable, 直接捕获会编译报错。 -struct ContextSnapshot: Sendable { - let songID: String - let title: String - let artist: String - let album: String - let isPlaying: Bool - let isLoading: Bool - let isLiveStream: Bool - let duration: TimeInterval - let currentTime: TimeInterval - let currentTimeAnchor: TimeInterval - let queueCount: Int - let currentLyric: String - let accentR: Double - let accentG: Double - let accentB: Double - let canLike: Bool - let isLiked: Bool - let offersPlaybackModes: Bool - let playbackMode: String - let allowsShuffle: Bool - let skipBackwardSeconds: Int - let skipForwardSeconds: Int - let skipBackwardSymbol: String - let skipForwardSymbol: String - let canSwitchStation: Bool - let hasLyrics: Bool - let nextLyric: String - let outputName: String - let outputKind: String - let playbackRate: Double - let volumeChangedAt: TimeInterval - - init(_ ctx: [String: Any]) { - songID = ctx["songID"] as? String ?? "" - title = ctx["title"] as? String ?? "" - artist = ctx["artist"] as? String ?? "" - album = ctx["album"] as? String ?? "" - isPlaying = ctx["isPlaying"] as? Bool ?? false - isLoading = ctx["isLoading"] as? Bool ?? false - isLiveStream = ctx["isLiveStream"] as? Bool ?? false - duration = ctx["duration"] as? Double ?? 0 - currentTime = ctx["currentTime"] as? Double ?? 0 - currentTimeAnchor = ctx["currentTimeAnchor"] as? Double ?? Date().timeIntervalSince1970 - queueCount = ctx["queueCount"] as? Int ?? 0 - currentLyric = ctx["currentLyric"] as? String ?? "" - accentR = ctx["accentR"] as? Double ?? 0.078 - accentG = ctx["accentG"] as? Double ?? 0.490 - accentB = ctx["accentB"] as? Double ?? 0.541 - // 以下是后加的键, 旧版 iPhone 不带时按「没有这项」处理。 - canLike = ctx["canLike"] as? Bool ?? false - isLiked = ctx["isLiked"] as? Bool ?? false - offersPlaybackModes = ctx["offersPlaybackModes"] as? Bool ?? false - playbackMode = ctx["playbackMode"] as? String ?? "" - allowsShuffle = ctx["allowsShuffle"] as? Bool ?? false - skipBackwardSeconds = ctx["skipBackwardSeconds"] as? Int ?? 0 - skipForwardSeconds = ctx["skipForwardSeconds"] as? Int ?? 0 - skipBackwardSymbol = ctx["skipBackwardSymbol"] as? String ?? "" - skipForwardSymbol = ctx["skipForwardSymbol"] as? String ?? "" - canSwitchStation = ctx["canSwitchStation"] as? Bool ?? false - // 旧版 iPhone 不报这项: 有当前行就当作有歌词。 - hasLyrics = ctx["hasLyrics"] as? Bool ?? !currentLyric.isEmpty - nextLyric = ctx["nextLyric"] as? String ?? "" - outputName = ctx["outputName"] as? String ?? "" - outputKind = ctx["outputKind"] as? String ?? "" - let rate = ctx["playbackRate"] as? Double ?? 1 - playbackRate = rate.isFinite && rate > 0 ? rate : 1 - volumeChangedAt = ctx["volumeChangedAt"] as? Double ?? 0 - } -} - #if DEBUG extension WatchPlayerStore { /// 截图用的演示状态: PRIMUSE_WATCH_DEMO = music / lyrics / lyricsLong / audiobook / radio / offline / empty。 diff --git a/PrimuseWatch/Views/PlaybackOptionsWatchView.swift b/PrimuseWatch/Views/PlaybackOptionsWatchView.swift index 574a1a142..3aa3ece35 100644 --- a/PrimuseWatch/Views/PlaybackOptionsWatchView.swift +++ b/PrimuseWatch/Views/PlaybackOptionsWatchView.swift @@ -21,6 +21,22 @@ struct WatchPlaybackOptionsView: View { if store.offersPlaybackModes { playbackModeRow } + if store.offersListeningSpaceControls { + Section { + if store.canCyclePlaybackRate { + playbackRateRow + } + if store.canToggleVoiceBoost { + voiceBoostRow + } + if store.canCycleSmartSpeed { + smartSpeedRow + } + if store.canAddBookmark { + bookmarkRow + } + } + } if !store.isLiveStream, store.duration > 0 { Button(action: onShowSeek) { Label(WatchString("ext.watch.seek.title"), systemImage: "timeline.selection") @@ -71,6 +87,76 @@ struct WatchPlaybackOptionsView: View { .accessibilityValue(WatchString(store.playbackMode.titleKey)) } + private var playbackRateRow: some View { + Button { + store.cyclePlaybackRate() + } label: { + Label { + VStack(alignment: .leading, spacing: 1) { + Text(WatchString("ext.watch.playbackSpeed")) + Text(store.formattedPlaybackRate) + .font(.footnote.monospacedDigit()) + .foregroundStyle(store.accent) + } + } icon: { + Image(systemName: "speedometer") + .foregroundStyle(store.accent) + } + } + } + + private var voiceBoostRow: some View { + Button { + store.toggleVoiceBoost() + } label: { + Label { + VStack(alignment: .leading, spacing: 1) { + Text(WatchString("ext.watch.voiceBoost")) + Text(WatchString(store.voiceBoostEnabled ? "ext.watch.on" : "ext.watch.off")) + .font(.footnote) + .foregroundStyle(store.voiceBoostEnabled ? store.accent : Color.secondary) + } + } icon: { + Image(systemName: store.voiceBoostEnabled ? "waveform.circle.fill" : "waveform") + .foregroundStyle(store.voiceBoostEnabled ? store.accent : Color.secondary) + .contentTransition(.symbolEffect(.replace)) + } + } + } + + private var smartSpeedRow: some View { + Button { + store.cycleSmartSpeed() + } label: { + Label { + VStack(alignment: .leading, spacing: 1) { + Text(WatchString("ext.watch.smartSpeed")) + Text(WatchString(store.smartSpeedTitleKey)) + .font(.footnote) + .foregroundStyle(store.smartSpeedIsActive ? store.accent : Color.secondary) + } + } icon: { + Image(systemName: store.smartSpeedIsActive ? "gauge.with.dots.needle.67percent" : "gauge.with.dots.needle.0percent") + .foregroundStyle(store.smartSpeedIsActive ? store.accent : Color.secondary) + } + } + } + + private var bookmarkRow: some View { + let recentlyAdded = Date().timeIntervalSince(store.lastBookmarkAddedAt) < 2.5 + return Button { + store.addBookmark() + } label: { + Label { + Text(WatchString(recentlyAdded ? "ext.watch.bookmark.added" : "ext.watch.bookmark.add")) + } icon: { + Image(systemName: recentlyAdded ? "checkmark.circle.fill" : "bookmark.fill") + .foregroundStyle(store.accent) + .contentTransition(.symbolEffect(.replace)) + } + } + } + private var outputRow: some View { HStack(spacing: 10) { Image(systemName: store.outputSymbol) diff --git a/PrimuseWatchShared/WatchOfflineLocalization.swift b/PrimuseWatchShared/WatchOfflineLocalization.swift index a37ddfc98..46198f771 100644 --- a/PrimuseWatchShared/WatchOfflineLocalization.swift +++ b/PrimuseWatchShared/WatchOfflineLocalization.swift @@ -29,25 +29,36 @@ enum WatchOfflineLocalization { "watchPreparing", "watchQueued", "watchAwaitingReceipt", - "watchReceived" -] + "watchReceived", + "ext.watch.playbackSpeed", + "ext.watch.voiceBoost", + "ext.watch.smartSpeed", + "ext.watch.smartSpeed.off", + "ext.watch.smartSpeed.mild", + "ext.watch.smartSpeed.standard", + "ext.watch.smartSpeed.strong", + "ext.watch.bookmark.add", + "ext.watch.bookmark.added", + "ext.watch.on", + "ext.watch.off" + ] private static let translations: [String: [String]] = [ - "en": ["On Apple Watch", "Control iPhone", "Send music from the iPhone transfer page to listen offline.", "Artwork and lyrics", "Delete", "Cancel", "Unable to play this file.", "Unable to save or remove this file.", "Turn the Digital Crown to adjust Apple Watch audio volume.", "OK", "Save on your paired watch for offline playback", "Pair an Apple Watch and install Primuse on it", "Watch transfers", "Preparing for Apple Watch", "Queued for Apple Watch", "Waiting for watch confirmation", "Saved on Apple Watch"], - "zh-Hans": ["手表上的音乐", "控制 iPhone", "从 iPhone 的文件传输页发送音乐,即可离线播放。", "封面与歌词", "删除", "取消", "无法播放此文件。", "无法保存或删除此文件。", "转动数码表冠调节 Apple Watch 的播放音量。", "好", "保存到已配对的手表,供离线播放", "请先配对 Apple Watch 并安装 Primuse", "手表传输记录", "正在为手表准备文件", "已加入手表传输队列", "等待手表确认", "已保存到 Apple Watch"], - "zh-Hant": ["手錶上的音樂", "控制 iPhone", "從 iPhone 的檔案傳輸頁傳送音樂,即可離線播放。", "封面與歌詞", "刪除", "取消", "無法播放此檔案。", "無法儲存或刪除此檔案。", "轉動數位錶冠調整 Apple Watch 的播放音量。", "好", "儲存到已配對的手錶,供離線播放", "請先配對 Apple Watch 並安裝 Primuse", "手錶傳輸記錄", "正在為手錶準備檔案", "已加入手錶傳輸佇列", "等待手錶確認", "已儲存到 Apple Watch"], - "de": ["Auf der Apple Watch", "iPhone steuern", "Musik über die Dateiübertragung auf dem iPhone senden und offline hören.", "Cover und Liedtexte", "Löschen", "Abbrechen", "Diese Datei kann nicht abgespielt werden.", "Diese Datei konnte nicht gespeichert oder gelöscht werden.", "Mit der Digital Crown die Lautstärke der Apple Watch ändern.", "OK", "Auf der gekoppelten Watch zum Offlinehören speichern", "Apple Watch koppeln und Primuse darauf installieren", "Watch-Übertragungen", "Für Apple Watch vorbereiten", "Für Apple Watch eingereiht", "Bestätigung der Watch ausstehend", "Auf Apple Watch gespeichert"], - "fr": ["Sur Apple Watch", "Contrôler l’iPhone", "Envoyez de la musique depuis le transfert de fichiers de l’iPhone pour l’écouter hors ligne.", "Pochettes et paroles", "Supprimer", "Annuler", "Impossible de lire ce fichier.", "Impossible d’enregistrer ou de supprimer ce fichier.", "Tournez la Digital Crown pour régler le volume de l’Apple Watch.", "OK", "Enregistrer sur la montre jumelée pour écouter hors ligne", "Jumelez une Apple Watch et installez Primuse dessus", "Transferts Watch", "Préparation pour Apple Watch", "En attente d’envoi vers Apple Watch", "En attente de confirmation de la montre", "Enregistré sur Apple Watch"], - "ja": ["Apple Watch内の音楽", "iPhoneを操作", "iPhoneのファイル転送画面から音楽を送信するとオフラインで再生できます。", "アートワークと歌詞", "削除", "キャンセル", "このファイルを再生できません。", "このファイルを保存または削除できません。", "Digital CrownでApple Watchの音量を調整します。", "OK", "ペアリング済みのWatchに保存してオフライン再生", "Apple WatchをペアリングしてPrimuseをインストールしてください", "Watchへの転送", "Apple Watch用に準備中", "Apple Watchへの転送待ち", "Watchの確認待ち", "Apple Watchに保存済み"], - "ko": ["Apple Watch의 음악", "iPhone 제어", "iPhone의 파일 전송 화면에서 음악을 보내 오프라인으로 재생하세요.", "앨범 표지 및 가사", "삭제", "취소", "이 파일을 재생할 수 없습니다.", "이 파일을 저장하거나 삭제할 수 없습니다.", "Digital Crown을 돌려 Apple Watch 음량을 조절하세요.", "확인", "페어링된 시계에 저장하여 오프라인 재생", "Apple Watch를 페어링하고 Primuse를 설치하세요", "Watch 전송", "Apple Watch용 파일 준비 중", "Apple Watch 전송 대기 중", "시계 확인 대기 중", "Apple Watch에 저장됨"], - "es-MX": ["En Apple Watch", "Controlar iPhone", "Envía música desde la transferencia de archivos del iPhone para escuchar sin conexión.", "Portadas y letras", "Eliminar", "Cancelar", "No se puede reproducir este archivo.", "No se pudo guardar o eliminar este archivo.", "Gira la Digital Crown para ajustar el volumen del Apple Watch.", "Aceptar", "Guardar en el reloj enlazado para escuchar sin conexión", "Enlaza un Apple Watch e instala Primuse", "Transferencias al Watch", "Preparando para Apple Watch", "En cola para Apple Watch", "Esperando confirmación del reloj", "Guardado en Apple Watch"], - "pt-BR": ["No Apple Watch", "Controlar iPhone", "Envie músicas pela transferência de arquivos do iPhone para ouvir offline.", "Capas e letras", "Apagar", "Cancelar", "Não foi possível reproduzir este arquivo.", "Não foi possível salvar ou apagar este arquivo.", "Gire a Digital Crown para ajustar o volume do Apple Watch.", "OK", "Salvar no relógio emparelhado para ouvir offline", "Emparelhe um Apple Watch e instale o Primuse", "Transferências para Watch", "Preparando para Apple Watch", "Na fila para Apple Watch", "Aguardando confirmação do relógio", "Salvo no Apple Watch"], - "ru": ["На Apple Watch", "Управлять iPhone", "Отправьте музыку через передачу файлов на iPhone, чтобы слушать офлайн.", "Обложки и тексты", "Удалить", "Отмена", "Не удалось воспроизвести файл.", "Не удалось сохранить или удалить файл.", "Поверните Digital Crown для изменения громкости Apple Watch.", "ОК", "Сохранить на связанных часах для прослушивания офлайн", "Создайте пару с Apple Watch и установите Primuse", "Передачи на Watch", "Подготовка для Apple Watch", "В очереди на Apple Watch", "Ожидание подтверждения часов", "Сохранено на Apple Watch"], - "uk": ["На Apple Watch", "Керувати iPhone", "Надішліть музику через передавання файлів на iPhone, щоб слухати офлайн.", "Обкладинки й тексти", "Видалити", "Скасувати", "Не вдалося відтворити файл.", "Не вдалося зберегти або видалити файл.", "Поверніть Digital Crown, щоб змінити гучність Apple Watch.", "ОК", "Зберегти на спареному годиннику для прослуховування офлайн", "Спарте Apple Watch і встановіть Primuse", "Передавання на Watch", "Підготовка для Apple Watch", "У черзі на Apple Watch", "Очікування підтвердження годинника", "Збережено на Apple Watch"], - "ar": ["على Apple Watch", "التحكم في iPhone", "أرسل الموسيقى من صفحة نقل الملفات على iPhone للاستماع دون اتصال.", "الأغلفة وكلمات الأغاني", "حذف", "إلغاء", "تعذر تشغيل هذا الملف.", "تعذر حفظ هذا الملف أو حذفه.", "أدر التاج الرقمي لضبط مستوى صوت Apple Watch.", "موافق", "الحفظ على الساعة المقترنة للاستماع دون اتصال", "اقرن Apple Watch وثبّت Primuse عليها", "عمليات النقل إلى Watch", "جارٍ التحضير لـ Apple Watch", "في قائمة الانتظار لـ Apple Watch", "بانتظار تأكيد الساعة", "تم الحفظ على Apple Watch"], - "hi": ["Apple Watch पर", "iPhone नियंत्रित करें", "ऑफ़लाइन सुनने के लिए iPhone के फ़ाइल ट्रांसफ़र पेज से संगीत भेजें।", "कवर और गीत के बोल", "हटाएँ", "रद्द करें", "यह फ़ाइल चलाई नहीं जा सकी।", "यह फ़ाइल सहेजी या हटाई नहीं जा सकी।", "Apple Watch की आवाज़ बदलने के लिए Digital Crown घुमाएँ।", "ठीक है", "ऑफ़लाइन सुनने के लिए पेयर की गई वॉच पर सहेजें", "Apple Watch पेयर करें और उस पर Primuse इंस्टॉल करें", "Watch ट्रांसफ़र", "Apple Watch के लिए तैयारी जारी", "Apple Watch के लिए कतार में", "वॉच की पुष्टि का इंतज़ार", "Apple Watch पर सहेजा गया"], - "pl": ["Na Apple Watch", "Steruj iPhonem", "Wyślij muzykę ze strony przesyłania plików na iPhonie, aby słuchać offline.", "Okładki i teksty", "Usuń", "Anuluj", "Nie można odtworzyć tego pliku.", "Nie można zapisać lub usunąć tego pliku.", "Obróć Digital Crown, aby zmienić głośność Apple Watch.", "OK", "Zapisz na połączonym zegarku do słuchania offline", "Połącz Apple Watch i zainstaluj na nim Primuse", "Transfery do Watch", "Przygotowanie dla Apple Watch", "W kolejce do Apple Watch", "Oczekiwanie na potwierdzenie zegarka", "Zapisano na Apple Watch"], - "tr": ["Apple Watch’ta", "iPhone’u kontrol et", "Çevrimdışı dinlemek için iPhone’un dosya aktarımı sayfasından müzik gönderin.", "Kapaklar ve şarkı sözleri", "Sil", "İptal", "Bu dosya çalınamadı.", "Bu dosya kaydedilemedi veya silinemedi.", "Apple Watch sesini ayarlamak için Digital Crown’u çevirin.", "Tamam", "Çevrimdışı dinlemek için eşlenmiş saate kaydet", "Apple Watch’u eşleyin ve Primuse’u yükleyin", "Watch aktarımları", "Apple Watch için hazırlanıyor", "Apple Watch için sırada", "Saatin onayı bekleniyor", "Apple Watch’a kaydedildi"], - "th": ["บน Apple Watch", "ควบคุม iPhone", "ส่งเพลงจากหน้าถ่ายโอนไฟล์บน iPhone เพื่อฟังแบบออฟไลน์", "ปกและเนื้อเพลง", "ลบ", "ยกเลิก", "ไม่สามารถเล่นไฟล์นี้ได้", "ไม่สามารถบันทึกหรือลบไฟล์นี้ได้", "หมุน Digital Crown เพื่อปรับระดับเสียง Apple Watch", "ตกลง", "บันทึกบน Apple Watch ที่จับคู่ไว้เพื่อฟังแบบออฟไลน์", "จับคู่ Apple Watch และติดตั้ง Primuse", "การถ่ายโอนไปยัง Watch", "กำลังเตรียมสำหรับ Apple Watch", "อยู่ในคิวส่งไปยัง Apple Watch", "กำลังรอการยืนยันจากนาฬิกา", "บันทึกบน Apple Watch แล้ว"], + "en": ["On Apple Watch", "Control iPhone", "Send music from the iPhone transfer page to listen offline.", "Artwork and lyrics", "Delete", "Cancel", "Unable to play this file.", "Unable to save or remove this file.", "Turn the Digital Crown to adjust Apple Watch audio volume.", "OK", "Save on your paired watch for offline playback", "Pair an Apple Watch and install Primuse on it", "Watch transfers", "Preparing for Apple Watch", "Queued for Apple Watch", "Waiting for watch confirmation", "Saved on Apple Watch", "Playback Speed", "Voice Boost", "Smart Speed", "Off", "Mild", "Standard", "Strong", "Add Bookmark", "Bookmark Added", "On", "Off"], + "zh-Hans": ["手表上的音乐", "控制 iPhone", "从 iPhone 的文件传输页发送音乐,即可离线播放。", "封面与歌词", "删除", "取消", "无法播放此文件。", "无法保存或删除此文件。", "转动数码表冠调节 Apple Watch 的播放音量。", "好", "保存到已配对的手表,供离线播放", "请先配对 Apple Watch 并安装 Primuse", "手表传输记录", "正在为手表准备文件", "已加入手表传输队列", "等待手表确认", "已保存到 Apple Watch", "倍速", "人声增强", "智能速度", "关闭", "轻柔", "标准", "强力", "添加书签", "已加书签", "开启", "关闭"], + "zh-Hant": ["手錶上的音樂", "控制 iPhone", "從 iPhone 的檔案傳輸頁傳送音樂,即可離線播放。", "封面與歌詞", "刪除", "取消", "無法播放此檔案。", "無法儲存或刪除此檔案。", "轉動數位錶冠調整 Apple Watch 的播放音量。", "好", "儲存到已配對的手錶,供離線播放", "請先配對 Apple Watch 並安裝 Primuse", "手錶傳輸記錄", "正在為手錶準備檔案", "已加入手錶傳輸佇列", "等待手錶確認", "已儲存到 Apple Watch", "倍速", "人聲增強", "智慧速度", "關閉", "輕柔", "標準", "強力", "加入書籤", "已加書籤", "開啟", "關閉"], + "de": ["Auf der Apple Watch", "iPhone steuern", "Musik über die Dateiübertragung auf dem iPhone senden und offline hören.", "Cover und Liedtexte", "Löschen", "Abbrechen", "Diese Datei kann nicht abgespielt werden.", "Diese Datei konnte nicht gespeichert oder gelöscht werden.", "Mit der Digital Crown die Lautstärke der Apple Watch ändern.", "OK", "Auf der gekoppelten Watch zum Offlinehören speichern", "Apple Watch koppeln und Primuse darauf installieren", "Watch-Übertragungen", "Für Apple Watch vorbereiten", "Für Apple Watch eingereiht", "Bestätigung der Watch ausstehend", "Auf Apple Watch gespeichert", "Tempo", "Stimmverstärkung", "Smart Speed", "Aus", "Sanft", "Standard", "Stark", "Lesezeichen", "Gespeichert", "Ein", "Aus"], + "fr": ["Sur Apple Watch", "Contrôler l’iPhone", "Envoyez de la musique depuis le transfert de fichiers de l’iPhone pour l’écouter hors ligne.", "Pochettes et paroles", "Supprimer", "Annuler", "Impossible de lire ce fichier.", "Impossible d’enregistrer ou de supprimer ce fichier.", "Tournez la Digital Crown pour régler le volume de l’Apple Watch.", "OK", "Enregistrer sur la montre jumelée pour écouter hors ligne", "Jumelez une Apple Watch et installez Primuse dessus", "Transferts Watch", "Préparation pour Apple Watch", "En attente d’envoi vers Apple Watch", "En attente de confirmation de la montre", "Enregistré sur Apple Watch", "Vitesse", "Amplification vocale", "Vitesse intelligente", "Désactivé", "Doux", "Standard", "Fort", "Signet", "Signet ajouté", "Activé", "Désactivé"], + "ja": ["Apple Watch内の音楽", "iPhoneを操作", "iPhoneのファイル転送画面から音楽を送信するとオフラインで再生できます。", "アートワークと歌詞", "削除", "キャンセル", "このファイルを再生できません。", "このファイルを保存または削除できません。", "Digital CrownでApple Watchの音量を調整します。", "OK", "ペアリング済みのWatchに保存してオフライン再生", "Apple WatchをペアリングしてPrimuseをインストールしてください", "Watchへの転送", "Apple Watch用に準備中", "Apple Watchへの転送待ち", "Watchの確認待ち", "Apple Watchに保存済み", "再生速度", "ボイスブースト", "スマートスピード", "オフ", "弱", "標準", "強", "ブックマーク追加", "追加済み", "オン", "オフ"], + "ko": ["Apple Watch의 음악", "iPhone 제어", "iPhone의 파일 전송 화면에서 음악을 보내 오프라인으로 재생하세요.", "앨범 표지 및 가사", "삭제", "취소", "이 파일을 재생할 수 없습니다.", "이 파일을 저장하거나 삭제할 수 없습니다.", "Digital Crown을 돌려 Apple Watch 음량을 조절하세요.", "확인", "페어링된 시계에 저장하여 오프라인 재생", "Apple Watch를 페어링하고 Primuse를 설치하세요", "Watch 전송", "Apple Watch용 파일 준비 중", "Apple Watch 전송 대기 중", "시계 확인 대기 중", "Apple Watch에 저장됨", "재생 속도", "음성 부스트", "스마트 속도", "끔", "약하게", "표준", "강하게", "북마크 추가", "북마크됨", "켬", "끔"], + "es-MX": ["En Apple Watch", "Controlar iPhone", "Envía música desde la transferencia de archivos del iPhone para escuchar sin conexión.", "Portadas y letras", "Eliminar", "Cancelar", "No se puede reproducir este archivo.", "No se pudo guardar o eliminar este archivo.", "Gira la Digital Crown para ajustar el volumen del Apple Watch.", "Aceptar", "Guardar en el reloj enlazado para escuchar sin conexión", "Enlaza un Apple Watch e instala Primuse", "Transferencias al Watch", "Preparando para Apple Watch", "En cola para Apple Watch", "Esperando confirmación del reloj", "Guardado en Apple Watch", "Velocidad", "Realce de voz", "Velocidad inteligente", "Desactivado", "Suave", "Estándar", "Fuerte", "Agregar marcador", "Marcador guardado", "Activado", "Desactivado"], + "pt-BR": ["No Apple Watch", "Controlar iPhone", "Envie músicas pela transferência de arquivos do iPhone para ouvir offline.", "Capas e letras", "Apagar", "Cancelar", "Não foi possível reproduzir este arquivo.", "Não foi possível salvar ou apagar este arquivo.", "Gire a Digital Crown para ajustar o volume do Apple Watch.", "OK", "Salvar no relógio emparelhado para ouvir offline", "Emparelhe um Apple Watch e instale o Primuse", "Transferências para Watch", "Preparando para Apple Watch", "Na fila para Apple Watch", "Aguardando confirmação do relógio", "Salvo no Apple Watch", "Velocidade", "Realce de voz", "Velocidade inteligente", "Desativado", "Suave", "Padrão", "Forte", "Adicionar marcador", "Marcador salvo", "Ativado", "Desativado"], + "ru": ["На Apple Watch", "Управлять iPhone", "Отправьте музыку через передачу файлов на iPhone, чтобы слушать офлайн.", "Обложки и тексты", "Удалить", "Отмена", "Не удалось воспроизвести файл.", "Не удалось сохранить или удалить файл.", "Поверните Digital Crown для изменения громкости Apple Watch.", "ОК", "Сохранить на связанных часах для прослушивания офлайн", "Создайте пару с Apple Watch и установите Primuse", "Передачи на Watch", "Подготовка для Apple Watch", "В очереди на Apple Watch", "Ожидание подтверждения часов", "Сохранено на Apple Watch", "Скорость", "Усиление голоса", "Умная скорость", "Выкл", "Мягкий", "Стандарт", "Сильный", "Закладка", "Сохранено", "Вкл", "Выкл"], + "uk": ["На Apple Watch", "Керувати iPhone", "Надішліть музику через передавання файлів на iPhone, щоб слухати офлайн.", "Обкладинки й тексти", "Видалити", "Скасувати", "Не вдалося відтворити файл.", "Не вдалося зберегти або видалити файл.", "Поверніть Digital Crown, щоб змінити гучність Apple Watch.", "ОК", "Зберегти на спареному годиннику для прослуховування офлайн", "Спарте Apple Watch і встановіть Primuse", "Передавання на Watch", "Підготовка для Apple Watch", "У черзі на Apple Watch", "Очікування підтвердження годинника", "Збережено на Apple Watch", "Швидкість", "Підсилення голосу", "Розумна швидкість", "Вимк", "М’який", "Стандарт", "Сильний", "Закладка", "Збережено", "Увімк", "Вимк"], + "ar": ["على Apple Watch", "التحكم في iPhone", "أرسل الموسيقى من صفحة نقل الملفات على iPhone للاستماع دون اتصال.", "الأغلفة وكلمات الأغاني", "حذف", "إلغاء", "تعذر تشغيل هذا الملف.", "تعذر حفظ هذا الملف أو حذفه.", "أدر التاج الرقمي لضبط مستوى صوت Apple Watch.", "موافق", "الحفظ على الساعة المقترنة للاستماع دون اتصال", "اقرن Apple Watch وثبّت Primuse عليها", "عمليات النقل إلى Watch", "جارٍ التحضير لـ Apple Watch", "في قائمة الانتظار لـ Apple Watch", "بانتظار تأكيد الساعة", "تم الحفظ على Apple Watch", "السرعة", "تعزيز الصوت", "السرعة الذكية", "إيقاف", "خفيف", "قياسي", "قوي", "إضافة إشارة", "تمت الإضافة", "تشغيل", "إيقاف"], + "hi": ["Apple Watch पर", "iPhone नियंत्रित करें", "ऑफ़लाइन सुनने के लिए iPhone के फ़ाइल ट्रांसफ़र पेज से संगीत भेजें।", "कवर और गीत के बोल", "हटाएँ", "रद्द करें", "यह फ़ाइल चलाई नहीं जा सकी।", "यह फ़ाइल सहेजी या हटाई नहीं जा सकी।", "Apple Watch की आवाज़ बदलने के लिए Digital Crown घुमाएँ।", "ठीक है", "ऑफ़लाइन सुनने के लिए पेयर की गई वॉच पर सहेजें", "Apple Watch पेयर करें और उस पर Primuse इंस्टॉल करें", "Watch ट्रांसफ़र", "Apple Watch के लिए तैयारी जारी", "Apple Watch के लिए कतार में", "वॉच की पुष्टि का इंतज़ार", "Apple Watch पर सहेजा गया", "गति", "वॉइस बूस्ट", "स्मार्ट स्पीड", "बंद", "हल्का", "मानक", "तेज़", "बुकमार्क जोड़ें", "जोड़ा गया", "चालू", "बंद"], + "pl": ["Na Apple Watch", "Steruj iPhonem", "Wyślij muzykę ze strony przesyłania plików na iPhonie, aby słuchać offline.", "Okładki i teksty", "Usuń", "Anuluj", "Nie można odtworzyć tego pliku.", "Nie można zapisać lub usunąć tego pliku.", "Obróć Digital Crown, aby zmienić głośność Apple Watch.", "OK", "Zapisz na połączonym zegarku do słuchania offline", "Połącz Apple Watch i zainstaluj na nim Primuse", "Transfery do Watch", "Przygotowanie dla Apple Watch", "W kolejce do Apple Watch", "Oczekiwanie na potwierdzenie zegarka", "Zapisano na Apple Watch", "Prędkość", "Wzmocnienie głosu", "Inteligentna prędkość", "Wył.", "Łagodne", "Standard", "Silne", "Dodaj zakładkę", "Dodano", "Wł.", "Wył."], + "tr": ["Apple Watch’ta", "iPhone’u kontrol et", "Çevrimdışı dinlemek için iPhone’un dosya aktarımı sayfasından müzik gönderin.", "Kapaklar ve şarkı sözleri", "Sil", "İptal", "Bu dosya çalınamadı.", "Bu dosya kaydedilemedi veya silinemedi.", "Apple Watch sesini ayarlamak için Digital Crown’u çevirin.", "Tamam", "Çevrimdışı dinlemek için eşlenmiş saate kaydet", "Apple Watch’u eşleyin ve Primuse’u yükleyin", "Watch aktarımları", "Apple Watch için hazırlanıyor", "Apple Watch için sırada", "Saatin onayı bekleniyor", "Apple Watch’a kaydedildi", "Hız", "Ses Güçlendirme", "Akıllı Hız", "Kapalı", "Hafif", "Standart", "Güçlü", "Yer İmi Ekle", "Eklendi", "Açık", "Kapalı"], + "th": ["บน Apple Watch", "ควบคุม iPhone", "ส่งเพลงจากหน้าถ่ายโอนไฟล์บน iPhone เพื่อฟังแบบออฟไลน์", "ปกและเนื้อเพลง", "ลบ", "ยกเลิก", "ไม่สามารถเล่นไฟล์นี้ได้", "ไม่สามารถบันทึกหรือลบไฟล์นี้ได้", "หมุน Digital Crown เพื่อปรับระดับเสียง Apple Watch", "ตกลง", "บันทึกบน Apple Watch ที่จับคู่ไว้เพื่อฟังแบบออฟไลน์", "จับคู่ Apple Watch และติดตั้ง Primuse", "การถ่ายโอนไปยัง Watch", "กำลังเตรียมสำหรับ Apple Watch", "อยู่ในคิวส่งไปยัง Apple Watch", "กำลังรอการยืนยันจากนาฬิกา", "บันทึกบน Apple Watch แล้ว", "ความเร็ว", "เร่งเสียงพูด", "ความเร็วอัจฉริยะ", "ปิด", "เบา", "มาตรฐาน", "แรง", "เพิ่มบุ๊กมาร์ก", "เพิ่มแล้ว", "เปิด", "ปิด"], ] } From 876f999827fb3aa009ec904ab2b7a92fd68aa546 Mon Sep 17 00:00:00 2001 From: vizmoe Date: Wed, 2 Dec 2026 02:01:52 -0500 Subject: [PATCH 15/15] =?UTF-8?q?=E6=94=B6=E7=B4=A7=E6=9C=AC=E8=BD=AE?= =?UTF-8?q?=E9=87=8D=E6=9E=84=E7=BC=A9=E5=B0=8F=E5=90=8E=E7=9A=84=E5=A4=A7?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8E=E5=8F=AF=E8=A7=82=E5=AF=9F=E7=B1=BB?= =?UTF-8?q?=E4=BD=93=E6=9E=B6=E6=9E=84=E5=85=B3=E5=8D=A1=E5=9F=BA=E7=BA=BF?= =?UTF-8?q?=20refs=20#547?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/gate/baselines/file-size.tsv | 45 +++++++++---------- .../gate/baselines/observable-class-body.tsv | 4 +- 2 files changed, 23 insertions(+), 26 deletions(-) diff --git a/scripts/gate/baselines/file-size.tsv b/scripts/gate/baselines/file-size.tsv index ba5076a33..c8b76e013 100644 --- a/scripts/gate/baselines/file-size.tsv +++ b/scripts/gate/baselines/file-size.tsv @@ -2,8 +2,8 @@ CarPlayEditorUITests/CarPlayEditorUITests.swift 1199 CarPlayEditorUITests/HomeTopSwitchingUITests.swift 1217 CarPlayEditorUITests/SearchExperienceUITests.swift 1220 -Primuse/App/AppServices.swift 3426 -Primuse/App/CarPlaySceneDelegate.swift 3124 +Primuse/App/AppServices.swift 3423 +Primuse/App/CarPlaySceneDelegate.swift 3086 Primuse/App/PlayMediaIntentHandler.swift 1579 Primuse/App/PrimuseApp.swift 3777 Primuse/Services/AI/MusicIntelligenceService.swift 4942 @@ -13,11 +13,11 @@ Primuse/Services/AppleMusic/AppleMusicLibraryService.swift 2869 Primuse/Services/AppleMusic/AppleMusicService.swift 1708 Primuse/Services/Audio/AudioCacheManager.swift 3779 Primuse/Services/Audio/AudioCacheSyncService.swift 2055 -Primuse/Services/Audio/AudioEngine.swift 2741 -Primuse/Services/Audio/AudioPlayerService+Casting.swift 3171 +Primuse/Services/Audio/AudioEngine.swift 2737 +Primuse/Services/Audio/AudioPlayerService+Casting.swift 3095 Primuse/Services/Audio/AudioPlayerService+Helpers.swift 1186 Primuse/Services/Audio/AudioPlayerService+SharedPlaybackState.swift 1109 -Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift 1895 +Primuse/Services/Audio/AudioPlayerService+SpokenWord.swift 1887 Primuse/Services/Audio/AudioPlayerService.swift 9893 Primuse/Services/Audio/CloudPlaybackSource.swift 3353 Primuse/Services/Audio/KaraokeSeparationService.swift 1066 @@ -32,8 +32,8 @@ Primuse/Services/FullscreenPlayerEffectSettings.swift 2101 Primuse/Services/Library/LocalImportService.swift 1383 Primuse/Services/Library/MetadataBackfillService.swift 9046 Primuse/Services/Library/MusicLibrary.swift 16283 -Primuse/Services/Library/ScanService.swift 6833 -Primuse/Services/Library/SpokenWordStore.swift 1431 +Primuse/Services/Library/ScanService.swift 6832 +Primuse/Services/Library/SpokenWordStore.swift 1312 Primuse/Services/Library/SpotlightIndexService.swift 1955 Primuse/Services/Lyrics/WordLyricsAlignmentService.swift 1123 Primuse/Services/Metadata/BatchTagEditService.swift 1217 @@ -47,8 +47,8 @@ Primuse/Services/Metadata/ScraperManager.swift 1443 Primuse/Services/Metadata/Scrapers/ConfigurableScraper.swift 1681 Primuse/Services/Metadata/Scrapers/ScraperConfigStore.swift 1060 Primuse/Services/Playlist/ServerPlaylistSyncService.swift 1248 -Primuse/Services/Podcast/PodcastStore.swift 1099 -Primuse/Services/Radio/RadioStationsStore.swift 1262 +Primuse/Services/Podcast/PodcastStore.swift 1098 +Primuse/Services/Radio/RadioStationsStore.swift 1260 Primuse/Services/Sources/CloudDrive/AliyunDriveSource.swift 1093 Primuse/Services/Sources/CloudDrive/BaiduPanSource.swift 1976 Primuse/Services/Sources/CloudDrive/DrimeSource.swift 1087 @@ -69,14 +69,13 @@ Primuse/Services/Sources/SynologyScanner.swift 1343 Primuse/Services/Sources/UPnPSource.swift 1860 Primuse/Services/Sources/WebDAVSource.swift 2151 Primuse/Services/ThemeService.swift 1189 -Primuse/Services/Watch/WatchSessionBridge.swift 1045 Primuse/Utilities/FileLogger.swift 1170 Primuse/Views/Components/BatchSelection/BatchTagEditorView.swift 1482 Primuse/Views/Components/BatchSelection/SongBatchActionBar.swift 1089 Primuse/Views/Components/CachedArtworkView.swift 2938 Primuse/Views/Components/MediaDetailActionBar.swift 1644 Primuse/Views/Components/MinimalShell.swift 1256 -Primuse/Views/Components/SongPlaybackRangeEditor.swift 1147 +Primuse/Views/Components/SongPlaybackRangeEditor.swift 1113 Primuse/Views/Components/SongRowView.swift 2792 Primuse/Views/Components/StoredCoverArtView.swift 2315 Primuse/Views/ContentView.swift 4500 @@ -100,17 +99,17 @@ Primuse/Views/Library/PlaylistListView.swift 1822 Primuse/Views/Library/SmartPlaylistDetailView.swift 1162 Primuse/Views/Library/SmartPlaylistEditorView.swift 1344 Primuse/Views/Library/SongListView.swift 7458 -Primuse/Views/Library/SpokenWordLibraryView.swift 3272 +Primuse/Views/Library/SpokenWordLibraryView.swift 3200 Primuse/Views/Library/TagEditorView.swift 2747 Primuse/Views/Mac/DesktopLyricsIslandView.swift 1161 Primuse/Views/Mac/MacContentView.swift 1671 Primuse/Views/Mac/MacHomeView.swift 2640 Primuse/Views/Mac/MacImmersivePlayerView.swift 2365 Primuse/Views/Mac/MacMiniPlayerView.swift 1249 -Primuse/Views/Mac/MacNowPlayingView.swift 3500 -Primuse/Views/Mac/MacSettingsView.swift 11339 +Primuse/Views/Mac/MacNowPlayingView.swift 3497 +Primuse/Views/Mac/MacSettingsView.swift 11328 Primuse/Views/Mac/MacSourcesView.swift 1481 -Primuse/Views/Mac/PlayerMoreMenu.swift 2468 +Primuse/Views/Mac/PlayerMoreMenu.swift 2286 Primuse/Views/Mac/Theme/PrimuseTheme.swift 2390 Primuse/Views/NowPlaying/ImmersiveKineticShaderSource.swift 1378 Primuse/Views/NowPlaying/ImmersivePlayerView.swift 2182 @@ -121,15 +120,15 @@ Primuse/Views/NowPlaying/ImmersiveWatercolorStoryScene.swift 1480 Primuse/Views/NowPlaying/KaraokeStageView.swift 2104 Primuse/Views/NowPlaying/LyricsTranslationTask.swift 1054 Primuse/Views/NowPlaying/NowPlayingCarousel.swift 1784 -Primuse/Views/NowPlaying/NowPlayingView.swift 22913 +Primuse/Views/NowPlaying/NowPlayingView.swift 22904 Primuse/Views/NowPlaying/PlayerTextFont.swift 1262 Primuse/Views/NowPlaying/ScrapeFieldReviewView.swift 1173 Primuse/Views/NowPlaying/ScrapeWritebackProgress.swift 1057 Primuse/Views/NowPlaying/SongCommentsView.swift 1333 -Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift 3730 +Primuse/Views/NowPlaying/SpokenWordPlayerComponents.swift 3710 Primuse/Views/Podcast/PodcastComponents.swift 1395 -Primuse/Views/Podcast/PodcastLibraryView.swift 1928 -Primuse/Views/Radio/RadioStationsView.swift 2201 +Primuse/Views/Podcast/PodcastLibraryView.swift 1904 +Primuse/Views/Radio/RadioStationsView.swift 2189 Primuse/Views/Radio/RadioSubscriptionsView.swift 1162 Primuse/Views/Search/SearchView.swift 5664 Primuse/Views/Settings/AISettingsView.swift 2597 @@ -140,7 +139,7 @@ Primuse/Views/Settings/NowPlayingStylePreview.swift 1253 Primuse/Views/Settings/NowPlayingStylePreviewScreens.swift 1359 Primuse/Views/Settings/PlaylistImportView.swift 3820 Primuse/Views/Settings/ScrobbleSettingsView.swift 1173 -Primuse/Views/Settings/SettingsView.swift 4541 +Primuse/Views/Settings/SettingsView.swift 4500 Primuse/Views/Settings/ThemeColorSettingsView.swift 1087 Primuse/Views/Sharing/LyricPoster/LyricPosterShareSheet.swift 1188 Primuse/Views/Sharing/ServerMediaShareSheet.swift 2867 @@ -181,7 +180,7 @@ PrimuseKit/Sources/PrimuseKit/Playback/PlaybackSessionSnapshot.swift 1070 PrimuseKit/Sources/PrimuseKit/Podcast/PodcastFeedParser.swift 1089 PrimuseKit/Sources/PrimuseKit/Sources/Servers/SubsonicCatalogPagingPolicy.swift 1041 PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordBookGroupingRules.swift 1215 -PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordContentPolicy.swift 1082 +PrimuseKit/Sources/PrimuseKit/SpokenWord/SpokenWordContentPolicy.swift 1026 PrimuseKit/Sources/PrimuseKit/Storage/ScanCheckpointStore.swift 1052 PrimuseKit/Sources/PrimuseKit/Streaming/AudiobookshelfServiceClient.swift 1607 PrimuseKit/Sources/PrimuseKit/Streaming/CloudDriveStreamResolver.swift 1123 @@ -210,11 +209,11 @@ PrimuseKit/Tests/PrimuseKitTests/Streaming/FnMusicLibraryTests.swift 1063 PrimuseKit/Tests/PrimuseKitTests/Streaming/StreamResolverTests.swift 1521 PrimuseKit/Tests/PrimuseKitTests/Streaming/SynologyAudioStationTests.swift 1237 PrimuseMacTests/MacResourceRegressionTests.swift 2097 -PrimuseTV/Audio/TVAudioEngine.swift 3011 +PrimuseTV/Audio/TVAudioEngine.swift 3009 PrimuseTV/Audio/TVPlaybackCoordinator.swift 3765 PrimuseTV/Model/TVArtwork.swift 2077 PrimuseTV/Model/TVServerFeedbackService.swift 1199 -PrimuseTV/Model/TVStore.swift 10401 +PrimuseTV/Model/TVStore.swift 10358 PrimuseTV/Services/Protocol/TVMetadataEnricher.swift 1062 PrimuseTV/Services/Protocol/TVSourceScanner.swift 3611 PrimuseTV/Services/TVMetadataScrapeService.swift 1035 diff --git a/scripts/gate/baselines/observable-class-body.tsv b/scripts/gate/baselines/observable-class-body.tsv index 32c1bcaba..ec8428b0e 100644 --- a/scripts/gate/baselines/observable-class-body.tsv +++ b/scripts/gate/baselines/observable-class-body.tsv @@ -30,7 +30,6 @@ Primuse/Services/Library/HomeHeroRecommendationModel.swift HomeHeroRecommendatio Primuse/Services/Library/LocalImportService.swift ExistingLocalImportCoordinator 5 Primuse/Services/Library/LyricsTextBackfillService.swift LyricsTextBackfillService 9 Primuse/Services/Library/PlayHistoryStore.swift RecentPlaybackStore 3 -Primuse/Services/Library/SpokenWordStore.swift TingReaderProgressSyncCoordinator 7 Primuse/Services/Library/SpokenWordTranscriptOffsetStore.swift SpokenWordTranscriptOffsetStore 19 Primuse/Services/Library/SpotlightIndexService.swift SpotlightIndexStatus 7 Primuse/Services/Lyrics/BaiduTranslateService.swift BaiduTranslateAccount 15 @@ -46,7 +45,6 @@ Primuse/Services/Podcast/LocalPodcastShowSettingsStore.swift LocalPodcastShowSet Primuse/Services/Podcast/PodcastNetwork.swift PodcastAvailabilityService 6 Primuse/Services/Podcast/PodcastNetwork.swift PodcastDirectoryService 5 Primuse/Services/Radio/RadioSubscriptionsStore.swift RadioSubscriptionsStore 18 -Primuse/Services/Radio/RadioTitleHistoryStore.swift RadioTitleHistoryStore 8 Primuse/Services/Scrobble/ScrobbleSettings.swift ScrobbleSettingsStore 6 Primuse/Services/Sharing/ListeningShareService.swift ListeningShareCoordinator 6 Primuse/Services/Sources/JellyfinSourceCreationTransaction.swift MediaServerSourceCreationTransaction 4 @@ -107,7 +105,7 @@ Primuse/Views/Settings/LyricsTranslationSettingsView.swift LyricsTranscriptionSe Primuse/Views/Settings/SettingsSearchComponents.swift SettingsNavigation 3 Primuse/Views/Settings/SettingsSearchComponents.swift SettingsSearchHistory 4 Primuse/Views/Settings/SettingsSearchComponents.swift SettingsSearchState 4 -Primuse/Views/Settings/SettingsView.swift CompanionAssetDownloadFlow 11 +Primuse/Views/Settings/SettingsView.swift CompanionAssetDownloadFlow 10 Primuse/Views/Sources/AddSourceView.swift AddSourceDraftRestoration 4 Primuse/Views/Sources/PlexAccountSignIn.swift PlexAccountSignInModel 15 Primuse/Views/Sources/SourceAddressForm.swift SourceAddressProbeController 7