Repository Public
1// SP Music iOS2// File: Core/Sources/SPMusicCore/Audio/PlaybackQueue.swift3// Description: Play queue rules (order, shuffle, repeat) as a pure value type.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910public enum RepeatMode: String, Sendable, Codable, CaseIterable { case off, all, one }1112/// The play queue: an ordered list, a position in it, shuffle and repeat. Pure value type (no audio, no I/O) with13/// the same rules as the web player, so both behave alike and the rules can be tested on their own.14public struct PlaybackQueue: Sendable, Equatable {15 public private(set) var tracks: [Track] = []16 public private(set) var index = 017 public private(set) var shuffle = false18 public var repeatMode = RepeatMode.off19 /// Order before shuffle was switched on (track ids).20 private var unshuffled: [String]?2122 public init() {}23 public var current: Track? { tracks.indices.contains(index) ? tracks[index] : nil }24 public var isEmpty: Bool { tracks.isEmpty }25 public var upcoming: ArraySlice<Track> { tracks.isEmpty ? [] : tracks[min(index + 1, tracks.count)...] }2627 public enum Step: Sendable, Equatable { case moved, restartCurrent, ended, none }2829 /// Replaces the queue. With `shuffle`, the start track comes first and the rest is shuffled behind it.30 public mutating func replace(_ list: [Track], startAt start: Int = 0, shuffle on: Bool? = nil, pickRandomStart: Bool = false, using rng: inout some RandomNumberGenerator) {31 guard !list.isEmpty else { tracks = []; index = 0; unshuffled = nil; return }32 let i = min(max(0, start), list.count - 1)33 shuffle = on ?? shuffle34 if shuffle {35 unshuffled = list.map(\.id)36 let first = pickRandomStart ? Int.random(in: 0..<list.count, using: &rng) : i37 var rest = list; rest.remove(at: first); rest.shuffle(using: &rng)38 tracks = [list[first]] + rest; index = 039 } else { unshuffled = nil; tracks = list; index = i }40 }41 public mutating func replace(_ list: [Track], startAt start: Int = 0, shuffle on: Bool? = nil, pickRandomStart: Bool = false) {42 var g = SystemRandomNumberGenerator()43 replace(list, startAt: start, shuffle: on, pickRandomStart: pickRandomStart, using: &g)44 }4546 /// Restores a saved queue as it was (no reshuffle).47 public mutating func restore(_ list: [Track], index i: Int, shuffle on: Bool, repeatMode r: RepeatMode) {48 tracks = list; index = list.isEmpty ? 0 : min(max(0, i), list.count - 1); shuffle = on; repeatMode = r; unshuffled = nil49 }5051 /// Index that would play after the current track ends by itself (nil: the queue ends, or repeat-one).52 public var indexAfterCurrent: Int? {53 guard !tracks.isEmpty, repeatMode != .one else { return nil }54 if index + 1 < tracks.count { return index + 1 }55 return repeatMode == .all ? 0 : nil56 }5758 /// `auto`: the track ended by itself. Otherwise the listener pressed "next".59 public mutating func advance(auto: Bool) -> Step {60 guard !tracks.isEmpty else { return .none }61 if auto && repeatMode == .one { return .restartCurrent }62 if index + 1 < tracks.count { index += 1; return .moved }63 if repeatMode == .all { index = 0; return .moved }64 return auto ? .ended : .none65 }6667 /// "Previous": back to the start of the track when it has played more than 3 s, else to the track before.68 public mutating func previous(position: TimeInterval) -> Step {69 guard !tracks.isEmpty else { return .none }70 if position > 3 { return .restartCurrent }71 if index > 0 { index -= 1; return .moved }72 if repeatMode == .all { index = tracks.count - 1; return .moved }73 return .restartCurrent74 }7576 public mutating func jump(to i: Int) -> Step {77 guard tracks.indices.contains(i) else { return .none }78 index = i; return .moved79 }8081 public mutating func playNext(_ list: [Track]) {82 if tracks.isEmpty { tracks = list; index = 0; return }83 tracks.insert(contentsOf: list, at: index + 1)84 }85 public mutating func append(_ list: [Track]) { tracks.append(contentsOf: list) }8687 /// Returns true when the current track was the one removed (the player must load the new current track).88 public mutating func remove(at i: Int) -> Bool {89 guard tracks.indices.contains(i) else { return false }90 tracks.remove(at: i)91 if i == index { index = min(i, max(0, tracks.count - 1)); return true }92 if i < index { index -= 1 }93 return false94 }9596 public mutating func move(from: Int, to: Int) {97 guard from != to, tracks.indices.contains(from), tracks.indices.contains(to) else { return }98 let cur = index99 let t = tracks.remove(at: from); tracks.insert(t, at: to)100 if from == cur { index = to }101 else if from < cur && to >= cur { index = cur - 1 }102 else if from > cur && to <= cur { index = cur + 1 }103 }104105 public mutating func clearUpcoming() { if !tracks.isEmpty { tracks = Array(tracks[...index]) } }106107 public mutating func setShuffle(_ on: Bool, using rng: inout some RandomNumberGenerator) {108 guard on != shuffle else { return }109 shuffle = on110 guard let cur = current else { return }111 if on {112 unshuffled = tracks.map(\.id)113 var rest = Array(tracks[(index + 1)...]); rest.shuffle(using: &rng)114 tracks = Array(tracks[...index]) + rest115 } else if let order = unshuffled {116 // Back to the original order, keeping what was added or removed since.117 let by = Dictionary(tracks.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })118 var restored = order.compactMap { by[$0] }119 let known = Set(order)120 restored.append(contentsOf: tracks.filter { !known.contains($0.id) })121 if restored.count == tracks.count { tracks = restored; index = tracks.firstIndex { $0.id == cur.id } ?? 0 }122 unshuffled = nil123 }124 }125 public mutating func setShuffle(_ on: Bool) { var g = SystemRandomNumberGenerator(); setShuffle(on, using: &g) }126127 public mutating func cycleRepeat() { repeatMode = repeatMode == .off ? .all : repeatMode == .all ? .one : .off }128129 /// Catalogue changed (favourite toggled, tags edited): refresh the copies held by the queue.130 public mutating func refresh(with fresh: [String: Track]) { tracks = tracks.map { fresh[$0.id] ?? $0 } }131}132