Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Audio/AudioQueue.swift3// Description: The play queue as pure data: order, shuffle, repeat, edits.4import Foundation56public struct QueueItem: Identifiable, Hashable, Sendable {7 public let id: UUID8 public var track: Track9 public init(_ track: Track, id: UUID = UUID()) { self.id = id; self.track = track }10}1112public enum RepeatMode: String, Sendable, CaseIterable { case off, all, one }1314/// The play queue: pure data and rules, no audio. `items` is always in the order things will play; turning shuffle15/// on reorders what comes after the current item and remembers the original order to restore it.16public struct AudioQueue: Sendable, Equatable {17 public private(set) var items: [QueueItem] = []18 public private(set) var index = 019 public private(set) var shuffle = false20 public var repeatMode: RepeatMode = .off21 private var originalOrder: [UUID] = []2223 public init() {}2425 public var current: QueueItem? { items.indices.contains(index) ? items[index] : nil }26 public var isEmpty: Bool { items.isEmpty }27 public var upcoming: ArraySlice<QueueItem> { index + 1 < items.count ? items[(index + 1)...] : [] }2829 public mutating func set(_ tracks: [Track], startAt start: Int = 0, shuffle: Bool? = nil) {30 items = tracks.map { QueueItem($0) }31 originalOrder = items.map(\.id)32 index = items.isEmpty ? 0 : max(0, min(start, items.count - 1))33 if let shuffle { self.shuffle = shuffle }34 if self.shuffle { shuffleUpcoming() }35 }3637 private mutating func shuffleUpcoming() {38 guard index + 1 < items.count else { return }39 var rest = Array(items[(index + 1)...]); rest.shuffle()40 items.replaceSubrange((index + 1)..., with: rest)41 }4243 public mutating func setShuffle(_ on: Bool) {44 guard on != shuffle else { return }45 shuffle = on46 guard let cur = current else { return }47 if on { shuffleUpcoming() }48 else {49 // Back to the original order, staying on the current item.50 let rank = Dictionary(uniqueKeysWithValues: originalOrder.enumerated().map { ($1, $0) })51 items.sort { (rank[$0.id] ?? .max) < (rank[$1.id] ?? .max) }52 index = items.firstIndex { $0.id == cur.id } ?? 053 }54 }5556 /// Index that plays after the current one. `auto` is true when the track ended by itself (then "repeat one" replays it).57 public func nextIndex(auto: Bool) -> Int? {58 guard !items.isEmpty else { return nil }59 if auto && repeatMode == .one { return index }60 if index + 1 < items.count { return index + 1 }61 return repeatMode == .off ? nil : 062 }63 public func previousIndex() -> Int? {64 guard !items.isEmpty else { return nil }65 if index > 0 { return index - 1 }66 return repeatMode == .all ? items.count - 1 : nil67 }68 public func item(at i: Int) -> QueueItem? { items.indices.contains(i) ? items[i] : nil }6970 public mutating func jump(to i: Int) { if items.indices.contains(i) { index = i } }71 public mutating func jump(toItem id: UUID) { if let i = items.firstIndex(where: { $0.id == id }) { index = i } }7273 public mutating func playNext(_ tracks: [Track]) {74 let new = tracks.map { QueueItem($0) }75 let at = items.isEmpty ? 0 : index + 176 items.insert(contentsOf: new, at: at)77 originalOrder.append(contentsOf: new.map(\.id))78 }79 public mutating func append(_ tracks: [Track]) {80 let new = tracks.map { QueueItem($0) }81 items.append(contentsOf: new); originalOrder.append(contentsOf: new.map(\.id))82 }83 /// Removes an item. Removing the current one is not allowed here (the controller skips first).84 public mutating func remove(_ id: UUID) {85 guard let i = items.firstIndex(where: { $0.id == id }), i != index else { return }86 items.remove(at: i); originalOrder.removeAll { $0 == id }87 if i < index { index -= 1 }88 }89 public mutating func move(from source: Int, to destination: Int) {90 guard items.indices.contains(source), destination >= 0, destination <= items.count, source != destination, source + 1 != destination else { return }91 let currentID = current?.id92 let item = items.remove(at: source)93 items.insert(item, at: destination > source ? destination - 1 : destination)94 if let currentID { index = items.firstIndex { $0.id == currentID } ?? index }95 }96 public mutating func clearUpcoming() {97 guard index + 1 < items.count else { return }98 let gone = Set(items[(index + 1)...].map(\.id))99 items.removeSubrange((index + 1)...); originalOrder.removeAll { gone.contains($0) }100 }101 /// Replaces the stored copy of a track (its download state or metadata changed).102 public mutating func refresh(_ tracks: [Track]) {103 let by = Dictionary(tracks.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })104 for i in items.indices { if let t = by[items[i].track.id] { items[i].track = t } }105 }106}107