VideoPreviewCollectionViewCell.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import CocoaLumberjackSwift
  21. class VideoImageCell: UICollectionViewCell, UIGestureRecognizerDelegate {
  22. @IBOutlet weak var videoBackgroundView: UIView!
  23. @IBOutlet weak var loadingView: UIView!
  24. @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  25. @IBOutlet weak var loadingVideoText: UILabel!
  26. @IBOutlet weak var playButton: UIImageView!
  27. var indexPath : IndexPath?
  28. var player: AVPlayer?
  29. var isPlaying = false
  30. var currentVideo : AVPlayerLayer?
  31. @objc func playerDidFinishPlaying(note: NSNotification) {
  32. self.player?.seek(to: .zero)
  33. self.playButton.isHidden = false
  34. self.isPlaying = false
  35. }
  36. required init?(coder: NSCoder) {
  37. super.init(coder: coder)
  38. NotificationCenter.default.addObserver(self, selector: #selector(self.pauseVideo), name: NSNotification.Name(rawValue: kMediaPreviewPauseVideo), object: nil)
  39. }
  40. override func prepareForReuse() {
  41. self.showLoadingScreen()
  42. if let video = currentVideo {
  43. video.removeFromSuperlayer()
  44. }
  45. }
  46. func addAccessibilityLabels() {
  47. self.videoBackgroundView.accessibilityLabel = String(format: NSLocalizedString("video", comment: ""))
  48. self.loadingView.accessibilityLabel = String(format: NSLocalizedString("loading_video", comment: ""))
  49. }
  50. func videoLoaded() {
  51. self.playButton.isHidden = false
  52. self.loadingView.isHidden = true
  53. }
  54. func setColors() {
  55. self.backgroundView?.backgroundColor = .clear
  56. self.backgroundColor = .clear
  57. self.videoBackgroundView.backgroundColor = .clear
  58. loadingView.backgroundColor = .clear
  59. self.playButton.tintColor = .white
  60. self.playButton.image = self.playButton.image?.draw(withTintColor: .white)
  61. self.activityIndicator.color = Colors.fontNormal()
  62. }
  63. func showLoadingScreen() {
  64. self.setColors()
  65. videoBackgroundView.isHidden = true
  66. playButton.isHidden = true
  67. loadingView.isHidden = false
  68. activityIndicator.isHidden = false
  69. loadingVideoText.isHidden = false
  70. activityIndicator.startAnimating()
  71. loadingVideoText.text = String(format: NSLocalizedString("loading_video", comment: ""))
  72. }
  73. override func layoutSubviews() {
  74. super.layoutSubviews()
  75. self.currentVideo?.frame = self.bounds
  76. self.videoBackgroundView.layer.sublayers?.first?.frame = self.bounds
  77. }
  78. func updateVideoWithAsset(asset : AVAsset) {
  79. let playerItem = AVPlayerItem(asset: asset)
  80. self.player = AVPlayer(playerItem: playerItem)
  81. self.player?.actionAtItemEnd = .pause
  82. let playerLayer = AVPlayerLayer()
  83. playerLayer.player = self.player
  84. playerLayer.frame = self.videoBackgroundView.frame
  85. playerLayer.videoGravity = .resizeAspect
  86. playerLayer.needsDisplayOnBoundsChange = true
  87. playerLayer.backgroundColor = UIColor.clear.cgColor
  88. self.videoBackgroundView.layer.addSublayer(playerLayer)
  89. self.currentVideo = playerLayer
  90. do {
  91. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
  92. } catch {
  93. DDLogError("Could not create AudioSession for .moviePlayback")
  94. }
  95. let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
  96. if playerItem.status != .readyToPlay && playerItem.status != .failed {
  97. return
  98. }
  99. DispatchQueue.main.async {
  100. self.videoBackgroundView.isHidden = false
  101. let view = UIView(frame: playerLayer.videoRect)
  102. view.backgroundColor = .clear
  103. self.videoBackgroundView.addSubview(view)
  104. self.videoBackgroundView.bringSubviewToFront(view)
  105. let tapGR = UITapGestureRecognizer(target: self, action: #selector(VideoImageCell.handleTap(_:)))
  106. tapGR.delegate = self
  107. tapGR.numberOfTapsRequired = 1
  108. view.addGestureRecognizer(tapGR)
  109. self.videoLoaded()
  110. timer.invalidate()
  111. }
  112. }
  113. timer.tolerance = 0.1
  114. }
  115. func togglePlaying() {
  116. if self.isPlaying {
  117. self.pauseVideo()
  118. } else {
  119. self.isPlaying = true
  120. self.playButton.isHidden = true
  121. self.player?.play()
  122. }
  123. }
  124. @objc func pauseVideo() {
  125. DispatchQueue.main.async {
  126. self.player?.pause()
  127. self.isPlaying = false
  128. self.playButton.isHidden = false
  129. }
  130. }
  131. @objc func handleTap(_ gesture: UITapGestureRecognizer) {
  132. DispatchQueue.main.async {
  133. NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil)
  134. self.togglePlaying()
  135. }
  136. }
  137. }