-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRTCVideoWrapper.swift
More file actions
81 lines (66 loc) · 2.73 KB
/
RTCVideoWrapper.swift
File metadata and controls
81 lines (66 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// RTCVideoWrapper.swift
// Neuro App
//
// Created by David Ferrufino on 8/27/24.
//
import Foundation
import WebRTC
import UIKit
class RTCVideoWrapper: UIView, RTCVideoRenderer {
private let videoView: RTCMTLVideoView
private var aspectRatioConstraint: NSLayoutConstraint?
override init(frame: CGRect) {
self.videoView = RTCMTLVideoView(frame: frame)
super.init(frame: frame)
// Apply horizontal flip for front-facing camera (mirroring)
self.videoView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
self.videoView.contentMode = .scaleAspectFit // Maintain aspect ratio
self.addSubview(videoView)
setupConstraints()
}
required init?(coder: NSCoder) {
self.videoView = RTCMTLVideoView(frame: .zero)
super.init(coder: coder)
// Apply horizontal flip for front-facing camera (mirroring)
self.videoView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
self.videoView.contentMode = .scaleAspectFit // Maintain aspect ratio
self.addSubview(videoView)
setupConstraints()
}
func setSize(_ size: CGSize) {
updateAspectRatioConstraint(size: size)
}
func renderFrame(_ frame: RTCVideoFrame?) {
guard let frame = frame else {
print("Received nil frame, not rendering.")
return
}
// Update aspect ratio whenever a new frame is rendered
let videoSize = CGSize(width: CGFloat(frame.width), height: CGFloat(frame.height))
updateAspectRatioConstraint(size: videoSize)
videoView.renderFrame(frame)
}
private func setupConstraints() {
videoView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
videoView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
videoView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
videoView.topAnchor.constraint(equalTo: self.topAnchor),
videoView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
private func updateAspectRatioConstraint(size: CGSize) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
// Remove the existing aspect ratio constraint
if let aspectRatioConstraint = self.aspectRatioConstraint {
self.removeConstraint(aspectRatioConstraint)
}
// Calculate and apply the new aspect ratio
let aspectRatio = size.width / size.height
self.aspectRatioConstraint = self.videoView.widthAnchor.constraint(equalTo: self.videoView.heightAnchor, multiplier: aspectRatio)
self.aspectRatioConstraint?.isActive = true
}
}
}