97 lines
2.3 KiB
TypeScript
97 lines
2.3 KiB
TypeScript
import { createReadStream } from "node:fs"
|
|
import type { Readable } from "node:stream"
|
|
import type { FfmpegProcess } from "@/lib/server-ffmpeg"
|
|
|
|
const HIGH_WATER_MARK_BYTES = 256 * 1024
|
|
|
|
export type ByteRange = {
|
|
start: number
|
|
end: number
|
|
}
|
|
|
|
/**
|
|
* Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs
|
|
* when the consumer goes away (seek, track change, disconnect). `finish` runs
|
|
* when the source ends and may reject to error the stream.
|
|
*/
|
|
function toWebStream(
|
|
source: Readable,
|
|
{
|
|
cancel,
|
|
finish,
|
|
}: { cancel: () => void; finish?: () => Promise<void> }
|
|
): ReadableStream<Uint8Array> {
|
|
let done = false
|
|
|
|
return new ReadableStream<Uint8Array>(
|
|
{
|
|
start(controller) {
|
|
const fail = (error: unknown) => {
|
|
if (done) {
|
|
return
|
|
}
|
|
done = true
|
|
controller.error(error)
|
|
cancel()
|
|
}
|
|
|
|
source.on("data", (chunk: Buffer) => {
|
|
if (done) {
|
|
return
|
|
}
|
|
controller.enqueue(new Uint8Array(chunk))
|
|
if ((controller.desiredSize ?? 0) <= 0) {
|
|
source.pause()
|
|
}
|
|
})
|
|
source.once("error", fail)
|
|
source.once("end", () => {
|
|
if (done) {
|
|
return
|
|
}
|
|
void (finish?.() ?? Promise.resolve()).then(() => {
|
|
if (!done) {
|
|
done = true
|
|
controller.close()
|
|
}
|
|
}, fail)
|
|
})
|
|
},
|
|
pull() {
|
|
source.resume()
|
|
},
|
|
cancel() {
|
|
if (done) {
|
|
return
|
|
}
|
|
done = true
|
|
cancel()
|
|
},
|
|
},
|
|
new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES })
|
|
)
|
|
}
|
|
|
|
export function streamFile(path: string, range?: ByteRange) {
|
|
const file = createReadStream(path, range)
|
|
return toWebStream(file, { cancel: () => file.destroy() })
|
|
}
|
|
|
|
/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */
|
|
export function ffmpegToReadableStream({
|
|
child,
|
|
exited,
|
|
stderrTail,
|
|
}: FfmpegProcess) {
|
|
return toWebStream(child.stdout, {
|
|
cancel: () => child.kill("SIGKILL"),
|
|
finish: async () => {
|
|
const code = await exited
|
|
if (code !== 0) {
|
|
console.error(`ffmpeg transcode exited with code ${code}`, stderrTail())
|
|
throw new Error(`ffmpeg exited with code ${code}`)
|
|
}
|
|
},
|
|
})
|
|
}
|