Skip to content

Commit

Permalink
refactor WebmCallback and WebmFactory to improve file saving logic an…
Browse files Browse the repository at this point in the history
…d event handling
  • Loading branch information
shinyoshiaki committed Jan 10, 2025
1 parent a3b645a commit 2a8623c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
9 changes: 9 additions & 0 deletions packages/rtp/src/extra/processor/webmCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,16 @@ export class WebmCallback extends WebmBase {
};
}

/**
*
* @param path
* @returns eol
*/
export const saveToFileSystem = (path: string) => async (value: WebmOutput) => {
if (value.saveToFile) {
await appendFile(path, value.saveToFile);

return false;
} else if (value.eol) {
const { durationElement } = value.eol;
const handler = await open(path, "r+");
Expand All @@ -67,5 +74,7 @@ export const saveToFileSystem = (path: string) => async (value: WebmOutput) => {
await handler.write(resize, 0, resize.length, SegmentSizePosition);

await handler.close();

return true;
}
};
17 changes: 14 additions & 3 deletions packages/webrtc/src/nonstandard/recorder/writer/webm.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { unlink } from "fs/promises";
import { EventDisposer } from "../../../imports/common";
import { EventDisposer, Event } from "../../../imports/common";

import { MediaWriter } from ".";
import { type MediaStreamTrack, WeriftError } from "../../..";
Expand All @@ -21,7 +21,8 @@ const sourcePath = "packages/webrtc/src/nonstandard/recorder/writer/webm.ts";

export class WebmFactory extends MediaWriter {
rtpSources: RtpSourceCallback[] = [];

private onEol = new Event();
private ended = false;
unSubscribers = new EventDisposer();

async start(tracks: MediaStreamTrack[]) {
Expand Down Expand Up @@ -140,7 +141,13 @@ export class WebmFactory extends MediaWriter {
return rtpSource;
});
if (this.props.path) {
webm.pipe(saveToFileSystem(this.props.path));
webm.pipe(async (o) => {
const eol = await saveToFileSystem(this.props.path)(o);
if (eol) {
this.onEol.execute();
this.ended = true;
}
});
} else if (this.props.stream) {
webm.pipe(async (o) => {
this.props.stream.execute(o);
Expand All @@ -150,6 +157,10 @@ export class WebmFactory extends MediaWriter {

async stop() {
await Promise.all(this.rtpSources.map((r) => r.stop()));

if (!this.ended) {
await this.onEol.asPromise(5000);
}
this.unSubscribers.dispose();
}
}
Expand Down

0 comments on commit 2a8623c

Please sign in to comment.