Cotton code
190 lines · 8.1 KB · SwiftRaw
// A player for the specimens (Loom, 29 Oct 2026): what the phone's player is// to a card, with no sound and no files — it holds where it stands on a// specimen's tape (how far into the whole playlist, and so which song and// how far into it), runs at the wall clock's pace while it plays, pauses,// seeks in the song and plays from any song. It answers the one hook a face// plays under (`faceTrackPlayer`, as CottonUI's `DeckTrackPlaying` does on// the phone), so the Loom app plays a cassette's specimens on the owner's phone// and he watches its reels turn and its pack wind. A card that carries no// songs stands still under it, as under no player. While it plays it meters// an invented level in each channel (`SpecimenLevels`), so a hi-fi's needles// move with no sound.import CottonFacesimport CottonValuesimport Observationimport SwiftUI/// Where a specimen's tape stands, at any moment: the songs' lengths, how/// far into the whole playlist it stood when it last started or stopped,/// and since when it has been playing.@MainActor @Observablepublic final class SpecimenPlayer {    /// Each song's length, in seconds, in the playlist's order.    public let lengths: [TimeInterval]    /// Seconds into the whole playlist, as of `since` while it plays.    private var at: TimeInterval = 0    /// When it last started playing from `at`; nil while it does not play.    private var since: Date?    /// It holds a song: it has played since it was still.    private var held = false    /// The specimen's volume, nought to one: no sound's.    public var volume: Double = 0.5    public init(lengths: [TimeInterval]) {        self.lengths = lengths.map { max(0, $0) }    }    /// A player standing where `play` says, at `now`: holding its song that    /// far in, playing from `now` or paused; still where it holds none.    public convenience init(lengths: [TimeInterval], standing play: TrackPlay, at now: Date) {        self.init(lengths: lengths)        guard play.held, !self.lengths.isEmpty else { return }        let song = min(max(0, play.song ?? 0), self.lengths.count - 1)        at = self.lengths[..<song].reduce(0, +) + min(max(0, play.elapsed), self.lengths[song])        held = true        since = play.playing ? now : nil    }    /// The whole playlist's length.    public var whole: TimeInterval { lengths.reduce(0, +) }    /// Seconds into the whole playlist at `now`: it runs at the clock's pace    /// while playing, and stops at the end.    public func position(at now: Date) -> TimeInterval {        guard let since else { return at }        return min(whole, at + max(0, now.timeIntervalSince(since)))    }    /// It is playing at `now`: started, not paused, not run out.    public func playing(at now: Date) -> Bool {        since != nil && position(at: now) < whole    }    /// Where it stands at `now`, as a face draws it: the song it holds, how    /// far into that song and how long it is; still while it holds none.    public func play(at now: Date) -> TrackPlay {        guard held, !lengths.isEmpty else { return .still }        let position = position(at: now)        var song = 0        var before: TimeInterval = 0        while song < lengths.count - 1, position >= before + lengths[song] {            before += lengths[song]            song += 1        }        let playing = playing(at: now)        return TrackPlay(            held: true, playing: playing, elapsed: min(lengths[song], position - before), duration: lengths[song],            song: song, level: playing ? SpecimenLevels.at(position) : nil)    }    /// Plays, or pauses where it stands; played while still, or once run    /// out, it plays from the first song.    public func toggle(at now: Date) {        guard whole > 0 else { return }        let position = position(at: now)        if since != nil, position < whole {            at = position            since = nil        } else {            at = !held || position >= whole ? 0 : position            held = true            since = now        }    }    /// Plays from the start of the song at `song`.    public func start(_ song: Int, at now: Date) {        guard lengths.indices.contains(song) else { return }        at = lengths[..<song].reduce(0, +)        held = true        since = now    }    /// Moves the playhead to `elapsed` into the song it holds, playing on    /// from there if it was playing.    public func seek(to elapsed: TimeInterval, at now: Date) {        let standing = play(at: now)        guard let song = standing.song else { return }        at = lengths[..<song].reduce(0, +) + min(max(0, elapsed), lengths[song])        if since != nil { since = now }    }}/// The specimen player as a face asks for one.public enum SpecimenPlaying {    /// What the Loom app installs as `faceTrackPlayer`: a card that carries    /// songs, or an episode, plays under a player of its own, redrawn at the    /// screen's pace while it plays; any other is still, as under no player.    public static let player: FaceTrackPlayer = { card, drawn in        AnyView(SpecimenPlayerCard(card: card, standing: nil, drawn: drawn))    }    /// The player a specimen reviewed under the player's word is drawn    /// under (`Specimen.play`): one that starts where it says.    public static func standing(_ play: TrackPlay) -> FaceTrackPlayer {        { card, drawn in AnyView(SpecimenPlayerCard(card: card, standing: play, drawn: drawn)) }    }    /// The lengths a card's specimen player plays: its songs', else its    /// episode's, else its song's (`duration`).    static func lengths(_ card: DeckCard) -> [TimeInterval] {        let songs = CassetteTape.songs(card).map(\.seconds)        if !songs.isEmpty { return songs }        if let episode = RadioDial.episode(card) { return [episode.seconds] }        return card.fields["duration"]?.number.map { [$0] } ?? []    }}/// An invented level in each channel, as a player meters it twenty times a/// second: a beat and a slower swell under it, the right channel a little/// behind the left, always somewhere between quiet and loud. The same at the/// same place in the playlist, so a specimen drawn twice draws the same.public enum SpecimenLevels {    /// How often the specimen player meters, a second.    public static let rate: Double = 20    public static func at(_ position: TimeInterval) -> TrackLevel {        let t = (position * rate).rounded(.down) / rate        return TrackLevel(left: channel(t), right: channel(t + 0.13))    }    /// One channel at `t`: a swell over eight seconds, a beat at two a    /// second, and a flutter, held between a fifth and nineteen twentieths.    static func channel(_ t: Double) -> Double {        let swell = 0.5 + 0.18 * sin(2 * .pi * t / 8)        let beat = 0.16 * pow(max(0, cos(2 * .pi * t * 2)), 3)        let flutter = 0.06 * sin(2 * .pi * t * 7.3) + 0.04 * sin(2 * .pi * t * 13.1)        return min(0.95, max(0.2, swell + beat + flutter))    }}/// One card under its specimen player.private struct SpecimenPlayerCard: View {    let card: DeckCard    let drawn: (FaceTrackPlay) -> AnyView    @State private var player: SpecimenPlayer    init(card: DeckCard, standing: TrackPlay?, drawn: @escaping (FaceTrackPlay) -> AnyView) {        self.card = card        self.drawn = drawn        let lengths = SpecimenPlaying.lengths(card)        _player = State(initialValue: standing.map { SpecimenPlayer(lengths: lengths, standing: $0, at: .now) } ?? SpecimenPlayer(lengths: lengths))    }    var body: some View {        if player.whole > 0 {            TimelineView(.animation(paused: !player.playing(at: .now))) { timeline in                drawn(FaceTrackPlay(                    play: player.play(at: timeline.date),                    toggle: { player.toggle(at: .now) },                    seek: { player.seek(to: $0, at: .now) },                    start: { player.start($0, at: .now) },                    volume: player.volume,                    turnVolume: { player.volume = $0 }))            }        } else {            drawn(FaceTrackPlay(play: .still, toggle: nil, seek: { _ in }))        }    }}