Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Sources/verbemo/Meetings/AutoRecordController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@ final class AutoRecordController {
/// touched the microphone for `stopDelay`, `silence` means neither track
/// made a sound for `silenceStop`, and `calendar-event-ended` means the
/// far end was quiet for `calendarEndQuiet` after the event was over.
/// A confirmed call exit stops without a silence timer.
///
/// `nil` for every other reason, because the others say nothing about
/// whether a meeting happened: "app-quit" and "max-duration" mean we
Expand All @@ -730,6 +731,7 @@ final class AutoRecordController {
) -> TimeInterval? {
switch reason {
case "call-ended": return settings.stopDelay
case "call-ended-confirmed": return 0
case "silence": return settings.silenceStop
case "calendar-event-ended": return calendarEndQuiet
default: return nil
Expand Down
27 changes: 22 additions & 5 deletions Sources/verbemo/RecordingSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,13 @@ final class RecordingSession {
}
}
guard let original = integrationCall else { return }
guard let current = observations.first(where: { $0.integrationID == original.integrationID }),
let current = observations.first { $0.integrationID == original.integrationID }
if let current, current.participation == .idle, (0...5).contains(now.timeIntervalSince(current.observedAt)),
trigger != .manual, participantRecorder != nil {
endDirectCall()
return
}
guard let current,
current.participation == .inCall,
original.call == nil || original.call?.id == current.call?.id
|| (original.source != current.source && original.call?.url != nil && original.call?.url == current.call?.url) else {
Expand Down Expand Up @@ -375,18 +381,29 @@ final class RecordingSession {
guard !recordingStopped else { return }
closeDirectPeriod()
await audioCapture?.stop()
guard !recordingStopped else { return }
captureSource = .ended
endDirectCall()
}

private func endDirectCall() {
guard !recordingStopped, captureSource != .ended else { return }
closeDirectPeriod()
sourceError = nil
writeManifest()
captureSource = .ended
}

private func startFallback(after error: any Error, scope: String, permission: @MainActor @Sendable () -> Bool) async {
guard !recordingStopped, captureSource != .fallback, captureSource != .failed else { return }
guard !recordingStopped, captureSource != .ended, captureSource != .fallback, captureSource != .failed else { return }
closeDirectPeriod()
sourceError = String(describing: error)
captureSource = .preparing
await audioCapture?.stop()
guard !recordingStopped, !Task.isCancelled else { return }
if !recordingStopped, captureSource != .ended, trigger != .manual, participantRecorder != nil, integrationCall != nil {
// The room can close the audio socket before the independent call
// monitor sees the exit. Give its next polls time to confirm it.
try? await Task.sleep(for: .seconds(2))
}
guard !recordingStopped, captureSource != .ended, !Task.isCancelled else { return }
do {
guard permission() else {
throw StartFailure.microphoneAccess
Expand Down
2 changes: 2 additions & 0 deletions Sources/verbemo/Verbemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,8 @@ final class AppController {
} else if source == .direct, session.trigger != .manual {
notifyUser(title: localised("verbemo — recording started", "verbemo — запись началась"),
body: session.title ?? session.dir.lastPathComponent, opening: session.dir)
} else if source == .ended, session.trigger != .manual {
stopSession(reason: "call-ended-confirmed")
} else if source == .failed {
notifyUser(title: localised("Recording stopped: audio unavailable", "Запись остановлена: звук недоступен"),
body: session.sourceError ?? localised("Check audio access in Settings.", "Проверьте доступ к звуку в настройках."),
Expand Down
8 changes: 8 additions & 0 deletions Tests/verbemoTests/AutoRecordTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ struct AutoRecordTests {
trigger: .micActivity, reason: "call-ended", duration: 45 * 60, settings: settings))
}

@Test func confirmedCallExitUsesActualDuration() {
let minimum = settings.minDuration
#expect(!AutoRecordController.shouldDiscard(
trigger: .micActivity, reason: "call-ended-confirmed", duration: minimum, settings: settings))
#expect(AutoRecordController.shouldDiscard(
trigger: .micActivity, reason: "call-ended-confirmed", duration: minimum - 1, settings: settings))
}

/// If you pressed the button, nine seconds of it were nine seconds you
/// meant. The guard is on the trigger, not on the reason, so it holds even
/// when a manual recording happens to be stopped by one of the auto rules.
Expand Down
44 changes: 39 additions & 5 deletions Tests/verbemoTests/ParticipantCaptureLifecycleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ struct ParticipantCaptureLifecycleTests {
#expect(participants)
}

private func wait(_ condition: () -> Bool) async throws {
for _ in 0..<200 {
private func wait(attempts: Int = 200, _ condition: () -> Bool) async throws {
for _ in 0..<attempts {
if condition() { return }
try await Task.sleep(for: .milliseconds(5))
}
Expand Down Expand Up @@ -156,19 +156,24 @@ struct ParticipantCaptureLifecycleTests {
#expect(try SessionMeta.read(from: session.dir).callAudio?.periods.last?.mode == .fallback)
}

@Test func lossPreservesDirectTracksAndPauseThroughFallback() async throws {
@Test(arguments: [RecordingSession.Trigger.manual, .micActivity])
func lossPreservesDirectTracksAndPauseThroughFallback(trigger: RecordingSession.Trigger) async throws {
let root = try ParticipantAudioRecorderTests.folder()
defer { try? FileManager.default.removeItem(at: root) }
let mic = FakeMicRecorder(), system = FakeSystemRecorder(), capture = FakeCallAudioCapture()
let session = try RecordingSession(root: root, mic: mic, system: system)
let reading = CallIntegrationRecordingTests()
var context = MeetingContext()
context.applyCall(reading.observation())
let session = try RecordingSession(root: root, context: context, trigger: trigger, mic: mic, system: system)
try session.start(callAudio: { capture }, fallbackPermission: { true })
try await wait { session.captureSource == .direct }
capture.continuation.yield(.track(ParticipantAudioRecorderTests.descriptor()))
capture.continuation.yield(.audio(.init(trackID: "p1", generation: 1, frameStart: 0, sampleRate: 48000, samples: [0.5])))
try await wait { session.participantSnapshot?.tracks.count == 1 }
session.pause()
capture.continuation.finish(throwing: CallAudioFailure.timedOut)
try await wait { session.captureSource == .fallback }
session.updateCallObservation([reading.observation(.unknown)])
try await wait(attempts: 600) { session.captureSource == .fallback }
#expect(mic.isMuted && system.isMuted)
#expect(mic.privacyGate == nil)
session.stop(); await session.finishCapture()
Expand All @@ -178,6 +183,35 @@ struct ParticipantCaptureLifecycleTests {
#expect(await capture.starts == 1)
}

@Test func closedCallSocketDoesNotOpenDevicesWhenCallExitArrivesNext() async throws {
let root = try ParticipantAudioRecorderTests.folder()
defer { try? FileManager.default.removeItem(at: root) }
let mic = FakeMicRecorder(), system = FakeSystemRecorder(), capture = FakeCallAudioCapture()
let reading = CallIntegrationRecordingTests()
var context = MeetingContext()
context.applyCall(reading.observation())
let session = try RecordingSession(root: root, context: context, trigger: .micActivity, mic: mic, system: system)
try session.start(callAudio: { capture }, fallbackPermission: { true })
try await wait { session.captureSource == .direct }
capture.continuation.yield(.track(ParticipantAudioRecorderTests.descriptor()))
try await wait { session.participantSnapshot?.tracks.count == 1 }

capture.continuation.finish(throwing: POSIXError(.ENOTCONN))
try await wait { session.captureSource != .direct }
// The call monitor is independent of the audio socket and can report
// the closed room on its next poll.
try await Task.sleep(for: .milliseconds(50))
session.updateCallObservation([reading.observation(.idle)])
try await wait { session.captureSource == .ended || session.captureSource == .fallback }
#expect(session.captureSource == .ended)
#expect(mic.startCount == 0 && system.startCount == 0)
session.stop(reason: "call-ended-confirmed")
await session.finishCapture()
let meta = try SessionMeta.read(from: session.dir)
#expect(meta.callAudio?.periods.map(\.mode) == [.direct])
#expect(meta.tracks.count == 1)
}

@Test func stopWhilePreparingOrClosingDoesNotStartFallback() async throws {
let root = try ParticipantAudioRecorderTests.folder()
defer { try? FileManager.default.removeItem(at: root) }
Expand Down
Loading