Skip to content

Commit

Permalink
rebroadcast: support recording truncation
Browse files Browse the repository at this point in the history
  • Loading branch information
koush committed Mar 28, 2023
1 parent 1d4052b commit ceda54f
Showing 1 changed file with 38 additions and 5 deletions.
43 changes: 38 additions & 5 deletions plugins/prebuffer-mixin/src/file-rtsp-server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Deferred } from "@scrypted/common/src/deferred";
import { Headers, RtspServer } from "@scrypted/common/src/rtsp-server";
import fs from 'fs';
import { format } from "path";
import { Duplex } from "stream";

// non standard extension that dumps the rtp payload to a file.
Expand Down Expand Up @@ -28,17 +30,48 @@ export class FileRtspServer extends RtspServer {
ws?.end(() => ws?.destroy());
}

write(url: string, requestHeaders: Headers) {
this.cleanup();
this.segmentBytesWritten = 0;

async write(url: string, requestHeaders: Headers) {
const file = requestHeaders['x-scrypted-rtsp-file'];

if (!file)
return this.respond(400, 'Bad Request', requestHeaders, {});

const truncate = requestHeaders['x-scrypted-rtsp-file-truncate'];

// this.writeConsole?.log('RTSP WRITE file', file);
this.writeStream = fs.createWriteStream(file);

// truncation preparation must happen before cleanup.
let truncateWriteStream: fs.WriteStream;
if (truncate) {
try {
const d = new Deferred<number>();
fs.open(truncate, 'w+', (e, fd) => {
if (e)
d.reject(e);
else
d.resolve(fd);
});
const fd = await d.promise;
try {
await fs.promises.rename(truncate, file);
truncateWriteStream = fs.createWriteStream(undefined, {
fd,
})
}
catch (e) {
throw e;
}
}
catch (e) {
this.writeConsole?.error('RTSP WRITE error renaming truncate file', truncate);
}
}

// everything after this point must be sync due to cleanup potentially causing dangling state.
this.cleanup();
this.segmentBytesWritten = 0;

this.writeStream = truncateWriteStream || fs.createWriteStream(truncate || file);
this.writeStream.on('error', e => {
this.writeConsole?.error('RTSP WRITE error', e);
});
Expand Down

0 comments on commit ceda54f

Please sign in to comment.