SPB Git

Repository Public MIT

GlassVideoPlayer.swift 6.2 KB 161 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMedia/Media/GlassVideoPlayer.swift8// Module           : SPGlassMedia9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// 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 AVKit43import AVFoundation44import SPGlassCore45import SPGlassTokens46import SPGlassThemes4748/// The system video player (`AVKit.VideoPlayer`) with an unavailable state and aspect-ratio handling.49///50/// ```swift51/// GlassVideoPlayer(url: trailerURL, accessibilityLabel: "Trailer")52/// GlassVideoPlayer(player: sharedPlayer, aspectRatio: 4.0 / 3.0)53/// ```54///55/// The controls, picture in picture and full screen are the platform's own. Playback never starts by itself.56/// When there is no player, no item, or the item turns out not to be playable, a "Media unavailable" message57/// takes the place of the player.58public struct GlassVideoPlayer: View {59    private enum Source {60        case player(AVPlayer?)61        case url(URL?)62    }6364    @GlassThemed private var theme65    private let source: Source66    private let aspectRatio: CGFloat?67    private let label: Text68    @State private var ownedPlayer: AVPlayer?69    @State private var isPlayable: Bool?7071    /// Displays a player owned by the host.72    /// - Parameter aspectRatio: width divided by height; `nil` lets the player fill the space it is given.73    public init(player: AVPlayer?, aspectRatio: CGFloat? = 16.0 / 9.0, accessibilityLabel: LocalizedStringKey? = nil) {74        source = .player(player)75        self.aspectRatio = GlassVideoLayout.sanitizedAspectRatio(aspectRatio)76        label = accessibilityLabel.map { Text($0) } ?? Text(GlassL10n.string(.videoPlayer))77    }7879    /// Creates and owns a player for `url`. The player is created when the view appears and released with it.80    public init(url: URL?, aspectRatio: CGFloat? = 16.0 / 9.0, accessibilityLabel: LocalizedStringKey? = nil) {81        source = .url(url)82        self.aspectRatio = GlassVideoLayout.sanitizedAspectRatio(aspectRatio)83        label = accessibilityLabel.map { Text($0) } ?? Text(GlassL10n.string(.videoPlayer))84    }8586    public var body: some View {87        content88            .aspectRatio(aspectRatio, contentMode: .fit)89            .task(id: sourceIdentity) { await prepare() }90    }9192    @ViewBuilder93    private var content: some View {94        let player = activePlayer95        switch GlassVideoAvailability.resolve(hasPlayer: player != nil, hasItem: player?.currentItem != nil, isPlayable: isPlayable) {96        case .available, .checking:97            VideoPlayer(player: player)98                .accessibilityLabel(label)99        case .unavailable:100            GlassMediaUnavailablePlate(systemImage: "video.slash")101                .clipShape(theme.shape(\.large))102                .overlay(theme.shape(\.large).strokeBorder(theme.color(.separator), lineWidth: 0.5))103                .accessibilityElement(children: .combine)104            .accessibilityLabel(label)105            .accessibilityValue(Text(GlassL10n.string(.mediaUnavailable)))106        }107    }108109    private var activePlayer: AVPlayer? {110        switch source {111        case .player(let player): player112        case .url: ownedPlayer113        }114    }115116    private var sourceIdentity: String {117        switch source {118        case .player(let player): player.map { "player-\(ObjectIdentifier($0).hashValue)" } ?? "player-none"119        case .url(let url): url?.absoluteString ?? "url-none"120        }121    }122123    private func prepare() async {124        isPlayable = nil125        if case .url(let url) = source {126            ownedPlayer = url.map { AVPlayer(playerItem: AVPlayerItem(url: $0)) }127        }128        guard let asset = activePlayer?.currentItem?.asset else { return }129        let playable = (try? await asset.load(.isPlayable)) ?? false130        if !Task.isCancelled { isPlayable = playable }131    }132}133134/// Whether a ``GlassVideoPlayer`` can show its player.135public enum GlassVideoAvailability: Equatable, Sendable {136    /// The item is known to be playable.137    case available138    /// There is an item whose playability is still being loaded; the player is shown meanwhile.139    case checking140    /// No player, no item, or an item that cannot be played.141    case unavailable142143    public static func resolve(hasPlayer: Bool, hasItem: Bool, isPlayable: Bool?) -> GlassVideoAvailability {144        guard hasPlayer, hasItem else { return .unavailable }145        switch isPlayable {146        case .some(true): return .available147        case .some(false): return .unavailable148        case .none: return .checking149        }150    }151}152153/// Layout rules of ``GlassVideoPlayer``.154public enum GlassVideoLayout {155    /// A usable aspect ratio: `nil` for missing, non-finite or non-positive values, clamped to 1:4…4:1 otherwise.156    public static func sanitizedAspectRatio(_ ratio: CGFloat?) -> CGFloat? {157        guard let ratio, ratio.isFinite, ratio > 0 else { return nil }158        return min(max(ratio, 0.25), 4)159    }160}161
Files main
Menu

Theme