From 287010a98fd39206bd3a28341528a013fee5b23f Mon Sep 17 00:00:00 2001 From: Aleksey Seren Date: Wed, 10 Apr 2024 12:50:31 -0500 Subject: [PATCH] Fixes by review comments #3 --- .../account/confirmations/confirmation_type.h | 2 +- .../NewTabPageBackgroundButtonsView.swift | 14 +- .../NewTabPageBackgroundView.swift | 36 ++-- .../NewTabPageVideoButtonsView.swift | 39 ++-- .../Backgrounds/NewTabPageVideoPlayer.swift | 196 +++++++----------- .../NewTabPageViewController.swift | 78 +++---- 6 files changed, 159 insertions(+), 206 deletions(-) diff --git a/components/brave_ads/core/public/account/confirmations/confirmation_type.h b/components/brave_ads/core/public/account/confirmations/confirmation_type.h index d5e570de067d..bb59f13a0259 100644 --- a/components/brave_ads/core/public/account/confirmations/confirmation_type.h +++ b/components/brave_ads/core/public/account/confirmations/confirmation_type.h @@ -46,7 +46,7 @@ enum class ConfirmationType { // When the user converts on an ad. kConversion, - // When a new tab page video ad started playing. + // When a new tab page video ad starts playing. kMediaPlay, // When played 25% of a new tab page video ad. diff --git a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundButtonsView.swift b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundButtonsView.swift index f5af2d485415..c57c42852445 100644 --- a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundButtonsView.swift +++ b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundButtonsView.swift @@ -171,16 +171,15 @@ class NewTabPageBackgroundButtonsView: UIView, PreferencesObserver { tappedPlayButton?() } - @objc private func tappedVideDuringAutoplay() { + @objc private func tappedVideoDuringAutoplay() { tappedBackgroundDuringAutoplay?() } func videoAutoplayStarted() { let tapGesture = UITapGestureRecognizer( target: self, - action: #selector(self.tappedVideDuringAutoplay) + action: #selector(self.tappedVideoDuringAutoplay) ) - tapGesture.numberOfTapsRequired = 1 addGestureRecognizer(tapGesture) playButtonGestureRecognizer = tapGesture } @@ -196,7 +195,7 @@ class NewTabPageBackgroundButtonsView: UIView, PreferencesObserver { } private func updatePlayButtonVisibility() { - let isLandscape = frame.width > frame.height + let isLandscape = window?.windowScene?.interfaceOrientation.isLandscape == true // Hide the play button if the video is in landscape mode on iPhone if isLandscape && UIDevice.isPhone { @@ -281,7 +280,9 @@ extension NewTabPageBackgroundButtonsView { } private class PlayButton: SpringButton { let imageView = UIImageView( - image: UIImage(braveSystemNamed: "leo.play.circle", compatibleWith: nil)! + image: UIImage(braveSystemNamed: "leo.play.circle")!.applyingSymbolConfiguration( + .init(scale: .large) + ) ).then { $0.tintColor = .white $0.contentMode = .scaleAspectFit @@ -305,10 +306,9 @@ extension NewTabPageBackgroundButtonsView { backgroundView.snp.makeConstraints { $0.edges.equalToSuperview() + $0.width.equalTo(self.snp.height) } imageView.snp.makeConstraints { - $0.width.equalTo(40) - $0.height.equalTo(40) $0.edges.equalToSuperview().inset(UIEdgeInsets(equalInset: 10)) } } diff --git a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundView.swift b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundView.swift index f56cde20ee4b..b26f94038ca1 100644 --- a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundView.swift +++ b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageBackgroundView.swift @@ -22,13 +22,15 @@ class NewTabPageBackgroundView: UIView { bounds = .init(x: -x, y: 0, width: bounds.width, height: bounds.height) } - func setupPlayerLayer(_ backgroundVideoPath: URL) { - backgroundColor = parseColorFromFilename( + func setupPlayerLayer(_ backgroundVideoPath: URL, player: AVPlayer?) { + playerLayer.player = player + layer.addSublayer(playerLayer) + + backgroundColor = parseBackgroundColorFromFilename( filename: backgroundVideoPath.lastPathComponent ) - let resizeToFill = shouldResizeToFill(filename: backgroundVideoPath.lastPathComponent) - if resizeToFill { + if shouldResizePlayerToFill(filename: backgroundVideoPath.lastPathComponent) { playerLayer.videoGravity = .resizeAspectFill } else { playerLayer.videoGravity = .resizeAspect @@ -48,8 +50,6 @@ class NewTabPageBackgroundView: UIView { return .init(rgb: 0x3b3e4f) } - layer.addSublayer(playerLayer) - addSubview(imageView) imageView.snp.makeConstraints { $0.edges.equalToSuperview() @@ -61,31 +61,21 @@ class NewTabPageBackgroundView: UIView { fatalError() } - private func parseColorFromFilename(filename: String) -> UIColor { - var color: String? + private func parseBackgroundColorFromFilename(filename: String) -> UIColor { + var colorHex: String? if let range = filename.range(of: "\\.RGB[a-fA-F0-9]+\\.", options: .regularExpression) { - color = filename[range].replacingOccurrences(of: ".RGB", with: "") + colorHex = filename[range].replacingOccurrences(of: ".RGB", with: "") .replacingOccurrences(of: ".", with: "") } - guard let color = color, - color.count == 6 - else { + guard let colorHex, colorHex.count == 6 else { return UIColor.black } - var rgbValue: UInt64 = 0 - Scanner(string: color).scanHexInt64(&rgbValue) - - return UIColor( - red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, - green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, - blue: CGFloat(rgbValue & 0x0000FF) / 255.0, - alpha: CGFloat(1.0) - ) + return UIColor(colorString: colorHex) } - private func shouldResizeToFill(filename: String) -> Bool { - return filename.range(of: "\\.RTF\\.", options: .regularExpression) != nil + private func shouldResizePlayerToFill(filename: String) -> Bool { + return filename.contains(".RTF.") } } diff --git a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoButtonsView.swift b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoButtonsView.swift index e94558e9d025..49c525aeec5d 100644 --- a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoButtonsView.swift +++ b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoButtonsView.swift @@ -14,7 +14,7 @@ import UIKit /// The foreground view of the New Tab Page video player. It contains the cancel /// button and handles user tap gestures to play/pause the video. class NewTabPageVideoButtonsView: UIView { - var tappedVideoBackground: (() -> Bool)? + var tappedBackgroundVideo: (() -> Bool)? var tappedCancelButton: (() -> Void)? private let playPauseButtonImage = BluredImageView().then { @@ -33,9 +33,8 @@ class NewTabPageVideoButtonsView: UIView { let tapGesture = UITapGestureRecognizer( target: self, - action: #selector(self.videoBackgroundTapped(sender:)) + action: #selector(self.backgroundVideoTapped(sender:)) ) - tapGesture.numberOfTapsRequired = 1 addGestureRecognizer(tapGesture) cancelButton.snp.makeConstraints { @@ -61,24 +60,29 @@ class NewTabPageVideoButtonsView: UIView { tappedCancelButton?() } - @objc private func videoBackgroundTapped(sender: UITapGestureRecognizer) { + @objc private func backgroundVideoTapped(sender: UITapGestureRecognizer) { let location = sender.location(in: self) if let view = super.hitTest(location, with: nil), view == cancelButton { tappedVideoCancelButton() return } - guard let playStarted = tappedVideoBackground?() else { + guard let playStarted = tappedBackgroundVideo?() else { return } if playStarted { - playPauseButtonImage.setImage(imageName: "leo.play.circle") - showAndFadeOutImage(imageView: playPauseButtonImage) + playPauseButtonImage.imageView.image = UIImage(braveSystemNamed: "leo.play.circle")! + .applyingSymbolConfiguration( + .init(scale: .large) + ) } else { - playPauseButtonImage.setImage(imageName: "leo.pause.circle") - showAndFadeOutImage(imageView: playPauseButtonImage) + playPauseButtonImage.imageView.image = UIImage(braveSystemNamed: "leo.pause.circle")! + .applyingSymbolConfiguration( + .init(scale: .large) + ) } + showAndFadeOutImage(imageView: playPauseButtonImage) } private func showAndFadeOutImage(imageView: UIView) { @@ -109,7 +113,9 @@ class NewTabPageVideoButtonsView: UIView { extension NewTabPageVideoButtonsView { private class CancelButton: SpringButton { let imageView = UIImageView( - image: UIImage(braveSystemNamed: "leo.close", compatibleWith: nil)! + image: UIImage(braveSystemNamed: "leo.close")!.applyingSymbolConfiguration( + .init(scale: .small) + ) ).then { $0.tintColor = .white $0.contentMode = .scaleAspectFit @@ -126,6 +132,7 @@ extension NewTabPageVideoButtonsView { super.init(frame: frame) clipsToBounds = true + accessibilityLabel = Strings.CancelString addSubview(backgroundView) @@ -133,10 +140,9 @@ extension NewTabPageVideoButtonsView { backgroundView.snp.makeConstraints { $0.edges.equalToSuperview() + $0.width.equalTo(self.snp.height) } imageView.snp.makeConstraints { - $0.width.equalTo(16) - $0.height.equalTo(16) $0.edges.equalToSuperview().inset(UIEdgeInsets(equalInset: 4)) } } @@ -155,7 +161,7 @@ extension NewTabPageVideoButtonsView { $0.clipsToBounds = true $0.isUserInteractionEnabled = false } - private let imageView = UIImageView().then { + let imageView = UIImageView().then { $0.tintColor = .white $0.contentMode = .scaleAspectFit } @@ -171,10 +177,9 @@ extension NewTabPageVideoButtonsView { backgroundView.snp.makeConstraints { $0.edges.equalToSuperview() + $0.width.equalTo(self.snp.height) } imageView.snp.makeConstraints { - $0.width.equalTo(40) - $0.height.equalTo(40) $0.edges.equalToSuperview().inset(UIEdgeInsets(equalInset: 10)) } } @@ -184,10 +189,6 @@ extension NewTabPageVideoButtonsView { layer.cornerRadius = bounds.height / 2.0 } - func setImage(imageName: String) { - imageView.image = UIImage(braveSystemNamed: imageName, compatibleWith: nil)! - } - @available(*, unavailable) required init(coder: NSCoder) { fatalError() diff --git a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoPlayer.swift b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoPlayer.swift index 6f7e252f0af6..2d634df358a2 100644 --- a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoPlayer.swift +++ b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/Backgrounds/NewTabPageVideoPlayer.swift @@ -16,50 +16,49 @@ import UIKit /// playback on the New Tab Page. It handles events such as play finished, /// played 25 percent, autoplay finished, play cancelled, and video loaded. class NewTabPageVideoPlayer { - var autoplayFinishedEvent: (() -> Void)? - var autoplayStartedEvent: (() -> Void)? - var playFinishedEvent: (() -> Void)? - var playStartedEvent: (() -> Void)? - var played25PercentEvent: (() -> Void)? - var playCancelledEvent: (() -> Void)? + var didStartAutoplayEvent: (() -> Void)? + var didFinishAutoplayEvent: (() -> Void)? + var didStartPlaybackEvent: (() -> Void)? + var didFinishPlaybackEvent: (() -> Void)? + var didPlay25PercentEvent: (() -> Void)? + var didCancelPlaybackEvent: (() -> Void)? var player: AVPlayer? - private var isPlayStarted = false - private var isLoadFinished = false - private var isAutoplayRequestedOnce = false - private var isAutoplayFinished = false + private let backgroundVideoPath: URL + private var didStartPlayback = false + private var didStartAutoplay = false + private var didFinishAutoplay = false private var timeObserver: Any? private var playerObserver: NSKeyValueObservation? private let kMaxAutoplayDuration = 6.0 + private let kMedia25Percent = 0.25 private var stopFrame: Int? private var frameRate: Float? + private var duration: CMTime? - init(backgroundVideoPath: URL, videoInitiallyVisible: Bool) { - // Do not start autoplay if video is not initially visible - if !videoInitiallyVisible { - isAutoplayRequestedOnce = true - isAutoplayFinished = true - } + private var isPlaying: Bool { + player?.timeControlStatus != .paused + } + init(_ backgroundVideoPath: URL) { + self.backgroundVideoPath = backgroundVideoPath stopFrame = parseStopFrameFromFilename(filename: backgroundVideoPath.lastPathComponent) - resetPlayer(backgroundVideoPath) - loadVideoTrackParams(backgroundVideoPath) + createPlayer() } deinit { cleanupObservers() } - func resetPlayer(_ backgroundVideoPath: URL?) { - guard let backgroundVideoPath = backgroundVideoPath else { - cleanupObservers() - player = nil - return - } + func resetPlayer() { + cleanupObservers() + player = nil + } + func createPlayer() { let item = AVPlayerItem(url: backgroundVideoPath) player = AVPlayer(playerItem: item) @@ -72,8 +71,8 @@ class NewTabPageVideoPlayer { ) } - func startVideoPlayback() { - if !isAutoplayFinished { + func startPlayback() { + if !didFinishAutoplay { autoplayFinished() } @@ -89,96 +88,81 @@ class NewTabPageVideoPlayer { timeObserver = player?.addPeriodicTimeObserver(forInterval: interval, queue: nil) { [weak self] time in - self?.checkPlayPercentage() + self?.checkMedia25Percentage() } player?.play() - isPlayStarted = true + didStartPlayback = true + + didStartPlaybackEvent?() + } - playStartedEvent?() + func cancelAutoplay() { + didStartAutoplay = true } func maybeCancelPlay() { - if !isAutoplayFinished && isLoadFinished { + if !didFinishAutoplay { autoplayFinished() player?.pause() - } - - if isPlayStarted { + } else if didStartPlayback { player?.pause() if let timeObserver = timeObserver { player?.removeTimeObserver(timeObserver) } timeObserver = nil - playCancelledEvent?() + didCancelPlaybackEvent?() + didStartPlayback = false } - isPlayStarted = false } func togglePlay() -> Bool { - let isVideoInProgress = isVideoInProgress() + let wasPlaying = isPlaying - if isVideoInProgress { + if wasPlaying { player?.pause() } else { player?.play() } - return !isVideoInProgress + return !wasPlaying } func maybeStartAutoplay() { - // Start autoplay only once. - if isAutoplayRequestedOnce { - return + if !didStartAutoplay { + loadTrackParams(backgroundVideoPath) } - isAutoplayRequestedOnce = true - - // Start autoplay after video is loaded - if !isLoadFinished { - return - } - - startAutoplay() } - private func loadVideoTrackParams(_ backgroundVideoPath: URL) { + private func loadTrackParams(_ backgroundVideoPath: URL) { Task { - var frameRate: Float? - let asset: AVURLAsset = AVURLAsset(url: backgroundVideoPath) - let isPlayable = try? await asset.load(.isPlayable) - if let isPlayable = isPlayable, - isPlayable, - let videoTrack = try? await asset.loadTracks(withMediaType: .video).first - { - frameRate = try? await videoTrack.load(.nominalFrameRate) - } - - finishPlayerSetup(isPlayable: isPlayable, frameRate: frameRate) + do { + var frameRate: Float? + let asset: AVURLAsset = AVURLAsset(url: backgroundVideoPath) + let (isPlayable, duration) = try await asset.load(.isPlayable, .duration) + if isPlayable { + if let track = try? await asset.loadTracks(withMediaType: .video).first { + frameRate = try? await track.load(.nominalFrameRate) + } + await loadedTrackParams(duration: duration, frameRate: frameRate) + } + } catch {} } } - private func finishPlayerSetup(isPlayable: Bool?, frameRate: Float?) { - DispatchQueue.main.async { [weak self] in - guard let self = self else { return } + @MainActor + private func loadedTrackParams(duration: CMTime?, frameRate: Float?) async { + self.duration = duration + self.frameRate = frameRate - guard let isPlayable = isPlayable else { - self.videoLoaded(succeeded: false) - return - } - self.frameRate = frameRate - self.videoLoaded(succeeded: isPlayable) - } + startAutoplay() } private func startAutoplay() { - if isAutoplayFinished { - autoplayFinished() - return - } + cancelAutoplay() - guard let duration = player?.currentItem?.duration else { + guard let duration else { autoplayFinished() return } @@ -193,8 +177,8 @@ class NewTabPageVideoPlayer { } } - // If autoplay length is less then video duration then set forward playback end - // time to stop the video at the specified time. + // If autoplay length is less then video duration then set forward playback + // end time to stop the video at the specified time. if autoplayLengthSeconds < CMTimeGetSeconds(duration) { player?.currentItem?.forwardPlaybackEndTime = CMTime( seconds: autoplayLengthSeconds, @@ -202,12 +186,12 @@ class NewTabPageVideoPlayer { ) } - // Detect if video was interrupted during autoplay and fire autoplayFinished - // event if needed. - playerObserver = player?.observe(\.timeControlStatus, options: [.new, .old]) { - [weak self] (player, change) in + // Detect if video was interrupted during autoplay and fire + // `autoplayFinished` event if needed. + playerObserver = player?.observe(\.timeControlStatus) { + [weak self] (player, _) in guard let self = self else { return } - if player.timeControlStatus == .paused && !self.isAutoplayFinished { + if player.timeControlStatus == .paused && !self.didFinishAutoplay { self.autoplayFinished() } } @@ -215,60 +199,38 @@ class NewTabPageVideoPlayer { player?.isMuted = true player?.play() - autoplayStartedEvent?() - } - - private func isVideoInProgress() -> Bool { - return player?.timeControlStatus != .paused + didStartAutoplayEvent?() } - @objc private func playerDidFinishPlaying(note: NSNotification) { - if !isAutoplayFinished { + @objc private func playerDidFinishPlaying() { + if !didFinishAutoplay { autoplayFinished() return } - playFinishedEvent?() - isPlayStarted = false + didFinishPlaybackEvent?() + didStartPlayback = false } - private func checkPlayPercentage() { - guard let timeObserver = timeObserver else { + private func checkMedia25Percentage() { + guard let timeObserver, let duration, let playerItem = player?.currentItem else { return } - guard let playerItem = player?.currentItem else { - return - } - - let duration = CMTimeGetSeconds(playerItem.duration) + let durationInSeconds = CMTimeGetSeconds(duration) let currentTime = CMTimeGetSeconds(playerItem.currentTime()) - if currentTime / duration >= 0.25 { - played25PercentEvent?() + if currentTime / durationInSeconds >= kMedia25Percent { + didPlay25PercentEvent?() player?.removeTimeObserver(timeObserver) self.timeObserver = nil } } - private func videoLoaded(succeeded: Bool) { - isLoadFinished = true - - if !succeeded { - autoplayFinished() - return - } - - // Autoplay didn't start before because the video wasn't loaded - if isAutoplayRequestedOnce { - startAutoplay() - } - } - private func autoplayFinished() { - isAutoplayFinished = true - autoplayFinishedEvent?() + didFinishAutoplay = true + didFinishAutoplayEvent?() } private func cleanupObservers() { diff --git a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/NewTabPageViewController.swift b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/NewTabPageViewController.swift index 8be4a960890f..0655baece455 100644 --- a/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/NewTabPageViewController.swift +++ b/ios/brave-ios/Sources/Brave/Frontend/Browser/New Tab Page/NewTabPageViewController.swift @@ -384,7 +384,7 @@ class NewTabPageViewController: UIViewController { // to use it. backgroundView.layoutIfNeeded() - updateVideoPlayerLayout() + updateVideoPlayer() calculateBackgroundCenterPoints() } @@ -392,11 +392,13 @@ class NewTabPageViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) - reportSponsoredImageBackgroundEvent(.servedImpression) { [weak self] _ in - self?.reportSponsoredImageBackgroundEvent(.viewedImpression) + reportSponsoredBackgroundEvent(.servedImpression) { [weak self] _ in + self?.reportSponsoredBackgroundEvent(.viewedImpression) } - videoPlayer?.maybeStartAutoplay() + if shouldShowBackgroundVideo() { + videoPlayer?.maybeStartAutoplay() + } presentNotification() @@ -416,11 +418,13 @@ class NewTabPageViewController: UIViewController { backgroundView.imageView.image = parent == nil ? nil : background.backgroundImage - if let backgroundVideoPath = background.backgroundVideoPath { - videoPlayer?.maybeCancelPlay() - videoPlayer?.resetPlayer(parent == nil ? nil : backgroundVideoPath) - backgroundView.playerLayer.player = parent == nil ? nil : videoPlayer?.player + videoPlayer?.maybeCancelPlay() + if parent == nil { + videoPlayer?.resetPlayer() + } else { + videoPlayer?.createPlayer() } + backgroundView.playerLayer.player = videoPlayer?.player } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { @@ -483,45 +487,41 @@ class NewTabPageViewController: UIViewController { guard let backgroundVideoPath = background.backgroundVideoPath else { return } - backgroundButtonsView.activeButton = .none - videoPlayer = NewTabPageVideoPlayer( - backgroundVideoPath: backgroundVideoPath, - videoInitiallyVisible: shouldShowVideoBackground() - ) - backgroundView.playerLayer.player = videoPlayer?.player - backgroundView.setupPlayerLayer(backgroundVideoPath) + videoPlayer = NewTabPageVideoPlayer(backgroundVideoPath) + backgroundView.setupPlayerLayer(backgroundVideoPath, player: videoPlayer?.player) - videoButtonsView.tappedVideoBackground = { [weak self] in - guard let videoPlayer = self?.videoPlayer else { + videoButtonsView.tappedBackgroundVideo = { [weak videoPlayer] in + guard let videoPlayer else { return false } return videoPlayer.togglePlay() } - videoButtonsView.tappedCancelButton = { [weak self] in - self?.videoPlayer?.maybeCancelPlay() + videoButtonsView.tappedCancelButton = { [weak videoPlayer] in + videoPlayer?.maybeCancelPlay() } + backgroundButtonsView.activeButton = .none backgroundButtonsView.tappedPlayButton = { [weak self] in guard let self = self else { return } self.videoButtonsView.isHidden = false self.fadeOutAndHideCollectionView() - self.videoPlayer?.startVideoPlayback() + self.videoPlayer?.startPlayback() } backgroundButtonsView.tappedBackgroundDuringAutoplay = { [weak self] in guard let self = self else { return } self.collectionView.isHidden = true self.videoButtonsView.isHidden = false - self.videoPlayer?.startVideoPlayback() + self.videoPlayer?.startPlayback() } - videoPlayer?.playCancelledEvent = { [weak self] in + videoPlayer?.didCancelPlaybackEvent = { [weak self] in self?.videoButtonsView.isHidden = true self?.showAndFadeInCollectionView() } - videoPlayer?.autoplayStartedEvent = { [weak self] in + videoPlayer?.didStartAutoplayEvent = { [weak self] in self?.backgroundButtonsView.videoAutoplayStarted() } - videoPlayer?.autoplayFinishedEvent = { [weak self] in + videoPlayer?.didFinishAutoplayEvent = { [weak self] in guard let self = self else { return } self.backgroundButtonsView.videoAutoplayFinished() if case .sponsoredImage(let background) = self.background.currentBackground { @@ -535,34 +535,34 @@ class NewTabPageViewController: UIViewController { } ) } - videoPlayer?.playFinishedEvent = { [weak self] in + videoPlayer?.didFinishPlaybackEvent = { [weak self] in guard let self = self else { return } self.videoButtonsView.isHidden = true - self.reportSponsoredImageBackgroundEvent(.media100) + self.reportSponsoredBackgroundEvent(.media100) self.showAndFadeInCollectionView() } - videoPlayer?.playStartedEvent = { [weak self] in - self?.reportSponsoredImageBackgroundEvent(.mediaPlay) + videoPlayer?.didStartPlaybackEvent = { [weak self] in + self?.reportSponsoredBackgroundEvent(.mediaPlay) } - videoPlayer?.played25PercentEvent = { [weak self] in - self?.reportSponsoredImageBackgroundEvent(.media25) + videoPlayer?.didPlay25PercentEvent = { [weak self] in + self?.reportSponsoredBackgroundEvent(.media25) } } - private func shouldShowVideoBackground() -> Bool { - let isLandscape = view.frame.width > view.frame.height - let isPhone = UIDevice.isPhone - return !(isLandscape && isPhone) + private func shouldShowBackgroundVideo() -> Bool { + let isLandscape = view.window?.windowScene?.interfaceOrientation.isLandscape == true + return !(isLandscape && UIDevice.isPhone) } - private func updateVideoPlayerLayout() { + private func updateVideoPlayer() { backgroundView.playerLayer.frame = view.bounds - if shouldShowVideoBackground() { + if shouldShowBackgroundVideo() { backgroundView.playerLayer.isHidden = false } else { - // Cancel play and hide the player layer in landscape mode on iPhone. + // Hide the player layer in landscape mode on iPhone. backgroundView.playerLayer.isHidden = true + videoPlayer?.cancelAutoplay() videoPlayer?.maybeCancelPlay() } } @@ -637,7 +637,7 @@ class NewTabPageViewController: UIViewController { backgroundView.updateImageXOffset(by: realisticXOffset) } - private func reportSponsoredImageBackgroundEvent( + private func reportSponsoredBackgroundEvent( _ event: BraveAds.NewTabPageAdEventType, completion: ((_ success: Bool) -> Void)? = nil ) { @@ -1092,7 +1092,7 @@ class NewTabPageViewController: UIViewController { delegate?.navigateToInput(url.absoluteString, inNewTab: false, switchingToPrivateMode: false) } - reportSponsoredImageBackgroundEvent(.clicked) + reportSponsoredBackgroundEvent(.clicked) } private func tappedQRCode(_ code: String) {