// 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.importCottonKitimportCottonValuesimportSwiftUI#if canImport(AVKit)import AVKit#endif/// Where a page's media bytes are.@MainActor@ObservablefinalclassMediaStageModel {enumBytes: Equatable {case resolvingcase 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?privatelet media: PhotosMediaSourcelet key: String?init(media: PhotosMediaSource, key: String?) {self.media = mediaself.key = key }/// The ledger first, then the one fetch; the view stamped either way.func resolve() async {guardlet key, !key.isEmpty else { bytes = .absentreturn } bytes = .resolving refusal = niliflet here = await media.answer(for: key, tier: .original) { bytes = .ready(path: here.path)await media.viewed(key)return }do {let path = tryawait media.ensure(key) bytes = path.isEmpty ? .absent : .ready(path: path) } catchlet error asCottonCallError {// 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 {guardlet key, bytes == .absent, let here = await media.answer(for: key, tier: .original) else { return } bytes = .ready(path: here.path) refusal = nilawait media.viewed(key) }}/// The player for one file column of one record.structMediaStage: View { @Environment(\.theme) privatevar themelet definition: TableDefinitionlet record: TableRecordlet column: ColumnDefinition @Environment(\.cottonCore) privatevar core @Environment(\.viewerPresenter) privatevar viewer @Environment(\.tableDefinitions) privatevar definitions @State privatevar model: MediaStageModel? @Environment(PagePlayback.self) privatevar playback: PagePlayback?/// The file's object key: a file column holds it as text, or as an/// object's `key`.staticfunc key(_ value: RecordValue) -> String? {switch value {case .text(let key): return key.isEmpty ? nil : keycase .object(let file): return file["key"]?.textdefault: returnnil } }var body: someView {Group {iflet 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.guardlet core, column.poster == nilelse { return }let model = MediaStageModel(media: PhotosMediaSource(core: core), key: Self.key(record[column.key]))self.model = modelif 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.privatevar margin: (text: String, glyph: String?) {let margin = definition.pictureMargin(of: column.key, in: record)return (margin.words ?? "", margin.own ? nil : "play.fill") }privatefunc film(poster: String) -> someView {let id = ViewerItem.pageID(definition.id, record.id, column.key)returnButton {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 {iflet 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 privatevar recording: someView {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.structRecordingPlayer: View { @Environment(\.theme) privatevar themelet path: Stringlet seed: String #if canImport(AVKit) @State privatevar player: AVPlayer? #endif @State privatevar playing = false @State privatevar played: Double = 0 @Environment(PagePlayback.self) privatevar playback: PagePlayback?var body: someView {// 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 inlet 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.iflet waiting = playback?.waiting { playback?.waiting = nil play(from: waiting) }await follow() } .onChange(of: playback?.ask) { _, _ iniflet playback { play(from: playback.from) } } }/// Plays from a time a turn of the transcript names.privatefunc 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 }privatefunc 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.privatefunc follow() async { #if canImport(AVKit)while !Task.isCancelled {try? awaitTask.sleep(for: .milliseconds(500))guardlet player, let item = player.currentItem else { continue }let total = item.duration.secondsguard total.isFinite, total > 0else { 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`).enumMediaStageKnobs {/// 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.staticlet macAway = "mac_away"staticlet faceMediaCaptionFillOpacity: CGFloat = 0.85staticlet faceMediaControlFillOpacity: CGFloat = 0.16staticlet faceMediaStageCaptionHorizontalPadding: CGFloat = 10staticlet faceMediaStageCaptionVerticalPadding: CGFloat = 4staticlet faceMediaStageControlHeight: CGFloat = 34staticlet faceMediaStageGap: CGFloat = 8staticlet faceMediaStageIconSide: CGFloat = 32staticlet faceMediaStageMaxWidth: CGFloat = 320staticlet faceMediaStagePlayScale: CGFloat = 1.3staticlet faceMediaStagePlaySymbolSize: CGFloat = 12staticlet faceMediaStagePlayerGap: CGFloat = 12staticlet faceMediaStagePosterEdge: CGFloat = 320staticlet faceMediaStageWaveBarFraction: CGFloat = 0.45staticlet faceMediaStageWavePitch: CGFloat = 3}