Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Descriptors/MediaDescriptors.swift8// Module : GlassStudio9// 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 AVFoundation43import SPGlassKit44import SPGlassExamples4546extension ComponentCatalog {47 static var mediaDescriptors: [ComponentDescriptor] {48 [glassAudioPlayer, glassVideoPlayer, glassVolumeControl, glassGallery, glassWaveform]49 }5051 // MARK: Audio player5253 private static let skipIntervals = ["5", "10", "15", "30", "45", "60"]5455 private static var glassAudioPlayer: ComponentDescriptor {56 ComponentDescriptor(57 "glass-audio-player",58 fields: [59 .text("title", "Title", default: "Harbour Lines", maxLength: 60),60 .text("subtitle", "Subtitle", default: "The Slow Coast · Episode 12", maxLength: 80),61 .choice("style", "Style", options: [.init("expanded", "Expanded"), .init("compact", "Compact")]),62 .choice("skip", "Skip interval", options: skipIntervals.map { .init($0, "\($0) s") }, default: "15"),63 .toggle("artwork", "Artwork", default: true),64 .toggle("waveform", "Waveform"),65 .toggle("available", "Playable", default: true),66 ],67 variants: [68 ComponentVariant("compact", "Compact", ["style": .choice("compact")]),69 ComponentVariant("waveform", "Waveform", ["waveform": .bool(true), "skip": .choice("30")]),70 ComponentVariant("plain", "No artwork", ["artwork": .bool(false), "subtitle": .text("")]),71 ComponentVariant("unavailable", "Unavailable", ["available": .bool(false), "title": .text("Missing recording"), "subtitle": .text("The file is no longer on this device")]),72 ],73 isComposable: true,74 prefersStage: true,75 preview: { values in76 SilentAudioPreview(77 title: values.text("title"),78 subtitle: values.text("subtitle"),79 skipInterval: Double(values.choice("skip")) ?? 15,80 isAvailable: values.bool("available"),81 showsArtwork: values.bool("artwork"),82 showsWaveform: values.bool("waveform"),83 style: GlassAudioPlayerStyle(rawValue: values.choice("style")) ?? .expanded84 )85 .id(values)86 },87 snippet: { values in88 let available = values.bool("available")89 var arguments = ["playback: GlassAVAudioPlayback(url: URL(fileURLWithPath: \(available ? "\"/path/to/episode.m4a\"" : "\"/path/to/missing.m4a\"")))"]90 if !values.text("title").isEmpty { arguments.append("title: \(SwiftLiteral.string(values.text("title")))") }91 if !values.text("subtitle").isEmpty { arguments.append("subtitle: \(SwiftLiteral.string(values.text("subtitle")))") }92 if values.choice("skip") != "15", skipIntervals.contains(values.choice("skip")) { arguments.append("skipInterval: \(values.choice("skip"))") }93 if values.bool("artwork") { arguments.append("artwork: Image(\"cover\")") }94 if values.bool("waveform") { arguments.append("waveform: GlassWaveformData(samples: (0..<600).map { Float(sin(Double($0) * 0.21)) })") }95 if values.choice("style") == "compact" { arguments.append("style: .compact") }96 let comment = available97 ? "// Keep the playback in @State in a real view and give it your own audio file."98 : "// A playback whose item cannot be played reports isAvailable == false: the unavailable state is shown."99 return "\(comment)\nGlassAudioPlayer(\n\(arguments.map { " " + $0 }.joined(separator: ",\n"))\n)"100 }101 )102 }103104 // MARK: Video player105106 private static func aspectRatio(_ id: String) -> CGFloat? {107 switch id {108 case "4x3": 4.0 / 3.0109 case "1x1": 1110 case "fill": nil111 default: 16.0 / 9.0112 }113 }114115 private static var glassVideoPlayer: ComponentDescriptor {116 ComponentDescriptor(117 "glass-video-player",118 fields: [119 .choice("source", "Source", options: [120 .init("poster", "Drawn poster, glass controls"), .init("missingURL", "Missing URL"),121 .init("noPlayer", "No player"), .init("emptyPlayer", "Player without an item"),122 ]),123 .choice("aspect", "Aspect ratio", options: [.init("16x9", "16:9"), .init("4x3", "4:3"), .init("1x1", "1:1"), .init("fill", "Fill the space")]),124 .text("label", "Title", default: "The Shore House · Trailer", maxLength: 60),125 ],126 variants: [127 ComponentVariant("classic", "4:3", ["aspect": .choice("4x3"), "label": .text("Studio visit · Part 2")]),128 ComponentVariant("unavailable", "Unavailable", ["source": .choice("missingURL")]),129 ComponentVariant("emptyPlayer", "Player without an item", ["source": .choice("emptyPlayer")]),130 ComponentVariant("fill", "Fill the space", ["aspect": .choice("fill")]),131 ],132 prefersStage: false,133 preview: { values in134 VideoPreview(source: values.choice("source"), aspectRatio: aspectRatio(values.choice("aspect")), label: values.text("label"))135 .frame(maxWidth: 520, maxHeight: 420)136 .id(values)137 },138 snippet: { values in139 var arguments: [String]140 var requirement = ""141 let source = values.choice("source")142 switch source {143 case "emptyPlayer":144 requirement = "// Requires: import AVKit\n"145 arguments = ["player: AVPlayer()"]146 case "noPlayer":147 arguments = ["player: nil"]148 case "missingURL":149 arguments = ["url: nil"]150 default:151 arguments = ["playback: GlassAVAudioPlayback(url: URL(fileURLWithPath: \"/path/to/trailer.mp4\"))"]152 if !values.text("label").isEmpty { arguments.append("title: \(SwiftLiteral.string(values.text("label")))") }153 }154 switch values.choice("aspect") {155 case "4x3": arguments.append("aspectRatio: 4.0 / 3.0")156 case "1x1": arguments.append("aspectRatio: 1")157 case "fill": arguments.append("aspectRatio: nil")158 default: break159 }160 if ["emptyPlayer", "noPlayer", "missingURL"].contains(source) {161 if !values.text("label").isEmpty { arguments.append("accessibilityLabel: \(SwiftLiteral.string(values.text("label")))") }162 return "\(requirement)// Give the player a real URL to get the system controls.\nGlassVideoPlayer(\(arguments.joined(separator: ", ")))"163 }164 return """165 // Glass controls over a picture you draw. For the system player use GlassVideoPlayer(url:).166 GlassVideoControls(\(arguments.joined(separator: ", "))) {167 Color.black // replace with your player layer or a poster image168 }169 """170 }171 )172 }173174 // MARK: Volume control175176 private static var glassVolumeControl: ComponentDescriptor {177 ComponentDescriptor(178 "glass-volume-control",179 fields: [180 .number("volume", "Volume", in: 0...1, step: 0.05, default: 0.65),181 .number("unmute", "Unmute level", in: 0...1, step: 0.05, default: 0.5),182 .toggle("value", "Show the percentage", default: true),183 .toggle("disabled", "Disabled"),184 ],185 variants: [186 ComponentVariant("muted", "Muted", ["volume": .number(0), "unmute": .number(0.4)]),187 ComponentVariant("full", "Full volume", ["volume": .number(1)]),188 ComponentVariant("bare", "Without the percentage", ["value": .bool(false)]),189 ComponentVariant("disabled", "Disabled", ["volume": .number(0.25), "disabled": .bool(true)]),190 ],191 isComposable: true,192 prefersStage: false,193 preview: { values in194 MediaPreviewState(values.number("volume")) { volume in195 VolumeScene {196 GlassVolumeControl(volume: volume, unmuteLevel: values.number("unmute"), showsValue: values.bool("value"))197 .disabled(values.bool("disabled"))198 }199 }200 .id(values)201 },202 snippet: { values in203 var arguments = ["volume: .constant(\(SwiftLiteral.number(values.number("volume"))))"]204 if abs(values.number("unmute") - GlassVolumeState.defaultUnmuteLevel) > 0.001 { arguments.append("unmuteLevel: \(SwiftLiteral.number(values.number("unmute")))") }205 if values.bool("value") { arguments.append("showsValue: true") }206 var code = "GlassVolumeControl(\(arguments.joined(separator: ", ")))"207 if values.bool("disabled") { code += "\n.disabled(true)" }208 return code209 }210 )211 }212213 // MARK: Gallery214215 @MainActor216 private static func galleryItems(count: Int, includesFailure: Bool) -> [GlassGalleryItem] {217 var items = (0..<min(count, SampleArtwork.count)).map { index in218 GlassGalleryItem(id: "photo-\(index + 1)", description: SampleArtwork.title(index), image: SampleArtwork.image(index))219 }220 if includesFailure {221 items.append(GlassGalleryItem(id: "broken", description: "An image that fails to load", load: { throw URLError(.fileDoesNotExist) }))222 }223 return items224 }225226 private static var glassGallery: ComponentDescriptor {227 ComponentDescriptor(228 "glass-gallery",229 fields: [230 .number("count", "Images", in: 0...12, default: 9),231 .choice("layout", "Layout", options: [.init("featured", "Featured"), .init("grid", "Grid")]),232 .number("cell", "Minimum cell width", in: 72...160, step: 8, default: 104),233 .toggle("selected", "Outline the second image", default: true),234 .toggle("failing", "Include a failing image"),235 ],236 variants: [237 ComponentVariant("grid", "Grid", ["layout": .choice("grid"), "count": .number(12), "selected": .bool(false)]),238 ComponentVariant("large", "Large cells", ["layout": .choice("grid"), "cell": .number(152), "count": .number(4)]),239 ComponentVariant("failing", "Failed image", ["failing": .bool(true), "count": .number(5), "layout": .choice("grid")]),240 ComponentVariant("empty", "Empty", ["count": .number(0)]),241 ],242 prefersStage: false,243 preview: { values in244 GlassGallery(245 items: galleryItems(count: Int(values.number("count")), includesFailure: values.bool("failing")),246 minimumCellWidth: values.number("cell"),247 layout: GlassGalleryLayout(rawValue: values.choice("layout")) ?? .featured,248 selection: values.bool("selected") ? "photo-2" : nil249 )250 .frame(maxWidth: 520, maxHeight: 500)251 .id(values)252 },253 snippet: { values in254 let count = min(Int(values.number("count")), SampleArtwork.count)255 var lines = (0..<count).map { index in256 " GlassGalleryItem(id: \"photo-\(index + 1)\", description: \(SwiftLiteral.string(SampleArtwork.title(index))), image: Image(\"photo-\(index + 1)\")),"257 }258 if values.bool("failing") {259 lines.append(" GlassGalleryItem(id: \"broken\", description: \"An image that fails to load\", load: { throw URLError(.fileDoesNotExist) }),")260 }261 var arguments = ["items: " + (lines.isEmpty ? "[]" : "[\n\(lines.joined(separator: "\n"))\n]")]262 if values.number("cell") != 104 { arguments.append("minimumCellWidth: \(SwiftLiteral.number(values.number("cell")))") }263 if values.choice("layout") != "grid" { arguments.append("layout: .featured") }264 if values.bool("selected") { arguments.append("selection: \"photo-2\"") }265 return "// Image(\"photo-1\") stands for an image of your asset catalogue.\nGlassGallery(\(arguments.joined(separator: ", ")))"266 }267 )268 }269270 // MARK: Waveform271272 /// A deterministic synthetic signal shaped like speech; the snippet contains the same expression.273 private static let waveformSamples: [Float] = (0..<4_800).map { index -> Float in274 let x = Double(index)275 let envelope: Double = 0.25 + 0.75 * abs(sin(x / 310) * sin(x / 97 + 1.3))276 return Float(sin(x * 0.21) * envelope)277 }278279 /// Length of the fictitious recording the waveform row shows.280 private static let waveformDuration: TimeInterval = 215281282 private static var glassWaveform: ComponentDescriptor {283 ComponentDescriptor(284 "glass-waveform",285 fields: [286 .number("buckets", "Bars", in: 16...160, step: 8, default: 72),287 .choice("aggregation", "Aggregation", options: [.init("peak", "Peak"), .init("rms", "RMS")]),288 .toggle("showsProgress", "Show progress", default: true),289 .number("progress", "Progress", in: 0...1, step: 0.05, default: 0.35),290 .toggle("playhead", "Playhead", default: true),291 .number("height", "Minimum height", in: 24...120, step: 8, default: 56),292 ],293 variants: [294 ComponentVariant("rms", "RMS", ["aggregation": .choice("rms")]),295 ComponentVariant("plain", "No progress", ["showsProgress": .bool(false), "buckets": .number(120)]),296 ComponentVariant("tall", "Tall", ["height": .number(96), "progress": .number(0.75), "playhead": .bool(false)]),297 ],298 isComposable: true,299 prefersStage: false,300 preview: { values in301 let progress = values.bool("showsProgress") ? values.number("progress") : nil302 WaveformRow(progress: progress, duration: waveformDuration) {303 GlassWaveform(304 samples: waveformSamples,305 maxBuckets: Int(values.number("buckets")),306 aggregation: GlassWaveformAggregation(rawValue: values.choice("aggregation")) ?? .peak,307 progress: progress,308 minimumHeight: values.number("height"),309 showsPlayhead: values.bool("playhead")310 )311 .fixedSize(horizontal: false, vertical: true)312 }313 },314 snippet: { values in315 var arguments = ["samples: samples"]316 if values.number("buckets") != 120 { arguments.append("maxBuckets: \(SwiftLiteral.number(values.number("buckets")))") }317 if values.choice("aggregation") == "rms" { arguments.append("aggregation: .rms") }318 if values.bool("showsProgress") { arguments.append("progress: \(SwiftLiteral.number(values.number("progress")))") }319 if values.number("height") != 48 { arguments.append("minimumHeight: \(SwiftLiteral.number(values.number("height")))") }320 if !values.bool("playhead") { arguments.append("showsPlayhead: false") }321 return """322 // Synthetic samples: replace them with the amplitudes of your recording.323 let samples: [Float] = (0..<4_800).map { index in324 let x = Double(index)325 let envelope: Double = 0.25 + 0.75 * abs(sin(x / 310) * sin(x / 97 + 1.3))326 return Float(sin(x * 0.21) * envelope)327 }328 GlassWaveform(329 \(arguments.map { " " + $0 }.joined(separator: ",\n"))330 )331 """332 }333 )334 }335}336337// MARK: - Preview support338339/// Holds a value the previewed component edits through a binding.340private struct MediaPreviewState<Value, Content: View>: View {341 @State private var value: Value342 private let content: (Binding<Value>) -> Content343344 init(_ initialValue: Value, @ViewBuilder content: @escaping (Binding<Value>) -> Content) {345 _value = State(initialValue: initialValue)346 self.content = content347 }348349 var body: some View { content($value) }350}351352/// A playback engine without audio: it only moves a clock.353@MainActor354@Observable355private final class SilentPlayback: GlassAudioPlayback {356 private(set) var isPlaying = false357 private(set) var currentTime: TimeInterval358 let duration: TimeInterval359 let isAvailable: Bool360361 init(isAvailable: Bool, duration: TimeInterval = 215, position: TimeInterval = 76) {362 self.isAvailable = isAvailable363 self.duration = isAvailable ? duration : 0364 currentTime = isAvailable ? position : 0365 }366367 func play() {368 guard isAvailable else { return }369 if currentTime >= duration { currentTime = 0 }370 isPlaying = true371 }372373 func pause() { isPlaying = false }374375 func seek(to time: TimeInterval) {376 currentTime = GlassPlaybackMath.clampedSeek(time, duration: duration)377 }378379 func advance(by seconds: TimeInterval) {380 currentTime = GlassPlaybackMath.clampedSeek(currentTime + seconds, duration: duration)381 if currentTime >= duration { isPlaying = false }382 }383}384385/// Ticks a silent playback while it is "playing": no audio clock exists.386private struct SilentClock: ViewModifier {387 let playback: SilentPlayback388389 func body(content: Content) -> some View {390 content.task(id: playback.isPlaying) {391 while playback.isPlaying, !Task.isCancelled {392 try? await Task.sleep(for: .milliseconds(500))393 if !Task.isCancelled { playback.advance(by: 0.5) }394 }395 }396 }397}398399private struct SilentAudioPreview: View {400 let title: String401 let subtitle: String402 let skipInterval: TimeInterval403 let showsArtwork: Bool404 let showsWaveform: Bool405 let style: GlassAudioPlayerStyle406 @State private var playback: SilentPlayback407408 /// Amplitudes of a fictitious recording, built once.409 private static let waveform = GlassWaveformData(410 samples: (0..<2_400).map { index -> Float in411 let x = Double(index)412 let envelope: Double = 0.25 + 0.75 * abs(sin(x / 170) * sin(x / 61 + 0.8))413 return Float(sin(x * 0.37) * envelope)414 },415 maxBuckets: 64416 )417418 init(title: String, subtitle: String, skipInterval: TimeInterval, isAvailable: Bool, showsArtwork: Bool, showsWaveform: Bool, style: GlassAudioPlayerStyle) {419 self.title = title420 self.subtitle = subtitle421 self.skipInterval = skipInterval422 self.showsArtwork = showsArtwork423 self.showsWaveform = showsWaveform424 self.style = style425 _playback = State(initialValue: SilentPlayback(isAvailable: isAvailable))426 }427428 var body: some View {429 GlassAudioPlayer(430 playback: playback,431 title: title.isEmpty ? nil : title,432 subtitle: subtitle.isEmpty ? nil : subtitle,433 skipInterval: skipInterval,434 artwork: showsArtwork ? SampleArtwork.image(1) : nil,435 waveform: showsWaveform ? Self.waveform : nil,436 style: style437 )438 .frame(maxWidth: 420)439 .modifier(SilentClock(playback: playback))440 }441}442443/// The video component: glass controls over a drawn poster (no media file is bundled), or the player in the444/// states that need no media either: no URL, no player, a player without an item.445private struct VideoPreview: View {446 let source: String447 let aspectRatio: CGFloat?448 let label: String449 @State private var emptyPlayer: AVPlayer?450 @State private var playback = SilentPlayback(isAvailable: true, duration: 134, position: 48)451452 init(source: String, aspectRatio: CGFloat?, label: String) {453 self.source = source454 self.aspectRatio = aspectRatio455 self.label = label456 _emptyPlayer = State(initialValue: source == "emptyPlayer" ? AVPlayer() : nil)457 }458459 private var accessibilityLabel: LocalizedStringKey? {460 label.isEmpty ? nil : LocalizedStringKey(label)461 }462463 var body: some View {464 switch source {465 case "missingURL":466 GlassVideoPlayer(url: nil, aspectRatio: aspectRatio, accessibilityLabel: accessibilityLabel)467 case "noPlayer", "emptyPlayer":468 GlassVideoPlayer(player: emptyPlayer, aspectRatio: aspectRatio, accessibilityLabel: accessibilityLabel)469 default:470 GlassVideoControls(playback: playback, title: label.isEmpty ? nil : label, aspectRatio: aspectRatio) {471 SampleArtwork(3)472 }473 .modifier(SilentClock(playback: playback))474 }475 }476}477478/// The volume control where it lives: in a glass capsule over the artwork of what is playing.479private struct VolumeScene<Control: View>: View {480 @GlassThemed private var theme481 @ViewBuilder let control: Control482483 var body: some View {484 SampleArtwork(6)485 .aspectRatio(4.0 / 3.0, contentMode: .fit)486 .overlay(alignment: .bottom) {487 control488 .padding(.leading, theme.spacing.sm)489 .padding(.trailing, theme.spacing.md)490 .glassSurface(.regular.tinted(.none), in: Capsule())491 .padding(theme.spacing.sm)492 }493 .clipShape(theme.shape(\.large))494 .overlay(theme.shape(\.large).strokeBorder(theme.color(.separator).opacity(0.6), lineWidth: 0.5))495 .frame(maxWidth: 420)496 }497}498499/// The waveform in a finished row: what the recording is, the bars, and both times underneath.500private struct WaveformRow<Waveform: View>: View {501 @GlassThemed private var theme502 let progress: Double?503 let duration: TimeInterval504 @ViewBuilder let waveform: Waveform505506 var body: some View {507 VStack(alignment: .leading, spacing: theme.spacing.sm) {508 HStack(spacing: theme.spacing.sm) {509 Image(systemName: "mic.fill")510 .font(.system(size: 16, weight: .semibold))511 .foregroundStyle(theme.color(.primary))512 .frame(width: 40, height: 40)513 .background(theme.color(.primary).opacity(theme.isDark ? 0.24 : 0.12), in: RoundedRectangle(cornerRadius: 11, style: .continuous))514 .accessibilityHidden(true)515 VStack(alignment: .leading, spacing: 2) {516 Text(verbatim: "Site visit, north stair")517 .font(theme.font(.headline))518 .foregroundStyle(theme.color(.textPrimary))519 Text(verbatim: "Voice memo · 14 March")520 .font(theme.font(.caption))521 .foregroundStyle(theme.color(.textSecondary))522 }523 Spacer(minLength: 0)524 }525 waveform526 HStack {527 Text(verbatim: GlassPlaybackMath.formatted((progress ?? 0) * duration))528 Spacer()529 Text(verbatim: GlassPlaybackMath.formatted(duration))530 }531 .font(theme.font(.caption).monospacedDigit())532 .foregroundStyle(theme.color(.textSecondary))533 }534 .padding(theme.spacing.md)535 .glassOpaqueSurface(in: theme.shape(\.large), elevated: true)536 .frame(maxWidth: 420)537 }538}539