Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassMedia/Media/GlassVideoPlayer+Controls.swift8// Module : SPGlassMedia9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0312// Last Modified : 2026-12-0313//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// Glass transport controls over a video surface the host draws: a poster, a custom player layer, a canvas.48///49/// ```swift50/// @State private var playback = GlassAVAudioPlayback(url: trailerURL) // drives any `AVPlayer`51///52/// GlassVideoControls(playback: playback, title: "Trailer") {53/// PlayerLayerView(player: playback.player) // or a poster image54/// }55/// ```56///57/// Use ``GlassVideoPlayer`` when the system controls are what you want. This view is for hosts that draw the58/// picture themselves: it adds a play or pause button and the skip buttons in the centre, and a bar with the59/// elapsed time, a seek track and the remaining time at the bottom, all on Liquid Glass over the picture.60/// Playback never starts by itself. While playing, the controls hide after a few seconds and a tap on the61/// picture brings them back; they stay on screen while paused and while VoiceOver is running.62/// When the playback reports `isAvailable == false` a "Media unavailable" plate replaces the controls.63public struct GlassVideoControls<Playback: GlassAudioPlayback, Surface: View>: View {64 @GlassThemed private var theme65 @Environment(\.accessibilityVoiceOverEnabled) private var isVoiceOverRunning66 @GlassAccessibility private var accessibility67 private let playback: Playback68 private let title: String?69 private let aspectRatio: CGFloat?70 private let skipInterval: TimeInterval71 private let surface: Surface72 @State private var showsControls = true73 @State private var interactionCount = 07475 /// - Parameters:76 /// - playback: the engine to display and drive.77 /// - title: name of the video, shown in a chip at the top and used as the accessibility label.78 /// - aspectRatio: width divided by height; `nil` lets the view fill the space it is given.79 /// - skipInterval: seconds skipped by the skip buttons.80 /// - surface: the picture. It is clipped to the frame.81 public init(82 playback: Playback,83 title: String? = nil,84 aspectRatio: CGFloat? = 16.0 / 9.0,85 skipInterval: TimeInterval = 10,86 @ViewBuilder surface: () -> Surface87 ) {88 self.playback = playback89 self.title = title90 self.aspectRatio = GlassVideoLayout.sanitizedAspectRatio(aspectRatio)91 self.skipInterval = max(skipInterval, 1)92 self.surface = surface()93 }9495 private var controlsAreVisible: Bool {96 GlassVideoControlsVisibility.isVisible(requested: showsControls, isPlaying: playback.isPlaying, isVoiceOverRunning: isVoiceOverRunning)97 }9899 public var body: some View {100 let shape = theme.shape(\.large)101 Color.black102 .overlay { surface }103 .clipped()104 .contentShape(Rectangle())105 .onTapGesture {106 showsControls.toggle()107 interactionCount += 1108 }109 .overlay {110 if playback.isAvailable {111 GlassVideoControlLayer(playback: playback, title: title, skipInterval: skipInterval) {112 showsControls = true113 interactionCount += 1114 }115 .opacity(controlsAreVisible ? 1 : 0)116 .allowsHitTesting(controlsAreVisible)117 .accessibilityHidden(!controlsAreVisible)118 .animation(theme.animation(.fast, reduceMotion: accessibility.reduceMotion), value: controlsAreVisible)119 // Video chrome is dark whatever the appearance, as in the system player.120 .environment(\.colorScheme, .dark)121 } else {122 GlassMediaUnavailablePlate(systemImage: "video.slash")123 }124 }125 .aspectRatio(aspectRatio, contentMode: .fit)126 .clipShape(shape)127 .overlay(shape.strokeBorder(theme.color(.separator).opacity(0.6), lineWidth: 0.5))128 .accessibilityElement(children: .contain)129 .accessibilityLabel(title.map { Text(verbatim: $0) } ?? Text(GlassL10n.string(.videoPlayer)))130 .task(id: GlassVideoControlsVisibility.HideTrigger(isPlaying: playback.isPlaying, interaction: interactionCount)) {131 guard playback.isPlaying, showsControls else { return }132 try? await Task.sleep(for: .seconds(GlassVideoControlsVisibility.autoHideDelay))133 if !Task.isCancelled, playback.isPlaying { showsControls = false }134 }135 }136}137138/// When the controls of a ``GlassVideoControls`` are on screen.139public enum GlassVideoControlsVisibility {140 /// Seconds of playback without interaction after which the controls hide.141 public static let autoHideDelay: TimeInterval = 3142143 /// The controls can only be hidden while playing, and never while VoiceOver is running.144 public static func isVisible(requested: Bool, isPlaying: Bool, isVoiceOverRunning: Bool) -> Bool {145 requested || !isPlaying || isVoiceOverRunning146 }147148 struct HideTrigger: Equatable {149 let isPlaying: Bool150 let interaction: Int151 }152}153154/// The controls themselves. A separate view so that its theme resolves in the dark appearance forced by the owner.155private struct GlassVideoControlLayer<Playback: GlassAudioPlayback>: View {156 @GlassThemed private var theme157 let playback: Playback158 let title: String?159 let skipInterval: TimeInterval160 let onInteraction: @MainActor () -> Void161 @State private var scrubTime: TimeInterval?162163 private var displayedTime: TimeInterval {164 GlassPlaybackMath.clampedSeek(scrubTime ?? playback.currentTime, duration: playback.duration)165 }166167 var body: some View {168 ZStack {169 GlassGroup(spacing: theme.spacing.lg) {170 HStack(spacing: theme.spacing.lg) {171 roundButton(GlassAudioPlayerSymbols.skip(skipInterval, forward: false), label: .skipBack, diameter: 44, symbolSize: 18) {172 playback.seek(to: GlassPlaybackMath.skip(from: playback.currentTime, by: -skipInterval, duration: playback.duration))173 }174 roundButton(playback.isPlaying ? "pause.fill" : "play.fill", label: playback.isPlaying ? .pause : .play, diameter: 64, symbolSize: 26) {175 if playback.isPlaying { playback.pause() } else { playback.play() }176 }177 .keyboardShortcut(.space, modifiers: [])178 roundButton(GlassAudioPlayerSymbols.skip(skipInterval, forward: true), label: .skipForward, diameter: 44, symbolSize: 18) {179 playback.seek(to: GlassPlaybackMath.skip(from: playback.currentTime, by: skipInterval, duration: playback.duration))180 }181 }182 }183 VStack(spacing: 0) {184 if let title, !title.isEmpty {185 Text(verbatim: title)186 .font(theme.font(.caption).weight(.semibold))187 .foregroundStyle(theme.color(.textPrimary))188 .lineLimit(1)189 .padding(.horizontal, theme.spacing.sm)190 .padding(.vertical, theme.spacing.xs)191 .glassSurface(.regular.tinted(.none), in: Capsule())192 .frame(maxWidth: .infinity, alignment: .leading)193 .accessibilityHidden(true)194 }195 Spacer(minLength: 0)196 bar197 }198 .padding(theme.spacing.sm)199 }200 }201202 private var bar: some View {203 HStack(spacing: theme.spacing.sm) {204 Text(verbatim: GlassPlaybackMath.formatted(displayedTime))205 .accessibilityLabel(Text(GlassL10n.string(.elapsedTime)))206 .accessibilityValue(Text(verbatim: GlassPlaybackMath.formatted(displayedTime)))207 GlassScrubber(208 currentTime: playback.currentTime,209 duration: playback.duration,210 tint: theme.color(.textPrimary),211 rail: theme.color(.textPrimary).opacity(0.3),212 scrubTime: Binding(213 get: { scrubTime },214 set: { newValue in215 scrubTime = newValue216 onInteraction()217 }218 )219 ) { playback.seek(to: $0) }220 .disabled(playback.duration <= 0)221 Text(verbatim: GlassPlaybackMath.formattedRemaining(currentTime: displayedTime, duration: playback.duration))222 .accessibilityLabel(Text(GlassL10n.string(.remainingTime)))223 .accessibilityValue(Text(verbatim: GlassPlaybackMath.formatted(GlassPlaybackMath.remaining(currentTime: displayedTime, duration: playback.duration))))224 }225 .font(theme.font(.caption).monospacedDigit())226 .foregroundStyle(theme.color(.textPrimary))227 .padding(.horizontal, theme.spacing.md)228 .padding(.vertical, theme.spacing.xxs)229 .glassSurface(.regular.tinted(.none), in: Capsule())230 }231232 private func roundButton(_ systemImage: String, label: GlassL10n.Key, diameter: CGFloat, symbolSize: CGFloat, action: @escaping @MainActor () -> Void) -> some View {233 Button {234 action()235 onInteraction()236 } label: {237 Image(systemName: systemImage)238 .font(.system(size: symbolSize, weight: .semibold))239 .foregroundStyle(theme.color(.textPrimary))240 .offset(x: systemImage == "play.fill" ? symbolSize * 0.07 : 0)241 .frame(width: diameter, height: diameter)242 .glassSurface(.interactive.tinted(.none), in: Circle())243 .contentShape(Circle())244 }245 .buttonStyle(.plain)246 .accessibilityLabel(Text(GlassL10n.string(label)))247 .help(GlassL10n.string(label))248 }249}250251/// The plate shown in place of a picture that cannot be played.252struct GlassMediaUnavailablePlate: View {253 @GlassThemed private var theme254 let systemImage: String255256 var body: some View {257 VStack(spacing: theme.spacing.sm) {258 Image(systemName: systemImage)259 .font(.system(size: 22, weight: .medium))260 .foregroundStyle(theme.color(.textSecondary))261 .frame(width: 52, height: 52)262 .background(theme.color(.textSecondary).opacity(0.12), in: Circle())263 .accessibilityHidden(true)264 Text(GlassL10n.string(.mediaUnavailable))265 .font(theme.font(.callout).weight(.medium))266 .foregroundStyle(theme.color(.textSecondary))267 .multilineTextAlignment(.center)268 }269 .padding(theme.spacing.md)270 .frame(maxWidth: .infinity, maxHeight: .infinity)271 .background(theme.color(.surface))272 }273}274