fix(mobile-recorder): scope recorder control to its owner and keep Android recordings on stop failure

This commit is contained in:
Yun Chan 2026-09-28 00:54:01 +09:00
parent 72c4ddaefb
commit ace946d5c7
10 changed files with 1673 additions and 697 deletions

View file

@ -0,0 +1,373 @@
import { Dirs, FileSystem } from 'react-native-file-access';
import {
AudioEncoderAndroidType,
AudioSourceAndroidType,
AVEncoderAudioQualityIOSType,
OutputFormatAndroidType,
createSound,
type AudioSet,
type RecordBackType,
} from 'react-native-nitro-sound';
import { createUuidV4 } from '../random-id';
import type {
RecordedAudio,
RecorderBackend,
RecordingProgress,
RecordingProgressHandler,
RecordingRuntimeSnapshot,
} from './recorder-types';
const RECORDING_PREFIX = 'd3ro-recording-';
const RECORDING_EXTENSION = '.m4a';
const RECORDING_MIME_TYPE = 'audio/mp4';
const AUDIO_SETTINGS: AudioSet = {
AudioSourceAndroid: AudioSourceAndroidType.MIC,
OutputFormatAndroid: OutputFormatAndroidType.MPEG_4,
AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
AudioQuality: 'medium',
AudioChannels: 1,
AudioSamplingRate: 44100,
AudioEncodingBitRate: 128000,
AVFormatIDKeyIOS: 'aac',
AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
AVNumberOfChannelsKeyIOS: 1,
AVSampleRateKeyIOS: 44100,
};
type NitroRecorderState =
| 'idle'
| 'starting'
| 'recording'
| 'pausing'
| 'paused'
| 'resuming'
| 'stopping'
| 'stopped';
function createTemporaryPath(): string {
return `${Dirs.CacheDir}/${RECORDING_PREFIX}${createUuidV4()}${RECORDING_EXTENSION}`;
}
function pathFromFileUri(uri: string): string | null {
if (!uri.startsWith('file://')) return null;
try {
return decodeURIComponent(uri.slice('file://'.length));
} catch {
return null;
}
}
export function isOwnedTemporaryPath(path: string): boolean {
const cachePrefix = `${Dirs.CacheDir}/`;
if (!path.startsWith(cachePrefix)) return false;
const fileName = path.slice(cachePrefix.length);
return (
!fileName.includes('/') &&
!fileName.includes('\\') &&
fileName.startsWith(RECORDING_PREFIX) &&
fileName.endsWith(RECORDING_EXTENSION)
);
}
async function deleteOwnedTemporaryFile(path: string | null): Promise<void> {
if (path === null) return;
if (!isOwnedTemporaryPath(path)) {
throw new Error('Refusing to delete a recording outside the app cache');
}
if (await FileSystem.exists(path)) {
await FileSystem.unlink(path);
}
}
async function deleteStaleTemporaryFiles(): Promise<void> {
const entries = await FileSystem.ls(Dirs.CacheDir);
const stalePaths = entries
.filter(
entry =>
entry.startsWith(RECORDING_PREFIX) &&
entry.endsWith(RECORDING_EXTENSION),
)
.map(entry => `${Dirs.CacheDir}/${entry}`);
await Promise.all(stalePaths.map(deleteOwnedTemporaryFile));
}
/**
* In-process capture through Nitro Sound (iOS). This backend creates its
* .m4a files in the app cache and is the only code allowed to delete them.
*/
export class NitroRecorderBackend implements RecorderBackend {
private state: NitroRecorderState = 'idle';
private currentPath: string | null = null;
private progress: RecordingProgress = { durationMs: 0, meteringDb: null };
private pendingStart: Promise<void> | null = null;
private pendingTransition: Promise<void> | null = null;
private pendingStop: Promise<RecordedAudio> | null = null;
private sound: ReturnType<typeof createSound> | null = null;
private progressHandler: RecordingProgressHandler | null = null;
private getSound(): ReturnType<typeof createSound> {
if (this.sound !== null) return this.sound;
const sound = createSound();
sound.setSubscriptionDuration(0.1);
sound.addRecordBackListener((event: RecordBackType) => {
if (this.progressHandler === null) return;
const durationMs = Number.isFinite(event.currentPosition)
? Math.max(0, Math.round(event.currentPosition))
: this.progress.durationMs;
const meteringDb =
typeof event.currentMetering === 'number' &&
Number.isFinite(event.currentMetering)
? event.currentMetering
: null;
this.progress = { durationMs, meteringDb };
this.progressHandler(this.progress);
});
this.sound = sound;
return sound;
}
async requestPermission(): Promise<boolean> {
// Nitro Sound requests iOS microphone access through AVAudioSession.
return true;
}
async start(onProgress: RecordingProgressHandler): Promise<void> {
if (this.state !== 'idle') {
throw new Error(`Cannot start recorder while it is ${this.state}`);
}
this.state = 'starting';
try {
await deleteStaleTemporaryFiles();
} catch (error) {
this.state = 'idle';
throw error;
}
const outputPath = createTemporaryPath();
this.currentPath = outputPath;
this.progress = { durationMs: 0, meteringDb: null };
this.progressHandler = onProgress;
const sound = this.getSound();
const pendingStart = (async () => {
try {
const startedUri = await sound.startRecorder(
outputPath,
AUDIO_SETTINGS,
true,
);
const startedPath = pathFromFileUri(startedUri);
if (startedPath !== outputPath) {
throw new Error('Recorder returned an unexpected output URI');
}
this.state = 'recording';
} catch (error) {
try {
await sound.stopRecorder();
} catch {
// stopRecorder also releases the native recorder when stopping fails.
}
this.progressHandler = null;
if (this.currentPath === outputPath) this.currentPath = null;
this.state = 'idle';
await deleteOwnedTemporaryFile(outputPath);
throw error;
}
})();
this.pendingStart = pendingStart;
try {
await pendingStart;
} finally {
if (this.pendingStart === pendingStart) this.pendingStart = null;
}
}
async pause(): Promise<void> {
if (this.state !== 'recording') {
throw new Error(`Cannot pause recorder while it is ${this.state}`);
}
this.state = 'pausing';
await this.runTransition(async () => {
try {
await this.getSound().pauseRecorder();
this.state = 'paused';
} catch (error) {
this.state = 'recording';
throw error;
}
});
}
async resume(): Promise<void> {
if (this.state !== 'paused') {
throw new Error(`Cannot resume recorder while it is ${this.state}`);
}
this.state = 'resuming';
await this.runTransition(async () => {
try {
await this.getSound().resumeRecorder();
this.state = 'recording';
} catch (error) {
this.state = 'paused';
throw error;
}
});
}
async stop(): Promise<RecordedAudio> {
if (this.state !== 'recording' && this.state !== 'paused') {
throw new Error(`Cannot stop recorder while it is ${this.state}`);
}
const outputPath = this.currentPath;
if (outputPath === null) throw new Error('Recorder has no output path');
const pendingStop = (async (): Promise<RecordedAudio> => {
this.state = 'stopping';
try {
const stoppedUri = await this.getSound().stopRecorder();
const stoppedPath = pathFromFileUri(stoppedUri);
if (stoppedPath !== outputPath) {
throw new Error('Recorder did not return the expected output file');
}
const stat = await FileSystem.stat(outputPath);
if (stat.type !== 'file' || stat.size <= 0) {
throw new Error('Recorder produced an empty audio file');
}
this.state = 'stopped';
return {
uri: stoppedUri,
path: outputPath,
fileName: outputPath.slice(outputPath.lastIndexOf('/') + 1),
mimeType: RECORDING_MIME_TYPE,
size: stat.size,
durationMs: this.progress.durationMs,
};
} catch (error) {
this.currentPath = null;
this.state = 'idle';
try {
await deleteOwnedTemporaryFile(outputPath);
} catch {
// The stop failure is what the caller must see; a stale cache file
// is swept by deleteStaleTemporaryFiles() on the next start.
}
throw error;
} finally {
this.progressHandler = null;
}
})();
this.pendingStop = pendingStop;
try {
return await pendingStop;
} finally {
if (this.pendingStop === pendingStop) this.pendingStop = null;
}
}
async cleanup(recording?: Pick<RecordedAudio, 'path'>): Promise<void> {
const path = recording?.path ?? this.currentPath;
await deleteOwnedTemporaryFile(path);
if (path === this.currentPath) {
this.currentPath = null;
this.state = 'idle';
this.progress = { durationMs: 0, meteringDb: null };
}
}
async cancel(): Promise<void> {
if (this.state === 'starting' && this.pendingStart !== null) {
try {
await this.pendingStart;
} catch {
return;
}
}
if (this.state === 'stopping' && this.pendingStop !== null) {
try {
await this.pendingStop;
} catch {
return;
}
}
if (this.pendingTransition !== null) {
try {
await this.pendingTransition;
} catch {
// Continue cleanup from the stable pre-transition recording state.
}
}
const outputPath = this.currentPath;
let stopError: unknown = null;
try {
if (this.state === 'recording' || this.state === 'paused') {
await this.getSound().stopRecorder();
}
} catch (error) {
stopError = error;
} finally {
this.progressHandler = null;
this.currentPath = null;
this.state = 'idle';
this.progress = { durationMs: 0, meteringDb: null };
await deleteOwnedTemporaryFile(outputPath);
}
if (stopError !== null) throw stopError;
}
async restore(): Promise<RecordingRuntimeSnapshot> {
// Nitro captures die with the JS process; there is nothing to reattach.
return {
state: 'idle',
recording: null,
meetingId: null,
interruptionReason: null,
startedAtMs: 0,
};
}
async isBusy(): Promise<boolean> {
return this.state !== 'idle';
}
hasInProcessCapture(): boolean {
return this.state !== 'idle';
}
private async runTransition(transition: () => Promise<void>): Promise<void> {
const pendingTransition = transition();
this.pendingTransition = pendingTransition;
try {
await pendingTransition;
} finally {
if (this.pendingTransition === pendingTransition) {
this.pendingTransition = null;
}
}
}
}