Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## Unreleased

### Added

- `open()`, `read()`, `write()` and `close()` read and write a file in chunks
through a file descriptor (backport of upstream ffmpegwasm/ffmpeg.wasm#984).
`write()` transfers its `Uint8Array` unless `{ transfer: false }`.

### Changed

- Both cores can grow their wasm memory up to 4 GB, up from 2 GB for the
Expand Down
28 changes: 28 additions & 0 deletions apps/website/docs/getting-started/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,34 @@ Required:

Please check this PR: [abort signal](https://github.com/ffmpegwasm/ffmpeg.wasm/pull/573)

## Read and write files in chunks

`open()`, `read()`, `write()` and `close()` work on a file descriptor, so a
large file can be written as it arrives instead of held in one array.

```ts
const fd = await ffmpeg.open("input.mp4", "w");
for await (const chunk of response.body) await ffmpeg.write(fd, chunk);
await ffmpeg.close(fd);
await ffmpeg.exec(["-i", "input.mp4", "output.mp4"]);
```

- `open(path, flags)` takes Node.js-style flags (`"r"`, `"r+"`, `"w"`, `"w+"`,
`"a"`, `"a+"`) and resolves to the file descriptor.
- `read(fd, length, position?)` resolves to up to `length` bytes, empty at the
end of the file. Without `position` it continues from the last read or write.
With `position` the file offset does not move.
- `write(fd, data, position?)` resolves to the number of bytes written. The
offset moves the same way as for `read()`, except that on a descriptor
opened with `"a"` or `"a+"` every write first moves it to the end of the
file, so a write without `position` appends. Like
`writeFile()`, it transfers `data` and leaves it empty unless you pass
`{ transfer: false }` as the last argument.
- `close(fd)` releases the descriptor. Using it afterwards rejects.

The data still lives in the in-memory file system, and `exec()` reads its
input from there. This does not stream input into ffmpeg.

## Helpers: probe, transcode and extract frames

`probe()`, `transcode()` and `extractFrames()` cover common jobs without the
Expand Down
93 changes: 93 additions & 0 deletions packages/ffmpeg/src/classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ export class FFmpeg {
case FFMessageType.UNMOUNT:
case FFMessageType.EXEC:
case FFMessageType.FFPROBE:
case FFMessageType.OPEN:
case FFMessageType.READ:
case FFMessageType.WRITE:
case FFMessageType.CLOSE:
case FFMessageType.WRITE_FILE:
case FFMessageType.READ_FILE:
case FFMessageType.DELETE_FILE:
Expand Down Expand Up @@ -378,6 +382,95 @@ export class FFmpeg {
) as Promise<OK>;
};

/**
* Open a file to read or write it in chunks. `flags` are Node.js-style:
* "r", "r+", "w", "w+", "a", "a+". Resolves to a file descriptor for
* read(), write() and close().
*
* @example
* ```ts
* const fd = await ffmpeg.open("input.mp4", "w");
* for await (const chunk of response.body) await ffmpeg.write(fd, chunk);
* await ffmpeg.close(fd);
* ```
*
* @remarks
* This writes into the in-memory file system. `exec()` still reads its
* input from there once the file is complete.
*
* @category File System
*/
public open = (
path: string,
flags: string,
{ signal }: FFMessageOptions = {}
): Promise<number> =>
this.#send(
{ type: FFMessageType.OPEN, data: { path, flags } },
undefined,
signal
) as Promise<number>;

/**
* Read up to `length` bytes from `position`, or from where the last read or
* write ended. Resolves to the bytes read: fewer than `length`, and empty
* at the end of the file. A read at `position` does not move the file
* offset.
*
* @category File System
*/
public read = (
fd: number,
length: number,
position?: number,
{ signal }: FFMessageOptions = {}
): Promise<Uint8Array> =>
this.#send(
{ type: FFMessageType.READ, data: { fd, length, position } },
undefined,
signal
) as Promise<Uint8Array>;

/**
* Write `data` at `position`, or where the last read or write ended.
* Resolves to the number of bytes written. A write at `position` does not
* advance the file offset by the bytes written. On a descriptor opened
* with "a" or "a+", every write first moves the offset to the end of the
* file, so a write without `position` appends.
*
* @remarks
* Like writeFile(), `data` is transferred to the worker, which leaves it
* empty in the caller. Pass `{ transfer: false }` to copy it instead.
*
* @category File System
*/
public write = (
fd: number,
data: Uint8Array,
position?: number,
{ signal, transfer = true }: FFMessageOptions & { transfer?: boolean } = {}
): Promise<number> =>
this.#send(
{ type: FFMessageType.WRITE, data: { fd, data, position } },
transfer ? [data.buffer] : [],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: Transferring data.buffer transfers the entire underlying ArrayBuffer, not just the Uint8Array view. If callers pass a view into a larger buffer (e.g., new Uint8Array(largeBuffer, offset, length)), the whole buffer becomes unusable. This matches writeFile() behavior but is worth documenting in the method's JSDoc for clarity.

signal
) as Promise<number>;

/**
* Close a file opened with open(). The descriptor is invalid afterwards.
*
* @category File System
*/
public close = (
fd: number,
{ signal }: FFMessageOptions = {}
): Promise<OK> =>
this.#send(
{ type: FFMessageType.CLOSE, data: { fd } },
undefined,
signal
) as Promise<OK>;

public mount = (fsType: FFFSType, options: FFFSMountOptions, mountPoint: FFFSPath, ): Promise<OK> => {
const trans: Transferable[] = [];
return this.#send(
Expand Down
4 changes: 4 additions & 0 deletions packages/ffmpeg/src/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export enum FFMessageType {
LOAD = "LOAD",
EXEC = "EXEC",
FFPROBE = "FFPROBE",
OPEN = "OPEN",
READ = "READ",
WRITE = "WRITE",
CLOSE = "CLOSE",
WRITE_FILE = "WRITE_FILE",
READ_FILE = "READ_FILE",
DELETE_FILE = "DELETE_FILE",
Expand Down
25 changes: 25 additions & 0 deletions packages/ffmpeg/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ export interface FFMessageExecData {
timeout?: number;
}

export interface FFMessageOpenData {
path: FFFSPath;
flags: string;
}

export interface FFMessageReadData {
fd: number;
length: number;
position?: number;
}

export interface FFMessageWriteData {
fd: number;
data: Uint8Array;
position?: number;
}

export interface FFMessageCloseData {
fd: number;
}

export interface FFMessageWriteFileData {
path: FFFSPath;
data: FileData;
Expand Down Expand Up @@ -117,6 +138,10 @@ export interface FFMessageUnmountData {
export type FFMessageData =
| FFMessageLoadConfig
| FFMessageExecData
| FFMessageOpenData
| FFMessageReadData
| FFMessageWriteData
| FFMessageCloseData
| FFMessageWriteFileData
| FFMessageReadFileData
| FFMessageDeleteFileData
Expand Down
42 changes: 42 additions & 0 deletions packages/ffmpeg/src/worker-node-entry.mts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import type {
FFMessage,
FFMessageLoadConfig,
FFMessageExecData,
FFMessageOpenData,
FFMessageReadData,
FFMessageWriteData,
FFMessageCloseData,
FFMessageWriteFileData,
FFMessageReadFileData,
FFMessageDeleteFileData,
Expand Down Expand Up @@ -160,6 +164,32 @@ const writeFile = ({ path, data }: FFMessageWriteFileData): OK => {
return true;
};

const open = ({ path, flags }: FFMessageOpenData): number =>
ffmpeg.FS.open(path, flags).fd;

const read = ({ fd, length, position }: FFMessageReadData): Uint8Array => {
const stream = ffmpeg.FS.getStreamChecked(fd);
// Allocate no more than the file holds, whatever length asks for.
const left = ffmpeg.FS.fstat(fd).size - (position ?? stream.position);
const buffer = new Uint8Array(Math.max(0, Math.min(length, left)));
const count = ffmpeg.FS.read(stream, buffer, 0, buffer.length, position);
return count === buffer.length ? buffer : buffer.slice(0, count);
};

const write = ({ fd, data, position }: FFMessageWriteData): number =>
ffmpeg.FS.write(
ffmpeg.FS.getStreamChecked(fd),
data,
0,
data.length,
position
);

const close = ({ fd }: FFMessageCloseData): OK => {
ffmpeg.FS.close(ffmpeg.FS.getStreamChecked(fd));
return true;
};

const readFile = ({ path, encoding }: FFMessageReadFileData): FileData =>
ffmpeg.FS.readFile(path, { encoding });

Expand Down Expand Up @@ -224,6 +254,18 @@ const handleMessage = async ({ id, type, data }: FFMessage): Promise<void> => {
case FFMessageType.FFPROBE:
result = ffprobe(data as FFMessageExecData);
break;
case FFMessageType.OPEN:
result = open(data as FFMessageOpenData);
break;
case FFMessageType.READ:
result = read(data as FFMessageReadData);
break;
case FFMessageType.WRITE:
result = write(data as FFMessageWriteData);
break;
case FFMessageType.CLOSE:
result = close(data as FFMessageCloseData);
break;
case FFMessageType.WRITE_FILE:
result = writeFile(data as FFMessageWriteFileData);
break;
Expand Down
42 changes: 42 additions & 0 deletions packages/ffmpeg/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import type {
FFMessageEvent,
FFMessageLoadConfig,
FFMessageExecData,
FFMessageOpenData,
FFMessageReadData,
FFMessageWriteData,
FFMessageCloseData,
FFMessageWriteFileData,
FFMessageReadFileData,
FFMessageDeleteFileData,
Expand Down Expand Up @@ -148,6 +152,32 @@ const writeFile = ({ path, data }: FFMessageWriteFileData): OK => {
return true;
};

const open = ({ path, flags }: FFMessageOpenData): number =>
ffmpeg.FS.open(path, flags).fd;

const read = ({ fd, length, position }: FFMessageReadData): Uint8Array => {
const stream = ffmpeg.FS.getStreamChecked(fd);
// Allocate no more than the file holds, whatever length asks for.
const left = ffmpeg.FS.fstat(fd).size - (position ?? stream.position);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: The read implementation calculates remaining bytes using position ?? stream.position. This relies on Emscripten's FS.read not updating stream.position when an explicit position is provided (pread semantics). If Emscripten's behavior differs, sequential reads with and without position could desynchronize. Verify against the core's FS.read behavior or add a comment documenting the assumption.

const buffer = new Uint8Array(Math.max(0, Math.min(length, left)));
const count = ffmpeg.FS.read(stream, buffer, 0, buffer.length, position);
return count === buffer.length ? buffer : buffer.slice(0, count);
};

const write = ({ fd, data, position }: FFMessageWriteData): number =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: Similarly, write passes position directly to FS.write. The documented behavior states that a write with explicit position should not advance the file offset. This depends on Emscripten's FS.write implementing pwrite semantics. Confirm the core's behavior matches the documented contract.

ffmpeg.FS.write(
ffmpeg.FS.getStreamChecked(fd),
data,
0,
data.length,
position
);

const close = ({ fd }: FFMessageCloseData): OK => {
ffmpeg.FS.close(ffmpeg.FS.getStreamChecked(fd));
return true;
};

const readFile = ({ path, encoding }: FFMessageReadFileData): FileData =>
ffmpeg.FS.readFile(path, { encoding });

Expand Down Expand Up @@ -218,6 +248,18 @@ self.onmessage = async ({
case FFMessageType.FFPROBE:
data = ffprobe(_data as FFMessageExecData);
break;
case FFMessageType.OPEN:
data = open(_data as FFMessageOpenData);
break;
case FFMessageType.READ:
data = read(_data as FFMessageReadData);
break;
case FFMessageType.WRITE:
data = write(_data as FFMessageWriteData);
break;
case FFMessageType.CLOSE:
data = close(_data as FFMessageCloseData);
break;
case FFMessageType.WRITE_FILE:
data = writeFile(_data as FFMessageWriteFileData);
break;
Expand Down
26 changes: 26 additions & 0 deletions packages/types/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ export interface WorkerFSMountConfig {
files?: File[];
}

/**
* An open file, from FS.open().
*/
export interface FSStream {
fd: number;
position: number;
}

/**
* Functions to interact with Emscripten FS library.
*
Expand All @@ -87,6 +95,24 @@ export interface FS {
path: string
) => void;
unmount: (path: string) => void;
open: (path: string, flags: string) => FSStream;
getStreamChecked: (fd: number) => FSStream;
fstat: (fd: number) => Stat;
read: (
stream: FSStream,
buffer: Uint8Array,
offset: number,
length: number,
position?: number
) => number;
write: (
stream: FSStream,
buffer: Uint8Array,
offset: number,
length: number,
position?: number
) => number;
close: (stream: FSStream) => void;
filesystems: FSFilesystems;
}

Expand Down
Loading
Loading