d3ro-voice/apps/mobile-rn/src/lib/audio-recorder.ts

149 lines
4.9 KiB
TypeScript

import { Platform } from 'react-native';
import { AndroidForegroundRecorderBackend } from './recorder/android-foreground-backend';
import { NitroRecorderBackend } from './recorder/nitro-backend';
import { RecorderBusyError } from './recorder/recorder-errors';
import type {
RecordedAudio,
RecorderBackend,
RecorderOwner,
RecorderSession,
RecordingProgressHandler,
RecordingStateHandler,
StartRecordingOptions,
} from './recorder/recorder-types';
export type {
RecordedAudio,
RecorderBackend,
RecorderOwner,
RecorderSession,
RecordingProgress,
RecordingRuntimeSnapshot,
RecordingRuntimeState,
StartRecordingOptions,
} from './recorder/recorder-types';
export { RecorderBusyError } from './recorder/recorder-errors';
/**
* A capture found with no lease (the Android foreground service survives a JS
* restart) can only have come from a meeting recording.
*/
const UNLEASED_CAPTURE_OWNER: RecorderOwner = 'record';
export function createPlatformRecorderBackend(): RecorderBackend {
return Platform.OS === 'android'
? new AndroidForegroundRecorderBackend()
: new NitroRecorderBackend();
}
/**
* Facade over the platform capture backend. Screens never drive the backend
* directly: they acquire an owner-scoped {@link RecorderSession}, so a screen
* can only stop or discard a capture it holds.
*/
export class AudioRecorder {
private selectedBackend: RecorderBackend | null;
private lease: RecorderOwner | null = null;
constructor(backend?: RecorderBackend) {
this.selectedBackend = backend ?? null;
}
private get backend(): RecorderBackend {
if (this.selectedBackend === null) {
this.selectedBackend = createPlatformRecorderBackend();
}
return this.selectedBackend;
}
requestPermission(): Promise<boolean> {
return this.backend.requestPermission();
}
/**
* Returns a session for `owner`, or throws {@link RecorderBusyError} without
* touching the capture when another owner holds it.
*/
async acquire(owner: RecorderOwner): Promise<RecorderSession> {
await this.assertAvailable(owner);
return this.createSession(owner);
}
/**
* Privileged discard of whatever capture exists, regardless of owner. Only
* the account-purge boundary may call this; screens use their session.
*/
async cancel(): Promise<void> {
try {
await this.backend.cancel();
} finally {
this.lease = null;
}
}
private createSession(owner: RecorderOwner): RecorderSession {
return {
owner,
start: (onProgress: RecordingProgressHandler, options?: StartRecordingOptions) =>
this.runAsOwner(owner, true, () => this.backend.start(onProgress, options)),
pause: () => this.runAsOwner(owner, false, () => this.backend.pause()),
resume: () => this.runAsOwner(owner, false, () => this.backend.resume()),
stop: () => this.runAsOwner(owner, false, () => this.backend.stop()),
cleanup: (recording?: Pick<RecordedAudio, 'path'>) => this.cleanupAsOwner(owner, recording),
cancel: () => this.cancelAsOwner(owner),
restore: (onProgress?: RecordingProgressHandler, onStateChange?: RecordingStateHandler) =>
this.runAsOwner(owner, true, () => this.backend.restore(onProgress, onStateChange)),
};
}
private async holder(): Promise<RecorderOwner | null> {
if (!(await this.backend.isBusy())) return null;
return this.lease ?? UNLEASED_CAPTURE_OWNER;
}
private async assertAvailable(owner: RecorderOwner): Promise<void> {
const holder = await this.holder();
if (holder !== null && holder !== owner) throw new RecorderBusyError(holder);
// Another owner may have started a capture while the status was read.
if (this.lease !== null && this.lease !== owner && this.backend.hasInProcessCapture()) {
throw new RecorderBusyError(this.lease);
}
}
private async runAsOwner<T>(
owner: RecorderOwner,
claim: boolean,
operation: () => Promise<T>,
): Promise<T> {
await this.assertAvailable(owner);
if (claim) this.lease = owner;
return operation();
}
private async cleanupAsOwner(
owner: RecorderOwner,
recording?: Pick<RecordedAudio, 'path'>,
): Promise<void> {
// An explicit recording is path-scoped and cannot touch another capture;
// an implicit cleanup targets the current capture and needs ownership.
if (recording === undefined) await this.assertAvailable(owner);
await this.backend.cleanup(recording);
this.releaseIfIdle(owner);
}
private async cancelAsOwner(owner: RecorderOwner): Promise<void> {
if ((await this.holder()) !== owner) return;
if (this.lease !== null && this.lease !== owner) return;
try {
await this.backend.cancel();
} finally {
this.releaseIfIdle(owner);
}
}
private releaseIfIdle(owner: RecorderOwner): void {
if (this.lease === owner && !this.backend.hasInProcessCapture()) this.lease = null;
}
}
export const audioRecorder = new AudioRecorder();