// The player: a page's audio or video column, playing where the page stands — // one drawing for every table whose slip names the column as its `player` // (Photos built it for films; Videos and Meetings wear the same one). // // * A FILE COLUMN WITH A `poster` is a film: the print at the picture's own // proportion with its poster in the window, and a tap plays it in the one // viewer (`MediaViewer`), which is the one player. Without a poster it is // a recording: the round play disc and the waveform, playing in place. // * WHERE THE BYTES ARE, SAID HONESTLY (`MediaStageModel`): `read.mediaPath` // under `tier: original` first — load-bearing, since a film's key resolves // under the tile's order to its thumbnail JPEG and would play nothing — // then `media.ensure`, the one fetch, which opening the page is the // asking for; `media.viewed` stamps the view. While they are not here the // print says so by hand ("fetching the video…", "not on this phone yet"), // and the crate's own refusal sentence is kept, never a code. A media // arrival while absent asks the LEDGER only, never the radio. import CottonKit import CottonValues import SwiftUI #if canImport(AVKit) import AVKit #endif /// Where a page's media bytes are. @MainActor @Observable final class MediaStageModel { enum Bytes: Equatable { case resolving case ready(path: String) case absent } private(set) var bytes: Bytes = .resolving /// The crate's own sentence for why the bytes cannot be had. private(set) var refusal: String? private let media: PhotosMediaSource let key: String? init(media: PhotosMediaSource, key: String?) { self.media = media self.key = key } /// The ledger first, then the one fetch; the view stamped either way. func resolve() async { guard let key, !key.isEmpty else { bytes = .absent return } bytes = .resolving refusal = nil if let here = await media.answer(for: key, tier: .original) { bytes = .ready(path: here.path) await media.viewed(key) return } do { let path = try await media.ensure(key) bytes = path.isEmpty ? .absent : .ready(path: path) } catch let error as CottonCallError { // Never the store's own words (a storage key, a status code): // what the person can know and do. The Mac away is the core's one // sentence for a missing byte; Fetch stays offered to retry. refusal = error.code == MediaStageKnobs.macAway ? error.message : ShellLines.line("faces", "media.could_not_fetch") bytes = .absent } catch { bytes = .absent } } /// Bytes moved on this phone: while absent, ask the ledger — never fetch /// again, which a failed fetch re-run on every tick once was. func resolveHere() async { guard let key, bytes == .absent, let here = await media.answer(for: key, tier: .original) else { return } bytes = .ready(path: here.path) refusal = nil await media.viewed(key) } } /// The player for one file column of one record. struct MediaStage: View { @Environment(\.theme) private var theme let definition: TableDefinition let record: TableRecord let column: ColumnDefinition @Environment(\.cottonCore) private var core @Environment(\.viewerPresenter) private var viewer @Environment(\.tableDefinitions) private var definitions @State private var model: MediaStageModel? @Environment(PagePlayback.self) private var playback: PagePlayback? /// The file's object key: a file column holds it as text, or as an /// object's `key`. static func key(_ value: RecordValue) -> String? { switch value { case .text(let key): return key.isEmpty ? nil : key case .object(let file): return file["key"]?.text default: return nil } } var body: some View { Group { if let poster = column.poster { film(poster: poster) } else { recording } } .task(id: Self.key(record[column.key])) { // A film's bytes are the viewer's to ask for, on the tap. guard let core, column.poster == nil else { return } let model = MediaStageModel(media: PhotosMediaSource(core: core), key: Self.key(record[column.key])) self.model = model if column.poster == nil { playback?.stage = model } await model.resolve() } .onMediaArrival { await model?.resolveHere() } .accessibilityIdentifier("page-\(definition.id)-player-\(column.key)") } /// The margin's words: the owner's caption alone; else the column's /// `caption_fallback` (the film's length, "0:42") beside the play mark; /// else the play mark alone — never a "0:00" for a film nobody measured. private var margin: (text: String, glyph: String?) { let margin = definition.pictureMargin(of: column.key, in: record) return (margin.words ?? "", margin.own ? nil : "play.fill") } private func film(poster: String) -> some View { let id = ViewerItem.pageID(definition.id, record.id, column.key) return Button { let item = ViewerItem( id: id, kind: .video, key: Self.key(record[column.key]), poster: record[poster].text, title: record.said?.slip.title, record: ViewerRecord(table: definition.id, id: record.id)) viewer?.open(ViewerSet(items: [item], start: 0)) } label: { InstantPrint( seed: record.id, caption: margin.text, captionGlyph: margin.glyph, size: .hero, photoAspect: definition.aspect(of: column.key, in: record).map { CGFloat($0) }, tilts: false ) { ZStack { if let key = record[poster].text { PagePicture(key: key, edge: MediaStageKnobs.faceMediaStagePosterEdge) } // A film's page says it plays: the paper disc over its // poster (walker 604bcce6). NavDisc(symbol: "play.fill") .scaleEffect(MediaStageKnobs.faceMediaStagePlayScale) .accessibilityHidden(true) } } } .buttonStyle(MotionButtonStyle()) .viewerSource(id) .frame(maxWidth: MediaStageKnobs.faceMediaStageMaxWidth) .frame(maxWidth: .infinity) } @ViewBuilder private var recording: some View { switch model?.bytes { case .ready(let path)?: RecordingPlayer(path: path, seed: record.id) case .absent?: // No play disc for bytes that are not here: the slip, and the // one act that can change it. AbsentSlip( kind: .recording, words: ViewerWords.reading(definitions), onFetch: { Task { await model?.resolve() } }, compact: true) .accessibilityIdentifier("page-\(definition.id)-not-here") default: AbsentSlip(kind: .recording, words: ViewerWords.reading(definitions), fetching: true, onFetch: {}, compact: true) } } } /// A recording, playing in place: the round disc plays and pauses, and the /// waveform (seeded by the record's id — no column holds a loudness) inks in /// as it plays. struct RecordingPlayer: View { @Environment(\.theme) private var theme let path: String let seed: String #if canImport(AVKit) @State private var player: AVPlayer? #endif @State private var playing = false @State private var played: Double = 0 @Environment(PagePlayback.self) private var playback: PagePlayback? var body: some View { // ONE button, the disc and the waveform together (S1): a tap anywhere // on the player plays or pauses, never only on the small disc. Button { toggle() } label: { HStack(spacing: MediaStageKnobs.faceMediaStagePlayerGap) { Image(systemName: playing ? "pause.fill" : "play.fill") .font(theme.type.interface(MediaStageKnobs.faceMediaStagePlaySymbolSize)) .foregroundStyle(theme.print(.ink)) .frame(width: MediaStageKnobs.faceMediaStageIconSide, height: MediaStageKnobs.faceMediaStageIconSide) .background(Circle().fill(theme.print(.pencil).opacity(MediaStageKnobs.faceMediaControlFillOpacity))) GeometryReader { geo in let bars = MeetingWaveform.bars( MeetingWaveform.samples(id: seed), count: MeetingWaveform.barCount(width: geo.size.width, pitch: MediaStageKnobs.faceMediaStageWavePitch)) ZStack(alignment: .leading) { Waveform(samples: bars, barFraction: MediaStageKnobs.faceMediaStageWaveBarFraction, theme: theme).fill(theme.print(.pencil)) Waveform(samples: bars, barFraction: MediaStageKnobs.faceMediaStageWaveBarFraction, theme: theme).fill(theme.print(.ink)) .mask(alignment: .leading) { Rectangle().frame(width: geo.size.width * played) } } } .frame(height: MediaStageKnobs.faceMediaStageControlHeight) } .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(ShellLines.line("faces", playing ? "media.pause" : "media.play")) .onChange(of: playing) { _, now in playback?.playing = now } .onDisappear { playback?.playing = false } .task(id: path) { // A turn tapped before the bytes were here plays now they are. if let waiting = playback?.waiting { playback?.waiting = nil play(from: waiting) } await follow() } .onChange(of: playback?.ask) { _, _ in if let playback { play(from: playback.from) } } } /// Plays from a time a turn of the transcript names. private func play(from seconds: Double) { #if canImport(AVKit) if player == nil { player = AVPlayer(url: URL(fileURLWithPath: path)) } player?.seek(to: CMTime(seconds: seconds, preferredTimescale: 600)) player?.play() playing = true #endif } private func toggle() { #if canImport(AVKit) if player == nil { player = AVPlayer(url: URL(fileURLWithPath: path)) } if playing { player?.pause() } else { player?.play() } playing.toggle() #endif } /// Where the playhead is, read twice a second while the page is open. private func follow() async { #if canImport(AVKit) while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(500)) guard let player, let item = player.currentItem else { continue } let total = item.duration.seconds guard total.isFinite, total > 0 else { continue } played = min(1, max(0, player.currentTime().seconds / total)) if played >= 1 { playing = false } } #endif } } /// The sizes, counts and timings MediaStage draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum MediaStageKnobs { /// The core's code for a missing byte while this device's copy says the /// Mac that keeps it is away (`read.sync_state`), never one failed fetch. static let macAway = "mac_away" static let faceMediaCaptionFillOpacity: CGFloat = 0.85 static let faceMediaControlFillOpacity: CGFloat = 0.16 static let faceMediaStageCaptionHorizontalPadding: CGFloat = 10 static let faceMediaStageCaptionVerticalPadding: CGFloat = 4 static let faceMediaStageControlHeight: CGFloat = 34 static let faceMediaStageGap: CGFloat = 8 static let faceMediaStageIconSide: CGFloat = 32 static let faceMediaStageMaxWidth: CGFloat = 320 static let faceMediaStagePlayScale: CGFloat = 1.3 static let faceMediaStagePlaySymbolSize: CGFloat = 12 static let faceMediaStagePlayerGap: CGFloat = 12 static let faceMediaStagePosterEdge: CGFloat = 320 static let faceMediaStageWaveBarFraction: CGFloat = 0.45 static let faceMediaStageWavePitch: CGFloat = 3 }