301 lines
15 KiB
Swift
301 lines
15 KiB
Swift
import Kingfisher
|
|
import AVFoundation
|
|
import AVKit
|
|
import SnapKit
|
|
import UIKit
|
|
|
|
/// 景区空境视频预览,正式素材播放服务端地址,Debug 素材保留本地预览。
|
|
@MainActor
|
|
final class ScenicMaterialPreviewViewController: UIViewController {
|
|
private let clip: ScenicMaterialClip
|
|
private let routeName: String
|
|
private let capturedAt: Date
|
|
private let calendar: Calendar
|
|
private let playerController = AVPlayerViewController()
|
|
private let contentView = UIView()
|
|
private let coverView = UIImageView()
|
|
private let playButton = UIButton(type: .system)
|
|
private let playbackStatus = ScenicMaterialsStyle.label(size: 13, color: ScenicMaterialsStyle.secondary)
|
|
private let playbackTime = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
|
|
private let progressView = UIProgressView(progressViewStyle: .bar)
|
|
private var playbackTask: Task<Void, Never>?
|
|
private var playbackObservation: ScenicMaterialPlaybackObservation?
|
|
private var playbackGeneration = UUID()
|
|
private var playbackDuration: Double?
|
|
private var playbackFinished = false
|
|
|
|
/// 预览指定片段,原片元信息与本地演示视频时长明确区分。
|
|
init(clip: ScenicMaterialClip, routeName: String, capturedAt: Date, calendar: Calendar = .current) {
|
|
self.clip = clip
|
|
self.routeName = routeName
|
|
self.capturedAt = capturedAt
|
|
self.calendar = calendar
|
|
super.init(nibName: nil, bundle: nil)
|
|
modalPresentationStyle = .pageSheet
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
setupUI()
|
|
sheetPresentationController?.detents = [.custom { [weak self] context in
|
|
guard let self else { return min(context.maximumDetentValue, 490) }
|
|
let width = max(self.view.bounds.width, 320)
|
|
let fittingSize = self.contentView.systemLayoutSizeFitting(
|
|
CGSize(width: width, height: UIView.layoutFittingCompressedSize.height),
|
|
withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
|
|
return min(context.maximumDetentValue, fittingSize.height)
|
|
}]
|
|
sheetPresentationController?.prefersGrabberVisible = true
|
|
sheetPresentationController?.preferredCornerRadius = 22
|
|
NotificationCenter.default.addObserver(self, selector: #selector(pausePlayback),
|
|
name: UIApplication.willResignActiveNotification, object: nil)
|
|
}
|
|
|
|
override func viewWillDisappear(_ animated: Bool) {
|
|
super.viewWillDisappear(animated)
|
|
pausePlayback()
|
|
}
|
|
|
|
override func viewDidDisappear(_ animated: Bool) {
|
|
super.viewDidDisappear(animated)
|
|
stopPlayback()
|
|
}
|
|
|
|
private func setupUI() {
|
|
view.backgroundColor = .white
|
|
view.accessibilityIdentifier = "scenic.materials.preview.sheet"
|
|
let title = ScenicMaterialsStyle.label("视频预览", size: 18, weight: .semibold)
|
|
let mediaContainer = UIView()
|
|
mediaContainer.backgroundColor = .black
|
|
mediaContainer.layer.cornerRadius = 10
|
|
mediaContainer.clipsToBounds = true
|
|
mediaContainer.accessibilityIdentifier = "scenic.materials.preview.media"
|
|
if clip.isRemote {
|
|
coverView.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo"))
|
|
playbackStatus.text = "点击播放原片"
|
|
} else {
|
|
coverView.image = UIImage(named: clip.coverAssetName)
|
|
playbackStatus.text = "本地演示短片 · 非真实景区视频"
|
|
}
|
|
coverView.contentMode = .scaleAspectFill
|
|
coverView.clipsToBounds = true
|
|
playButton.tintColor = .white
|
|
playButton.accessibilityIdentifier = "scenic.materials.preview.play"
|
|
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
|
|
updatePlayButton(isPlaying: false)
|
|
playbackStatus.numberOfLines = 2
|
|
progressView.progressTintColor = ScenicMaterialsStyle.primary
|
|
progressView.trackTintColor = ScenicMaterialsStyle.border
|
|
progressView.accessibilityIdentifier = "scenic.materials.preview.progress"
|
|
progressView.accessibilityLabel = "播放进度"
|
|
playbackTime.accessibilityIdentifier = "scenic.materials.preview.playbackTime"
|
|
resetPlaybackTime()
|
|
let metadata = ScenicMaterialsStyle.label("\(clip.durationText) · \(clip.sizeText)", size: 11, color: ScenicMaterialsStyle.secondary)
|
|
metadata.numberOfLines = 2
|
|
metadata.textAlignment = .right
|
|
metadata.accessibilityIdentifier = "scenic.materials.preview.metadata"
|
|
let timeline = UIStackView(arrangedSubviews: [playbackTime, metadata])
|
|
timeline.alignment = .top
|
|
timeline.distribution = .fillEqually
|
|
timeline.spacing = 8
|
|
let route = ScenicMaterialsStyle.label(routeName, size: 16, weight: .semibold)
|
|
route.numberOfLines = 2
|
|
route.accessibilityIdentifier = "scenic.materials.preview.route"
|
|
let formatter = DateFormatter()
|
|
formatter.calendar = calendar
|
|
formatter.timeZone = calendar.timeZone
|
|
formatter.locale = Locale(identifier: "zh_CN")
|
|
formatter.dateFormat = "MM-dd HH:mm"
|
|
let time = ScenicMaterialsStyle.label("\(formatter.string(from: capturedAt)) · 片段 \(clip.ordinal)", size: 12, color: ScenicMaterialsStyle.secondary)
|
|
time.accessibilityIdentifier = "scenic.materials.preview.capturedAt"
|
|
let done = UIButton(type: .system)
|
|
done.setTitle("返回素材列表", for: .normal)
|
|
done.setTitleColor(.white, for: .normal)
|
|
done.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
|
|
done.backgroundColor = ScenicMaterialsStyle.primary
|
|
done.layer.cornerRadius = 10
|
|
done.accessibilityIdentifier = "scenic.materials.preview.done"
|
|
done.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
|
let scroll = UIScrollView()
|
|
view.addSubview(scroll)
|
|
scroll.addSubview(contentView)
|
|
[title, playbackStatus, mediaContainer, progressView, timeline, route, time, done].forEach(contentView.addSubview)
|
|
addChild(playerController)
|
|
playerController.view.backgroundColor = .black
|
|
playerController.view.isHidden = true
|
|
playerController.showsPlaybackControls = false
|
|
playerController.allowsPictureInPicturePlayback = false
|
|
mediaContainer.addSubview(playerController.view)
|
|
playerController.didMove(toParent: self)
|
|
mediaContainer.addSubview(coverView)
|
|
mediaContainer.addSubview(playButton)
|
|
scroll.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
|
|
contentView.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
|
|
title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.trailing.equalToSuperview().inset(18) }
|
|
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(6); $0.leading.trailing.equalTo(title) }
|
|
mediaContainer.snp.makeConstraints {
|
|
$0.top.equalTo(playbackStatus.snp.bottom).offset(18)
|
|
$0.leading.trailing.equalTo(title)
|
|
$0.height.equalTo(mediaContainer.snp.width).multipliedBy(9.0 / 16.0)
|
|
}
|
|
playerController.view.snp.makeConstraints { $0.edges.equalToSuperview() }
|
|
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
|
|
playButton.snp.makeConstraints { $0.center.equalToSuperview(); $0.size.equalTo(44) }
|
|
progressView.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(16); $0.leading.trailing.equalTo(mediaContainer); $0.height.equalTo(3) }
|
|
timeline.snp.makeConstraints { $0.top.equalTo(progressView.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
|
|
route.snp.makeConstraints { $0.top.equalTo(timeline.snp.bottom).offset(22); $0.leading.trailing.equalTo(mediaContainer) }
|
|
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(7); $0.leading.trailing.equalTo(mediaContainer) }
|
|
done.snp.makeConstraints {
|
|
$0.top.equalTo(time.snp.bottom).offset(20)
|
|
$0.leading.trailing.equalTo(mediaContainer)
|
|
$0.height.equalTo(46)
|
|
$0.bottom.equalToSuperview().inset(18)
|
|
}
|
|
}
|
|
|
|
@objc private func playTapped() {
|
|
guard playbackTask == nil, clip.isAvailable else { return }
|
|
if let player = playerController.player {
|
|
if player.rate > 0 {
|
|
pausePlayback()
|
|
} else {
|
|
if playbackFinished { player.seek(to: .zero); playbackFinished = false }
|
|
player.play()
|
|
updatePlayButton(isPlaying: true)
|
|
updatePlayingStatus()
|
|
}
|
|
return
|
|
}
|
|
let demoURL = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
|
|
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock")
|
|
guard let url = clip.isRemote ? clip.remoteURL : demoURL else {
|
|
playbackStatus.text = "视频地址暂不可用"
|
|
return
|
|
}
|
|
playButton.isEnabled = false
|
|
playbackGeneration = UUID()
|
|
let generation = playbackGeneration
|
|
playbackTask = Task { @MainActor [weak self] in
|
|
let asset = AVURLAsset(url: url)
|
|
let playable = (try? await asset.load(.isPlayable)) == true
|
|
let duration = try? await asset.load(.duration)
|
|
guard let self, self.playbackGeneration == generation else { return }
|
|
self.playbackTask = nil
|
|
self.playButton.isEnabled = true
|
|
guard !Task.isCancelled, self.view.window != nil else { return }
|
|
guard playable else {
|
|
self.playbackStatus.text = "视频暂不可播放,请稍后重试"
|
|
return
|
|
}
|
|
let seconds = duration?.seconds ?? .nan
|
|
self.playbackDuration = seconds.isFinite && seconds > 0 ? seconds : nil
|
|
let player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
|
|
self.playerController.player = player
|
|
self.playerController.view.isHidden = false
|
|
self.coverView.isHidden = true
|
|
self.playbackFinished = false
|
|
self.playbackObservation = ScenicMaterialPlaybackObservation(player: player) { [weak self] time in
|
|
Task { @MainActor [weak self] in
|
|
guard let self, self.playbackGeneration == generation else { return }
|
|
self.updatePlaybackProgress(time)
|
|
}
|
|
}
|
|
NotificationCenter.default.addObserver(self, selector: #selector(playbackEnded),
|
|
name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
|
|
self.updatePlaybackProgress(.zero)
|
|
self.updatePlayingStatus()
|
|
self.updatePlayButton(isPlaying: true)
|
|
player.play()
|
|
}
|
|
}
|
|
|
|
private func updatePlaybackProgress(_ time: CMTime) {
|
|
let seconds = time.seconds.isFinite ? max(time.seconds, 0) : 0
|
|
progressView.progress = playbackDuration.map { Float(min(seconds / $0, 1)) } ?? 0
|
|
let total = playbackDuration.map(Self.durationText) ?? "时长未知"
|
|
playbackTime.text = "\(Self.durationText(seconds)) / \(total)"
|
|
}
|
|
|
|
private func updatePlayingStatus() {
|
|
if clip.isRemote {
|
|
playbackStatus.text = "正在播放原片"
|
|
} else if let duration = playbackDuration {
|
|
playbackStatus.text = "正在播放 \(Int(duration.rounded())) 秒本地演示 · 原片 \(clip.durationText)"
|
|
} else {
|
|
playbackStatus.text = "正在播放本地演示 · 原片 \(clip.durationText)"
|
|
}
|
|
}
|
|
|
|
private func updatePlayButton(isPlaying: Bool) {
|
|
let symbol = isPlaying ? "pause.fill" : "play.fill"
|
|
playButton.setImage(UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 24)), for: .normal)
|
|
playButton.accessibilityLabel = isPlaying ? "暂停播放" : (clip.isRemote ? "播放景区视频" : "播放本地演示视频")
|
|
}
|
|
|
|
private func resetPlaybackTime() {
|
|
playbackTime.text = "00:00 / \(clip.isRemote ? "" : "原片 ")\(clip.durationText)"
|
|
}
|
|
|
|
private static func durationText(_ seconds: Double) -> String {
|
|
let value = max(Int(seconds), 0)
|
|
return String(format: "%02d:%02d", value / 60, value % 60)
|
|
}
|
|
|
|
@objc private func playbackEnded() {
|
|
playbackFinished = true
|
|
if let duration = playbackDuration { updatePlaybackProgress(CMTime(seconds: duration, preferredTimescale: 600)) }
|
|
updatePlayButton(isPlaying: false)
|
|
playbackStatus.text = clip.isRemote ? "播放结束,点击重新播放" : "本地演示已结束 · 原片 \(clip.durationText)"
|
|
}
|
|
|
|
@objc private func pausePlayback() {
|
|
playerController.player?.pause()
|
|
if playbackTask != nil {
|
|
playbackGeneration = UUID()
|
|
playbackTask?.cancel()
|
|
playbackTask = nil
|
|
playButton.isEnabled = true
|
|
}
|
|
updatePlayButton(isPlaying: false)
|
|
if playerController.player != nil {
|
|
playbackStatus.text = clip.isRemote ? "已暂停,点击继续播放" : "本地演示已暂停 · 原片 \(clip.durationText)"
|
|
}
|
|
}
|
|
|
|
private func stopPlayback() {
|
|
pausePlayback()
|
|
playbackGeneration = UUID()
|
|
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)
|
|
playbackObservation = nil
|
|
playerController.player = nil
|
|
playerController.view.isHidden = true
|
|
coverView.isHidden = false
|
|
playbackDuration = nil
|
|
playbackFinished = false
|
|
progressView.progress = 0
|
|
resetPlaybackTime()
|
|
}
|
|
|
|
@objc private func closeTapped() {
|
|
stopPlayback()
|
|
dismiss(animated: true)
|
|
}
|
|
}
|
|
|
|
/// 与播放器成对持有周期观察令牌,释放时移除观察,避免弹窗销毁后残留定时回调。
|
|
private final class ScenicMaterialPlaybackObservation {
|
|
private let player: AVPlayer
|
|
private let token: Any
|
|
|
|
init(player: AVPlayer, onTime: @escaping @Sendable (CMTime) -> Void) {
|
|
self.player = player
|
|
token = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.1, preferredTimescale: 600),
|
|
queue: .main, using: onTime)
|
|
}
|
|
|
|
deinit { player.removeTimeObserver(token) }
|
|
}
|