@feedbackrelay/react-native-replay 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +43 -0
- package/LICENSE +202 -0
- package/README.md +134 -2
- package/RelayReplay.podspec +20 -0
- package/android/build.gradle +17 -0
- package/android/src/main/java/app/feedbackrelay/reactnativereplay/RelayReplayModule.kt +121 -0
- package/android/src/main/java/app/feedbackrelay/reactnativereplay/RelayReplayPackage.kt +17 -0
- package/ios/RCTRelayReplay.h +4 -0
- package/ios/RCTRelayReplay.mm +68 -0
- package/ios/RelayReplayBridge.swift +122 -0
- package/lib/NativeRelayReplay.js +4 -0
- package/lib/client.d.ts +30 -0
- package/lib/client.js +300 -0
- package/lib/delivery.js +76 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.js +9 -0
- package/native/android/AndroidManifest.xml +1 -0
- package/native/android/java/app/feedbackrelay/replay/RelayReplayCapture.kt +615 -0
- package/native/android/java/app/feedbackrelay/replay/ReplayBuffer.kt +53 -0
- package/native/android/java/app/feedbackrelay/replay/ReplayEncoder.kt +268 -0
- package/native/android/java/app/feedbackrelay/sdk/RelayReplayProvider.kt +29 -0
- package/native/ios/Resources/PrivacyInfo.xcprivacy +16 -0
- package/native/ios/VideoRecorder.swift +450 -0
- package/package.json +73 -4
- package/react-native.config.js +4 -0
- package/src/NativeRelayReplay.ts +15 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
import AVFoundation
|
|
3
|
+
import VideoToolbox
|
|
4
|
+
import Darwin
|
|
5
|
+
|
|
6
|
+
/// A frozen MP4 or a reason why no recording was available. The recorder owns the file.
|
|
7
|
+
struct RelayRecordedVideo: Sendable {
|
|
8
|
+
let url: URL?
|
|
9
|
+
let omitted: String?
|
|
10
|
+
let width: Int
|
|
11
|
+
let height: Int
|
|
12
|
+
let byteSize: Int
|
|
13
|
+
let durationMs: Int
|
|
14
|
+
let startedBeforeEventMs: Int
|
|
15
|
+
let endedBeforeEventMs: Int
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/// Native recording only. This file also powers the React Native addon; it has no delivery dependency.
|
|
19
|
+
@MainActor final class RelayVideoRecorder {
|
|
20
|
+
private let encoder = ReplayEncoder()
|
|
21
|
+
private let fixedFPS: Int?
|
|
22
|
+
private var fps: Int
|
|
23
|
+
private weak var window: UIWindow?
|
|
24
|
+
private var scope: String?
|
|
25
|
+
private var attachments: [UUID: Bool] = [:]
|
|
26
|
+
private static weak var activeRecorder: RelayVideoRecorder?
|
|
27
|
+
static let ownershipAvailable = Notification.Name("app.feedbackrelay.replay.ownershipAvailable")
|
|
28
|
+
private var leases: [UUID: FrozenReplay] = [:]
|
|
29
|
+
private var exportReservations: [UUID: Int] = [:]
|
|
30
|
+
private var timer: Timer?
|
|
31
|
+
private var lastFrame = 0.0
|
|
32
|
+
private var lastTick = 0.0
|
|
33
|
+
private var schedulingLag = 0.0
|
|
34
|
+
private var lastSample = 0.0
|
|
35
|
+
private var lastCPU = 0.0
|
|
36
|
+
private var healthySamples = 0
|
|
37
|
+
private var captureCost = 0.0
|
|
38
|
+
private var encoderCost = 0.0
|
|
39
|
+
private var lastBattery = 0.0
|
|
40
|
+
private var batteryLevel: Float = -1
|
|
41
|
+
private var capturePending = false
|
|
42
|
+
private var generation = UUID()
|
|
43
|
+
private var leaseGeneration = UUID()
|
|
44
|
+
private var destroyed = false
|
|
45
|
+
private var backgroundObserver: NSObjectProtocol?
|
|
46
|
+
|
|
47
|
+
init(fps: Int? = nil) {
|
|
48
|
+
ReplayTemporaryFiles.pruneOnce()
|
|
49
|
+
fixedFPS = fps.flatMap { (1...10).contains($0) ? $0 : nil }; self.fps = fixedFPS ?? 1
|
|
50
|
+
backgroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in
|
|
51
|
+
Task { @MainActor in self?.resetEpoch() }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
deinit { timer?.invalidate(); if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) }; encoder.stop() }
|
|
56
|
+
|
|
57
|
+
func attach(scope: String, enabled: Bool = true) -> UUID? {
|
|
58
|
+
guard !destroyed, self.scope == nil || self.scope == scope else { return nil }
|
|
59
|
+
self.scope = scope
|
|
60
|
+
guard !enabled || Self.activeRecorder == nil || Self.activeRecorder === self else { return nil }
|
|
61
|
+
if enabled { Self.activeRecorder = self }
|
|
62
|
+
let id = UUID(); attachments[id] = enabled; start(); return id
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
var currentFPS: Int? {
|
|
66
|
+
guard !destroyed, Self.activeRecorder === self, attachments.values.contains(true),
|
|
67
|
+
let window = window ?? Self.activeWindow(), !window.isHidden, window.windowScene?.activationState == .foregroundActive else { return nil }
|
|
68
|
+
return fps
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
func setWindow(_ window: UIWindow?) {
|
|
72
|
+
guard !destroyed else { return }
|
|
73
|
+
if self.window !== window { resetEpoch(); self.window = window }
|
|
74
|
+
start()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
func preview(attachmentID: UUID? = nil, window: UIWindow? = nil) -> UUID {
|
|
78
|
+
let id = attachmentID ?? attachments.first(where: { $0.value })?.key ?? attachments.keys.first ?? UUID()
|
|
79
|
+
if attachments[id] == true, let window { setWindow(window) }
|
|
80
|
+
return freeze(attachmentID: id, submissionID: UUID().uuidString, isRetry: false, allowed: attachments[id] == true)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
func freeze(attachmentID: UUID, submissionID: String, isRetry: Bool, allowed: Bool) -> UUID {
|
|
84
|
+
expire()
|
|
85
|
+
if let existing = leases.first(where: { $0.value.attachmentID == attachmentID && $0.value.submissionID == submissionID }) {
|
|
86
|
+
if !allowed || attachments[attachmentID] == false {
|
|
87
|
+
if let file = existing.value.file { try? FileManager.default.removeItem(at: file) }
|
|
88
|
+
leases[existing.key] = FrozenReplay(attachmentID: attachmentID, submissionID: submissionID,
|
|
89
|
+
frames: ReplayFrames(samples: [], width: 0, height: 0, eventTime: existing.value.frames.eventTime, bytes: 0),
|
|
90
|
+
omitted: "capture-disabled", expiresAt: existing.value.expiresAt, expiresDate: existing.value.expiresDate)
|
|
91
|
+
}
|
|
92
|
+
return existing.key
|
|
93
|
+
}
|
|
94
|
+
let id = UUID(); let now = CACurrentMediaTime()
|
|
95
|
+
let reason: String?
|
|
96
|
+
if destroyed { reason = "recorder-unavailable" }
|
|
97
|
+
else if attachments[attachmentID] == nil { reason = Self.activeRecorder != nil && Self.activeRecorder !== self ? "replay-busy" : "recorder-unavailable" }
|
|
98
|
+
else if !allowed || attachments[attachmentID] == false { reason = "capture-disabled" }
|
|
99
|
+
else if isRetry { reason = "retry-history-unavailable" }
|
|
100
|
+
else if leases.count >= 4 { reason = "replay-busy" }
|
|
101
|
+
else { reason = nil }
|
|
102
|
+
let snapshot = reason == nil ? encoder.snapshot(at: now) : ReplayFrames(samples: [], width: 0, height: 0, eventTime: now, bytes: 0)
|
|
103
|
+
// Reserve the full rolling budget so later encoder output cannot exceed the shared cap.
|
|
104
|
+
let retained = leases.values.reduce(2 * 1024 * 1024) { $0 + ($1.frames.bytes > 0 ? $1.frames.bytes * 3 + 64 * 1024 : 0) }
|
|
105
|
+
+ exportReservations.filter { (leases[$0.key]?.frames.bytes ?? 0) == 0 }.values.reduce(0, +)
|
|
106
|
+
let omission = reason ?? (snapshot.samples.isEmpty ? "history-unavailable" : retained + snapshot.bytes * 3 + 64 * 1024 > 8 * 1024 * 1024 ? "replay-budget" : nil)
|
|
107
|
+
// Omitted leases contain no image data and still register their reason after event acceptance.
|
|
108
|
+
let lease = FrozenReplay(attachmentID: attachmentID, submissionID: submissionID,
|
|
109
|
+
frames: omission == nil ? snapshot : ReplayFrames(samples: [], width: 0, height: 0, eventTime: now, bytes: 0),
|
|
110
|
+
omitted: omission, expiresAt: now + 60, expiresDate: Date().addingTimeInterval(60))
|
|
111
|
+
// Never evict a live frozen clip just to admit another. Omitted descriptors are cheap,
|
|
112
|
+
// but cap them too; the adapter handles a missing lease as replay-busy.
|
|
113
|
+
if leases.count < 4 { leases[id] = lease }
|
|
114
|
+
return id
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
func deadline(leaseID: UUID, now: Date = Date()) -> Date? {
|
|
118
|
+
guard let lease = leases[leaseID], now < lease.expiresDate, CACurrentMediaTime() < lease.expiresAt else { release(leaseID: leaseID); return nil }
|
|
119
|
+
return lease.expiresDate
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
func materialize(leaseID: UUID) async throws -> RelayRecordedVideo {
|
|
123
|
+
expire()
|
|
124
|
+
guard let lease = leases[leaseID] else { return Self.omitted("replay-unavailable") }
|
|
125
|
+
if let omitted = lease.omitted { return Self.omitted(omitted) }
|
|
126
|
+
if let url = lease.file { return try Self.descriptor(url: url, frames: lease.frames) }
|
|
127
|
+
guard exportReservations.isEmpty else { return Self.omitted("replay-busy") }
|
|
128
|
+
exportReservations[leaseID] = lease.frames.bytes * 3 + 64 * 1024
|
|
129
|
+
defer { exportReservations.removeValue(forKey: leaseID); releaseOwnershipIfIdle() }
|
|
130
|
+
let generation = leaseGeneration
|
|
131
|
+
let frames = lease.frames
|
|
132
|
+
let deadline = min(lease.expiresAt, CACurrentMediaTime() + 30)
|
|
133
|
+
let task = Task.detached(priority: .utility) { try ReplayEncoder.mux(frames, deadline: deadline, expiresAt: lease.expiresDate) }
|
|
134
|
+
let url = try await withTaskCancellationHandler(operation: { try await task.value }, onCancel: { task.cancel() })
|
|
135
|
+
guard !Task.isCancelled, self.leaseGeneration == generation, leases[leaseID] != nil, CACurrentMediaTime() < lease.expiresAt, Date() < lease.expiresDate else {
|
|
136
|
+
try? FileManager.default.removeItem(at: url); throw CancellationError()
|
|
137
|
+
}
|
|
138
|
+
leases[leaseID]?.file = url
|
|
139
|
+
return try Self.descriptor(url: url, frames: frames)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
func release(leaseID: UUID) {
|
|
143
|
+
if let lease = leases.removeValue(forKey: leaseID), let file = lease.file { try? FileManager.default.removeItem(at: file) }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
func detach(attachmentID: UUID) {
|
|
147
|
+
attachments.removeValue(forKey: attachmentID)
|
|
148
|
+
for (id, lease) in leases where lease.attachmentID == attachmentID { release(leaseID: id) }
|
|
149
|
+
if !attachments.values.contains(true) { timer?.invalidate(); timer = nil; resetEpoch(); releaseOwnershipIfIdle() }
|
|
150
|
+
if attachments.isEmpty { clear(); scope = nil }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
func clear() {
|
|
154
|
+
leaseGeneration = UUID()
|
|
155
|
+
resetEpoch()
|
|
156
|
+
for id in Array(leases.keys) { release(leaseID: id) }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
func destroy() {
|
|
160
|
+
guard !destroyed else { return }
|
|
161
|
+
destroyed = true; timer?.invalidate(); timer = nil; clear(); attachments.removeAll(); scope = nil; window = nil
|
|
162
|
+
if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver); self.backgroundObserver = nil }
|
|
163
|
+
encoder.stop()
|
|
164
|
+
releaseOwnershipIfIdle()
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private func releaseOwnershipIfIdle() {
|
|
168
|
+
if !attachments.values.contains(true), exportReservations.isEmpty, Self.activeRecorder === self {
|
|
169
|
+
Self.activeRecorder = nil
|
|
170
|
+
NotificationCenter.default.post(name: Self.ownershipAvailable, object: nil)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private func start() {
|
|
175
|
+
guard !destroyed, attachments.values.contains(true), timer == nil else { return }
|
|
176
|
+
let timer = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in Task { @MainActor in self?.tick() } }
|
|
177
|
+
self.timer = timer; RunLoop.main.add(timer, forMode: .common)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private func tick() {
|
|
181
|
+
expire()
|
|
182
|
+
guard !destroyed, attachments.values.contains(true), let window = window ?? Self.activeWindow(), !window.isHidden, window.windowScene?.activationState == .foregroundActive else { return }
|
|
183
|
+
if self.window == nil { self.window = window }
|
|
184
|
+
let now = CACurrentMediaTime()
|
|
185
|
+
if lastTick > 0 { schedulingLag = max(schedulingLag, max(0, now - lastTick - 0.1)) }; lastTick = now
|
|
186
|
+
if now - lastSample >= 2.5 { sample(now: now) }
|
|
187
|
+
guard !capturePending, now - lastFrame >= 1 / Double(fps) else { return }
|
|
188
|
+
lastFrame = now
|
|
189
|
+
let bounds = window.bounds
|
|
190
|
+
guard bounds.width.isFinite, bounds.height.isFinite, bounds.origin.x.isFinite, bounds.origin.y.isFinite,
|
|
191
|
+
bounds.width > 0, bounds.height > 0 else { return }
|
|
192
|
+
let ratio = min(1, 720 / max(bounds.width, bounds.height))
|
|
193
|
+
let width = max(2, Int(bounds.width * ratio) / 2 * 2), height = max(2, Int(bounds.height * ratio) / 2 * 2)
|
|
194
|
+
let size = CGSize(width: width, height: height)
|
|
195
|
+
guard let scale = Self.captureScale(bounds: bounds, size: size) else { return }
|
|
196
|
+
let format = UIGraphicsImageRendererFormat(); format.scale = 1; format.opaque = true
|
|
197
|
+
var rendered = false
|
|
198
|
+
let image = UIGraphicsImageRenderer(size: size, format: format).image { context in
|
|
199
|
+
context.cgContext.scaleBy(x: scale.width, y: scale.height)
|
|
200
|
+
rendered = window.drawHierarchy(in: bounds, afterScreenUpdates: false)
|
|
201
|
+
}
|
|
202
|
+
guard rendered, let cgImage = image.cgImage else { return }
|
|
203
|
+
captureCost = CACurrentMediaTime() - now
|
|
204
|
+
capturePending = true
|
|
205
|
+
let generation = generation
|
|
206
|
+
let encodedAt = CACurrentMediaTime()
|
|
207
|
+
encoder.encode(image: cgImage, time: now, fps: fps) { [weak self] in
|
|
208
|
+
Task { @MainActor in guard let self else { return }; self.capturePending = false; if self.generation == generation { self.encoderCost = CACurrentMediaTime() - encodedAt } }
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
static func captureScale(bounds: CGRect, size: CGSize) -> CGSize? {
|
|
213
|
+
let scale = CGSize(width: size.width / bounds.width, height: size.height / bounds.height)
|
|
214
|
+
guard scale.width.isFinite, scale.height.isFinite, scale.width > 0, scale.height > 0 else { return nil }
|
|
215
|
+
return scale
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private func sample(now: Double) {
|
|
219
|
+
guard fixedFPS == nil else { lastSample = now; return }
|
|
220
|
+
var usage = rusage(); getrusage(RUSAGE_SELF, &usage)
|
|
221
|
+
let cpu = Double(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + Double(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1_000_000
|
|
222
|
+
defer { lastCPU = cpu; lastSample = now; schedulingLag = 0 }
|
|
223
|
+
let process = ProcessInfo.processInfo
|
|
224
|
+
let busy = lastSample > 0 ? (cpu - lastCPU) / (now - lastSample) / Double(max(1, process.activeProcessorCount)) : 0
|
|
225
|
+
if now - lastBattery >= 60 {
|
|
226
|
+
let device = UIDevice.current, monitoring = UIDevice.current.isBatteryMonitoringEnabled
|
|
227
|
+
if !monitoring { device.isBatteryMonitoringEnabled = true }
|
|
228
|
+
batteryLevel = device.batteryLevel
|
|
229
|
+
if !monitoring { device.isBatteryMonitoringEnabled = false }
|
|
230
|
+
lastBattery = now
|
|
231
|
+
}
|
|
232
|
+
let constrained = process.isLowPowerModeEnabled || process.thermalState == .serious || process.thermalState == .critical || os_proc_available_memory() < 64 * 1024 * 1024 || (batteryLevel >= 0 && batteryLevel <= 0.2)
|
|
233
|
+
var cap = min(5, max(1, Int(0.05 / max(0.000_001, captureCost))))
|
|
234
|
+
if constrained || busy >= 0.5 || schedulingLag >= 0.1 { cap = 1 }
|
|
235
|
+
else if busy >= 0.25 || schedulingLag >= 0.05 || encoderCost >= 0.2 { cap = min(cap, 2) }
|
|
236
|
+
if fps > cap { fps = cap; healthySamples = 0 }
|
|
237
|
+
else if fps < cap { healthySamples += 1; if healthySamples >= 3 { fps += 1; healthySamples = 0 } }
|
|
238
|
+
else { healthySamples = 0 }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private func resetEpoch() {
|
|
242
|
+
generation = UUID(); lastFrame = 0; lastTick = 0; healthySamples = 0
|
|
243
|
+
encoder.clear()
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private static func activeWindow() -> UIWindow? {
|
|
247
|
+
let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
|
248
|
+
.filter { $0.activationState == .foregroundActive }.flatMap(\.windows).filter { $0.isKeyWindow && !$0.isHidden }
|
|
249
|
+
return windows.count == 1 ? windows[0] : nil
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private func expire() {
|
|
253
|
+
let now = CACurrentMediaTime()
|
|
254
|
+
for (id, lease) in leases where now >= lease.expiresAt || Date() >= lease.expiresDate { release(leaseID: id) }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private static func omitted(_ reason: String) -> RelayRecordedVideo {
|
|
258
|
+
RelayRecordedVideo(url: nil, omitted: reason, width: 0, height: 0, byteSize: 0, durationMs: 0, startedBeforeEventMs: 0, endedBeforeEventMs: 0)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private static func descriptor(url: URL, frames: ReplayFrames) throws -> RelayRecordedVideo {
|
|
262
|
+
let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
|
|
263
|
+
guard size > 0, size <= 2 * 1024 * 1024, let first = frames.samples.first else { throw ReplayFailure.encoding }
|
|
264
|
+
let start = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(first))
|
|
265
|
+
let end = ReplayEncoder.endTime(frames)
|
|
266
|
+
return RelayRecordedVideo(url: url, omitted: nil, width: frames.width, height: frames.height, byteSize: size,
|
|
267
|
+
durationMs: max(1, Int((end - start) * 1000)), startedBeforeEventMs: max(0, Int((frames.eventTime - start) * 1000)), endedBeforeEventMs: max(0, Int((frames.eventTime - end) * 1000)))
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
enum ReplayFailure: Error { case encoding, expired }
|
|
272
|
+
private struct FrozenReplay {
|
|
273
|
+
let attachmentID: UUID
|
|
274
|
+
let submissionID: String
|
|
275
|
+
let frames: ReplayFrames
|
|
276
|
+
let omitted: String?
|
|
277
|
+
let expiresAt: Double
|
|
278
|
+
let expiresDate: Date
|
|
279
|
+
var file: URL?
|
|
280
|
+
}
|
|
281
|
+
struct ReplayFrames: @unchecked Sendable {
|
|
282
|
+
let samples: [CMSampleBuffer]
|
|
283
|
+
let width: Int
|
|
284
|
+
let height: Int
|
|
285
|
+
let eventTime: Double
|
|
286
|
+
let bytes: Int
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
final class ReplayEncoder: @unchecked Sendable {
|
|
290
|
+
private let queue = DispatchQueue(label: "app.feedbackrelay.replay.encoder", qos: .utility)
|
|
291
|
+
private let lock = NSLock()
|
|
292
|
+
private var session: VTCompressionSession?
|
|
293
|
+
private var width = 0, height = 0
|
|
294
|
+
private var samples: [CMSampleBuffer] = []
|
|
295
|
+
private var bytes = 0
|
|
296
|
+
private var lastKeyframe = 0.0
|
|
297
|
+
private var stopped = false
|
|
298
|
+
private var minimumTime = 0.0
|
|
299
|
+
|
|
300
|
+
func encode(image: CGImage, time: Double, fps: Int, completion: @escaping @Sendable () -> Void) {
|
|
301
|
+
queue.async { [self] in
|
|
302
|
+
defer { completion() }
|
|
303
|
+
guard !stopped else { return }
|
|
304
|
+
if session == nil || image.width != width || image.height != height {
|
|
305
|
+
invalidate(); reset()
|
|
306
|
+
width = image.width; height = image.height
|
|
307
|
+
var created: VTCompressionSession?
|
|
308
|
+
let status = VTCompressionSessionCreate(allocator: kCFAllocatorDefault, width: Int32(width), height: Int32(height), codecType: kCMVideoCodecType_H264,
|
|
309
|
+
encoderSpecification: nil, imageBufferAttributes: [kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA, kCVPixelBufferWidthKey: width, kCVPixelBufferHeightKey: height, kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary,
|
|
310
|
+
compressedDataAllocator: nil, outputCallback: { refcon, _, status, _, sample in
|
|
311
|
+
guard status == noErr, let sample, let refcon else { return }
|
|
312
|
+
Unmanaged<ReplayEncoder>.fromOpaque(refcon).takeUnretainedValue().append(sample)
|
|
313
|
+
}, refcon: Unmanaged.passUnretained(self).toOpaque(), compressionSessionOut: &created)
|
|
314
|
+
guard status == noErr, let created else { return }
|
|
315
|
+
session = created
|
|
316
|
+
VTSessionSetProperty(created, key: kVTCompressionPropertyKey_RealTime, value: kCFBooleanTrue)
|
|
317
|
+
VTSessionSetProperty(created, key: kVTCompressionPropertyKey_AllowFrameReordering, value: kCFBooleanFalse)
|
|
318
|
+
VTSessionSetProperty(created, key: kVTCompressionPropertyKey_AverageBitRate, value: 500_000 as CFNumber)
|
|
319
|
+
VTSessionSetProperty(created, key: kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, value: 1 as CFNumber)
|
|
320
|
+
VTSessionSetProperty(created, key: kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_Baseline_AutoLevel)
|
|
321
|
+
VTCompressionSessionPrepareToEncodeFrames(created)
|
|
322
|
+
}
|
|
323
|
+
guard let session, let pool = VTCompressionSessionGetPixelBufferPool(session) else { return }
|
|
324
|
+
var pixel: CVPixelBuffer?
|
|
325
|
+
guard CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool, &pixel) == kCVReturnSuccess, let pixel else { return }
|
|
326
|
+
CVPixelBufferLockBaseAddress(pixel, [])
|
|
327
|
+
guard let context = CGContext(data: CVPixelBufferGetBaseAddress(pixel), width: width, height: height, bitsPerComponent: 8,
|
|
328
|
+
bytesPerRow: CVPixelBufferGetBytesPerRow(pixel), space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) else { CVPixelBufferUnlockBaseAddress(pixel, []); return }
|
|
329
|
+
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
|
|
330
|
+
CVPixelBufferUnlockBaseAddress(pixel, [])
|
|
331
|
+
let force = time - lastKeyframe >= 1
|
|
332
|
+
if force { lastKeyframe = time }
|
|
333
|
+
let pts = CMTime(seconds: time, preferredTimescale: 600)
|
|
334
|
+
guard VTCompressionSessionEncodeFrame(session, imageBuffer: pixel, presentationTimeStamp: pts, duration: CMTime(seconds: 1 / Double(fps), preferredTimescale: 600), frameProperties: force ? [kVTEncodeFrameOptionKey_ForceKeyFrame: true] as CFDictionary : nil, sourceFrameRefcon: nil, infoFlagsOut: nil) == noErr else { return }
|
|
335
|
+
guard VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: pts) == noErr else { invalidate(); reset(); return }
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private func append(_ sample: CMSampleBuffer) {
|
|
340
|
+
guard CMSampleBufferDataIsReady(sample) else { return }
|
|
341
|
+
lock.lock(); defer { lock.unlock() }
|
|
342
|
+
let sync = Self.isSync(sample)
|
|
343
|
+
let size = CMSampleBufferGetTotalSampleSize(sample)
|
|
344
|
+
guard size <= 2 * 1024 * 1024 else { samples.removeAll(); bytes = 0; return }
|
|
345
|
+
let time = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sample))
|
|
346
|
+
guard time >= minimumTime else { return }
|
|
347
|
+
let cutoff = time - 10
|
|
348
|
+
// Free complete dependent groups before allocating the incoming owned block.
|
|
349
|
+
while !samples.isEmpty, (bytes + size > 2 * 1024 * 1024 || CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(samples[0])) < cutoff) {
|
|
350
|
+
bytes -= CMSampleBufferGetTotalSampleSize(samples.removeFirst())
|
|
351
|
+
while let first = samples.first, !Self.isSync(first) { bytes -= CMSampleBufferGetTotalSampleSize(samples.removeFirst()) }
|
|
352
|
+
}
|
|
353
|
+
guard !samples.isEmpty || sync, let owned = Self.ownedSample(sample) else { return }
|
|
354
|
+
samples.append(owned); bytes += size
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
func snapshot(at time: Double) -> ReplayFrames {
|
|
358
|
+
lock.lock(); defer { lock.unlock() }
|
|
359
|
+
let result = samples.filter { let t = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp($0)); return t >= time - 10 && t <= time }
|
|
360
|
+
guard let index = result.firstIndex(where: Self.isSync) else { return ReplayFrames(samples: [], width: 0, height: 0, eventTime: time, bytes: 0) }
|
|
361
|
+
let valid = Array(result[index...])
|
|
362
|
+
let dimensions = valid.first.flatMap { CMSampleBufferGetFormatDescription($0) }.map(CMVideoFormatDescriptionGetDimensions)
|
|
363
|
+
return ReplayFrames(samples: valid, width: Int(dimensions?.width ?? 0), height: Int(dimensions?.height ?? 0), eventTime: time, bytes: valid.reduce(0) { $0 + CMSampleBufferGetTotalSampleSize($1) })
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
func clear() { lock.lock(); minimumTime = CACurrentMediaTime(); samples.removeAll(); bytes = 0; lock.unlock(); queue.async { [self] in invalidate(); reset() } }
|
|
367
|
+
func stop() { queue.async { [self] in stopped = true; invalidate(); reset() } }
|
|
368
|
+
private func invalidate() { if let session { VTCompressionSessionInvalidate(session) }; session = nil }
|
|
369
|
+
private func reset() { lock.lock(); samples.removeAll(); bytes = 0; lastKeyframe = 0; lock.unlock() }
|
|
370
|
+
private static func ownedSample(_ sample: CMSampleBuffer) -> CMSampleBuffer? {
|
|
371
|
+
guard let source = CMSampleBufferGetDataBuffer(sample), let format = CMSampleBufferGetFormatDescription(sample) else { return nil }
|
|
372
|
+
let length = CMBlockBufferGetDataLength(source)
|
|
373
|
+
var block: CMBlockBuffer?
|
|
374
|
+
guard CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: length, blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0, dataLength: length, flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &block) == noErr, let block else { return nil }
|
|
375
|
+
var destination: UnsafeMutablePointer<Int8>?
|
|
376
|
+
guard CMBlockBufferGetDataPointer(block, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: nil, dataPointerOut: &destination) == noErr, let destination,
|
|
377
|
+
CMBlockBufferCopyDataBytes(source, atOffset: 0, dataLength: length, destination: destination) == noErr else { return nil }
|
|
378
|
+
var timing = CMSampleTimingInfo(duration: CMSampleBufferGetDuration(sample), presentationTimeStamp: CMSampleBufferGetPresentationTimeStamp(sample), decodeTimeStamp: CMSampleBufferGetDecodeTimeStamp(sample))
|
|
379
|
+
var size = length; var result: CMSampleBuffer?
|
|
380
|
+
guard CMSampleBufferCreateReady(allocator: kCFAllocatorDefault, dataBuffer: block, formatDescription: format, sampleCount: 1, sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleSizeEntryCount: 1, sampleSizeArray: &size, sampleBufferOut: &result) == noErr, let result else { return nil }
|
|
381
|
+
if !isSync(sample), let attachments = CMSampleBufferGetSampleAttachmentsArray(result, createIfNecessary: true) as? [NSMutableDictionary] { attachments.first?[kCMSampleAttachmentKey_NotSync] = true }
|
|
382
|
+
return result
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private static func isSync(_ sample: CMSampleBuffer) -> Bool {
|
|
386
|
+
let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[CFString: Any]]
|
|
387
|
+
return (attachments?.first?[kCMSampleAttachmentKey_NotSync] as? Bool) != true
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
static func endTime(_ frames: ReplayFrames) -> Double {
|
|
391
|
+
guard let last = frames.samples.last else { return frames.eventTime }
|
|
392
|
+
let pts = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(last))
|
|
393
|
+
let duration = CMTimeGetSeconds(CMSampleBufferGetDuration(last))
|
|
394
|
+
return min(frames.eventTime, pts + (duration.isFinite && duration > 0 ? duration : 0))
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
static func mux(_ frames: ReplayFrames, deadline: Double, expiresAt: Date = Date().addingTimeInterval(60)) throws -> URL {
|
|
398
|
+
guard let first = frames.samples.first, let format = CMSampleBufferGetFormatDescription(first) else { throw ReplayFailure.encoding }
|
|
399
|
+
let expiry = expiresAt.timeIntervalSince1970 * 1000
|
|
400
|
+
guard expiry.isFinite, expiry >= 0, expiry < Double(Int64.max) else { throw ReplayFailure.encoding }
|
|
401
|
+
try FileManager.default.createDirectory(at: ReplayTemporaryFiles.directory, withIntermediateDirectories: true)
|
|
402
|
+
let url = ReplayTemporaryFiles.directory.appendingPathComponent("\(Int64(expiry))-\(UUID().uuidString).mp4")
|
|
403
|
+
var success = false
|
|
404
|
+
defer { if !success { try? FileManager.default.removeItem(at: url) } }
|
|
405
|
+
let writer = try AVAssetWriter(outputURL: url, fileType: .mp4)
|
|
406
|
+
let input = AVAssetWriterInput(mediaType: .video, outputSettings: nil, sourceFormatHint: format)
|
|
407
|
+
guard writer.canAdd(input) else { throw ReplayFailure.encoding }
|
|
408
|
+
writer.add(input)
|
|
409
|
+
guard writer.startWriting() else { throw ReplayFailure.encoding }
|
|
410
|
+
writer.startSession(atSourceTime: .zero)
|
|
411
|
+
let start = CMSampleBufferGetPresentationTimeStamp(first)
|
|
412
|
+
for (index, sample) in frames.samples.enumerated() {
|
|
413
|
+
while !input.isReadyForMoreMediaData {
|
|
414
|
+
guard !Task.isCancelled, CACurrentMediaTime() < deadline, writer.status == .writing else { writer.cancelWriting(); throw ReplayFailure.expired }
|
|
415
|
+
Thread.sleep(forTimeInterval: 0.005)
|
|
416
|
+
}
|
|
417
|
+
guard !Task.isCancelled, CACurrentMediaTime() < deadline else { writer.cancelWriting(); throw ReplayFailure.expired }
|
|
418
|
+
let pts = CMSampleBufferGetPresentationTimeStamp(sample)
|
|
419
|
+
let end = index + 1 < frames.samples.count ? CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(frames.samples[index + 1])) : endTime(frames)
|
|
420
|
+
let duration = max(0, end - CMTimeGetSeconds(pts))
|
|
421
|
+
var timing = CMSampleTimingInfo(duration: CMTime(seconds: duration, preferredTimescale: 600), presentationTimeStamp: CMTimeSubtract(pts, start), decodeTimeStamp: .invalid)
|
|
422
|
+
var copy: CMSampleBuffer?
|
|
423
|
+
guard CMSampleBufferCreateCopyWithNewTiming(allocator: kCFAllocatorDefault, sampleBuffer: sample, sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleBufferOut: ©) == noErr,
|
|
424
|
+
let copy, input.append(copy) else { writer.cancelWriting(); throw ReplayFailure.encoding }
|
|
425
|
+
}
|
|
426
|
+
input.markAsFinished()
|
|
427
|
+
let done = DispatchSemaphore(value: 0)
|
|
428
|
+
writer.finishWriting { done.signal() }
|
|
429
|
+
guard done.wait(timeout: .now() + max(0, deadline - CACurrentMediaTime())) == .success, writer.status == .completed, !Task.isCancelled else { writer.cancelWriting(); throw ReplayFailure.expired }
|
|
430
|
+
success = true; return url
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/// Names encode lease expiry so pruning never reads file timestamps or host directories.
|
|
435
|
+
enum ReplayTemporaryFiles {
|
|
436
|
+
static let directory = FileManager.default.temporaryDirectory.appendingPathComponent("relay-replay", isDirectory: true)
|
|
437
|
+
private static let cleanup: Void = {
|
|
438
|
+
DispatchQueue(label: "app.feedbackrelay.replay.cleanup", qos: .utility).async { pruneExpired(in: directory, now: Date()) }
|
|
439
|
+
}()
|
|
440
|
+
static func pruneOnce() { _ = cleanup }
|
|
441
|
+
static func pruneExpired(in directory: URL, now: Date) {
|
|
442
|
+
guard let files = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) else { return }
|
|
443
|
+
for file in files where file.pathExtension == "mp4" {
|
|
444
|
+
let parts = file.deletingPathExtension().lastPathComponent.split(separator: "-", maxSplits: 1)
|
|
445
|
+
guard parts.count == 2, let expiry = Int64(parts[0]), expiry >= 0,
|
|
446
|
+
UUID(uuidString: String(parts[1])) != nil, Double(expiry) <= now.timeIntervalSince1970 * 1000 else { continue }
|
|
447
|
+
try? FileManager.default.removeItem(at: file)
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,75 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@feedbackrelay/react-native-replay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Optional local video replay for Relay React Native",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"types": "lib/index.d.ts",
|
|
7
|
+
"react-native": "lib/index.js",
|
|
8
|
+
"files": [
|
|
9
|
+
"src/NativeRelayReplay.ts",
|
|
10
|
+
"lib/index.js",
|
|
11
|
+
"lib/client.js",
|
|
12
|
+
"lib/delivery.js",
|
|
13
|
+
"lib/NativeRelayReplay.js",
|
|
14
|
+
"lib/index.d.ts",
|
|
15
|
+
"lib/client.d.ts",
|
|
16
|
+
"ios",
|
|
17
|
+
"native",
|
|
18
|
+
"RelayReplay.podspec",
|
|
19
|
+
"react-native.config.js",
|
|
20
|
+
"android/build.gradle",
|
|
21
|
+
"android/src/main/java",
|
|
22
|
+
"README.md",
|
|
23
|
+
"AGENTS.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsc -p tsconfig.json",
|
|
28
|
+
"test": "node --import tsx --test --test-concurrency=1 test/*.test.ts",
|
|
29
|
+
"codegen": "node scripts/codegen.mjs",
|
|
30
|
+
"stage-native": "node scripts/stage-native.mjs",
|
|
31
|
+
"prepack": "npm run stage-native && npm run build"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@feedbackrelay/react-native": "^0.1.1",
|
|
35
|
+
"react": "^19.2.3",
|
|
36
|
+
"react-native": ">=0.86.3 <0.87"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@feedbackrelay/react-native": "file:../react-native",
|
|
40
|
+
"@react-native/codegen": "0.86.3",
|
|
41
|
+
"@types/node": "^24.0.0",
|
|
42
|
+
"@types/react": "^19.2.0",
|
|
43
|
+
"react": "19.3.0",
|
|
44
|
+
"react-native": "0.86.3",
|
|
45
|
+
"tsx": "^4.20.0",
|
|
46
|
+
"typescript": "^5.9.0"
|
|
47
|
+
},
|
|
48
|
+
"codegenConfig": {
|
|
49
|
+
"name": "RelayReplaySpec",
|
|
50
|
+
"type": "modules",
|
|
51
|
+
"jsSrcsDir": "src",
|
|
52
|
+
"android": {
|
|
53
|
+
"javaPackageName": "app.feedbackrelay.reactnativereplay"
|
|
54
|
+
},
|
|
55
|
+
"ios": {
|
|
56
|
+
"modules": {
|
|
57
|
+
"RelayReplay": {
|
|
58
|
+
"className": "RCTRelayReplay"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
"license": "Apache-2.0",
|
|
64
|
+
"repository": {
|
|
65
|
+
"type": "git",
|
|
66
|
+
"url": "git+https://github.com/apal21/relay-sdk.git",
|
|
67
|
+
"directory": "sdk/react-native-replay"
|
|
68
|
+
},
|
|
69
|
+
"homepage": "https://github.com/apal21/relay-sdk/tree/main/sdk/react-native-replay#readme",
|
|
70
|
+
"bugs": { "url": "https://github.com/apal21/relay-sdk/issues" },
|
|
71
|
+
"publishConfig": {
|
|
72
|
+
"access": "public",
|
|
73
|
+
"registry": "https://registry.npmjs.org/"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { TurboModule } from 'react-native';
|
|
2
|
+
import { TurboModuleRegistry } from 'react-native';
|
|
3
|
+
export interface Spec extends TurboModule {
|
|
4
|
+
create(optionsJson: string): string;
|
|
5
|
+
attach(optionsJson: string): string;
|
|
6
|
+
freeze(optionsJson: string): string;
|
|
7
|
+
preview(optionsJson: string): string;
|
|
8
|
+
getCurrentFPS(recorderId: string): number;
|
|
9
|
+
materialize(leaseId: string): Promise<string>;
|
|
10
|
+
release(leaseId: string): boolean;
|
|
11
|
+
detach(attachmentId: string): boolean;
|
|
12
|
+
clear(recorderId: string): boolean;
|
|
13
|
+
destroy(recorderId: string): boolean;
|
|
14
|
+
}
|
|
15
|
+
export default TurboModuleRegistry.get<Spec>('RelayReplay');
|