Commit f93d45b for stable-diffusion.cpp

commit f93d45bb33bccf15ccfd8df63202b63431c7dc83
Author: leejet <leejet714@gmail.com>
Date:   Wed Dec 2 02:37:25 2026 +0800

    feat: unify media I/O in DGL with FFmpeg fallback (#2480)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1a70a62..858ac8d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -392,10 +392,13 @@ target_sources(${SD_LIB} PRIVATE $<TARGET_OBJECTS:zip>)
 target_link_libraries(${SD_LIB} PUBLIC ggml)
 find_package(Threads REQUIRED)
 target_link_libraries(${SD_LIB} PRIVATE Threads::Threads)
+if(WIN32)
+    target_link_libraries(${SD_LIB} PRIVATE advapi32)
+endif()
 target_link_libraries(${SD_LIB} PRIVATE onig sd-utf8proc)
 if(SD_WEBP)
     target_compile_definitions(${SD_LIB} PRIVATE SD_USE_WEBP)
-    target_link_libraries(${SD_LIB} PRIVATE webp webpdemux)
+    target_link_libraries(${SD_LIB} PRIVATE webp webpdemux libwebpmux)
 endif()
 if(SD_WEBM)
     target_compile_definitions(${SD_LIB} PRIVATE SD_USE_WEBM)
diff --git a/docs/build.md b/docs/build.md
index 9d65ead..804ba8e 100644
--- a/docs/build.md
+++ b/docs/build.md
@@ -64,19 +64,12 @@ tree for the compatibility layer's private headers.
 ## WebP and WebM Support

 WebP and WebM support are enabled by default. The library links `libwebp`,
-`libwebpdemux` and `libwebm` so DGL `video::load` works through the C API as
-well as CLI and server. WebP input supports static images and animation;
-WebM input supports this project's independent VP8 frames and PCM16 audio.
-No libvpx dependency is required. See [DGL media I/O](dgl.md) for frame-rate
-and codec restrictions.
-
-The CLI and server also use `libwebp` for WebP images. CLI WebM output reuses
-`libwebp` to encode each frame as VP8 before muxing with `libwebm`. System WebP
-packages must provide the decoder, demuxer and muxer libraries.
-
-DGL `video::encode` supports silent WebM and AVI with PCM16 audio. Requesting
-WebM audio reports an unsupported-encoder error; use `format="avi"` to include
-an audio track.
+`libwebpdemux`, the WebP muxer and `libwebm`. These codecs are shared by
+DGL, the CLI and the server. The built-in WebM reader handles independent VP8
+frames, including older files with PCM16 audio. The built-in writer produces
+silent VP8 WebM. WebM with audio uses FFmpeg with Opus. AVI supports PCM16 audio.
+See [DGL media input and output](dgl.md#media-input-and-output) for format and
+codec details.

 If you do not want WebP/WebM support, you can disable them at configure time:

diff --git a/docs/development/c_api.md b/docs/development/c_api.md
index bfa6fd1..c41bfdf 100644
--- a/docs/development/c_api.md
+++ b/docs/development/c_api.md
@@ -19,8 +19,8 @@ See the [C API guide](../guides/c_api.md) for keys, value types and ownership ru
 | `src/api/templates/` | Complete DGL execution flows and a few shared helpers. |
 | `src/api/program_result.cpp` | Adaptation of DGL tensors and dictionaries to C results. |
 | `src/api/generation_metadata.cpp` | Image parameter and WebUI infotext extraction through the metadata C API. |
-| `src/api/image_metadata.cpp` | Container metadata reading and text/JSON reports through `sd_read_metadata()`. |
-| `src/api/media_metadata.cpp`, `metadata.h` | Shared metadata encoding and C access to PNG/JPEG/XMP/AVI chunks. |
+| `src/api/image_metadata.cpp` | Container metadata reading and text/JSON reports through `media::read_metadata`. |
+| `src/api/media_metadata.cpp`, `metadata.h` | Shared PNG/JPEG/XMP/AVI metadata encoding. |
 | `src/core/option_types.h/.cpp` | Internal mode enums, name lookup and parsing. |

 Options are validated and converted at the API boundary. The translator renders
@@ -64,7 +64,8 @@ embedding are separate from inference and never rebuild the execution program.
 `src/api/generation_metadata.cpp` parses the source once to produce image
 parameters and WebUI infotext together. Examples obtain this JSON through
 `sd_get_generation_metadata()` without compiling or calling the DGL parser.
-Container reading and metadata chunk generation also use the public C API.
+The CLI reads containers through the DGL media built-in. The library's encoders
+write container metadata.
 Examples have no private `src` include path and retain generated DGL source
 without legacy JSON conversion or LoRA path rewriting.
 The translator uses an explicit `llm_path` as the text encoder's main `path`, falling back to
diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md
index b344b0e..4c367a6 100644
--- a/docs/dgl-builtins.md
+++ b/docs/dgl-builtins.md
@@ -10,6 +10,8 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn
 | `animatediff::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `animatediff` |
 | `apg` | `positive: predictor`, `negative: predictor`, `scale: number`, `image_only?: predictor`, `image_scale?: number = 1`, `schedule?: list<number>`, `eta?: number = 1`, `momentum?: number = 0`, `norm_threshold?: number = 0`, `norm_threshold_smoothing?: number = 0` | `predictor` |
 | `apply_lora` | `model: model`, `lora: lora`, `weight?: number = 1.0`, `mode?: string` | same type as `model` |
+| `audio::decode` | `data: bytes` | `dict`<br>`sample_rate: int`<br>`samples: tensor` |
+| `audio::encode` | `audio: dict`, `format?: string = "wav"`, `pcm?: string = "f32"` | `dict`<br>`data: bytes`<br>`mime_type: string` |
 | `audio::load` | `path: string` | `dict`<br>`sample_rate: int`<br>`samples: tensor` |
 | `audio::save` | `path: string`, `audio: dict`, `format?: string = "f32"` | `void` |
 | `audio_latent_shape` | `vae: audio_vae`, `frames: int`, `fps: int` | `tensor` |
@@ -29,10 +31,11 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn
 | `encode_prompt` | `encoder: text_encoder`, `text: string`, `width?: int = 512`, `height?: int = 512`, `clip_skip?: int = -1`, `system?: string`, `media?: list<any>`, `image_bindings?: dict`, `raw?: bool = false` | `dict`<br>`concat: tensor`<br>`crossattn: tensor`<br>`extra_crossattn: list<tensor>`<br>`image_embed_indices: list<tensor>`<br>`image_embeds: list<tensor>`<br>`input_ids: tensor`<br>`position_ids: tensor`<br>`ref_audios: list<tensor>`<br>`ref_images: list<tensor>`<br>`reference_blocks: list<dict>`<br>`reference_blocks.audio: int`<br>`reference_blocks.frame_index: int`<br>`reference_blocks.kind: string`<br>`reference_blocks.video: int`<br>`t5_ids: tensor`<br>`t5_weights: tensor`<br>`token_types: tensor`<br>`vector: tensor`<br>`vinput_mask: tensor` |
 | `encode_vision` | `encoder: vision_encoder`, `image: tensor`, `pooled?: bool = false`, `clip_skip?: int = -2`, `zero?: bool = false`, `zero_input?: bool = false` | `tensor` |
 | `image::canny` | `image: tensor`, `high_threshold?: number = 0.08`, `low_threshold?: number = 0.04`, `weak?: number = 0.5`, `strong?: number = 1`, `invert?: bool = false` | `tensor` |
-| `image::encode` | `image: tensor`, `format?: string = "png"` | `dict`<br>`data: bytes`<br>`mime_type: string` |
-| `image::load` | `path: string` | `tensor` |
+| `image::decode` | `data: bytes`, `channels?: int = 0`, `strict_channels?: bool = false` | `tensor` |
+| `image::encode` | `image: tensor`, `format?: string = "png"`, `quality?: int = 90`, `metadata?: string` | `dict`<br>`data: bytes`<br>`mime_type: string` |
+| `image::load` | `path: string`, `channels?: int = 0`, `strict_channels?: bool = false` | `tensor` |
 | `image::load_dir` | `path: string`, `max_images?: int = 0` | `list<tensor>` |
-| `image::save` | `path: string`, `image: tensor` | `void` |
+| `image::save` | `path: string`, `image: tensor`, `quality?: int = 90`, `metadata?: string` | `void` |
 | `image::to_f32` | `image: tensor`, `channels?: int = 0` | `tensor` |
 | `image::to_u8` | `pixels: tensor` | `tensor` |
 | `ip_adapter::apply` | `condition: dict`, `adapter: ip_adapter`, `tokens: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number` | same type as `condition`<br>`ip_adapters: ip_adapter_bindings` |
@@ -65,7 +68,9 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn
 | `math::product` | `items: i64 tensor or list<int>` | `int` |
 | `math::round` | `value: number` | `int` |
 | `math::sub` | `a: number`, `b: number` | `number` |
+| `media::read_metadata` | `path: string`, `format?: string = "text"`, `raw?: bool = false`, `brief?: bool = false`, `structural?: bool = false` | `string` |
 | `media::save` | `path: string`, `media: dict` | `void` |
+| `media::supported_formats` |  | `dict`<br>`audio: list<string>`<br>`image: list<string>`<br>`video: list<string>` |
 | `photomaker::apply` | `condition: dict`, `photomaker: photomaker`, `tokens: tensor`, `mask: tensor` | same type as `condition`<br>`crossattn: tensor` |
 | `photomaker::encode_images` | `photomaker: photomaker`, `images: list<tensor>`, `id_embedding?: tensor` | `tensor` |
 | `photomaker::encode_prompt` | `encoder: text_encoder`, `text: string`, `tokens: tensor`, `width?: int = 1024`, `height?: int = 1024`, `clip_skip?: int = -1` | `dict`<br>`condition: dict`<br>`condition.concat: tensor`<br>`condition.crossattn: tensor`<br>`condition.extra_crossattn: list<tensor>`<br>`condition.image_embed_indices: list<tensor>`<br>`condition.image_embeds: list<tensor>`<br>`condition.input_ids: tensor`<br>`condition.position_ids: tensor`<br>`condition.ref_audios: list<tensor>`<br>`condition.ref_images: list<tensor>`<br>`condition.reference_blocks: list<dict>`<br>`condition.reference_blocks.audio: int`<br>`condition.reference_blocks.frame_index: int`<br>`condition.reference_blocks.kind: string`<br>`condition.reference_blocks.video: int`<br>`condition.t5_ids: tensor`<br>`condition.t5_weights: tensor`<br>`condition.token_types: tensor`<br>`condition.vector: tensor`<br>`condition.vinput_mask: tensor`<br>`mask: tensor`<br>`plain: dict`<br>`plain.concat: tensor`<br>`plain.crossattn: tensor`<br>`plain.extra_crossattn: list<tensor>`<br>`plain.image_embed_indices: list<tensor>`<br>`plain.image_embeds: list<tensor>`<br>`plain.input_ids: tensor`<br>`plain.position_ids: tensor`<br>`plain.ref_audios: list<tensor>`<br>`plain.ref_images: list<tensor>`<br>`plain.reference_blocks: list<dict>`<br>`plain.reference_blocks.audio: int`<br>`plain.reference_blocks.frame_index: int`<br>`plain.reference_blocks.kind: string`<br>`plain.reference_blocks.video: int`<br>`plain.t5_ids: tensor`<br>`plain.t5_weights: tensor`<br>`plain.token_types: tensor`<br>`plain.vector: tensor`<br>`plain.vinput_mask: tensor` |
@@ -136,10 +141,11 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn
 | `vae_encode` | `vae: vae`, `pixels: tensor`, `rng: rng`, `tiling?: dict`, `circular_x?: bool = false`, `circular_y?: bool = false`, `posterior?: string = "sample"` | `tensor` |
 | `vae_to_dit_latents` | `vae: vae`, `latent: tensor` | `tensor` |
 | `vae_to_unet_latents` (alias of `vae_to_dit_latents`) | `vae: vae`, `latent: tensor` | `tensor` |
-| `video::encode` | `video: dict`, `audio?: dict`, `format?: string = "webm"` | `dict`<br>`data: bytes`<br>`mime_type: string` |
+| `video::decode` | `data: bytes`, `max_frames?: int = 0`, `fps_num?: int = 0`, `fps_den?: int = 1`, `audio?: bool = true` | `dict`<br>`audio: dict`<br>`audio.sample_rate: int`<br>`audio.samples: tensor`<br>`video: dict`<br>`video.fps_den: int`<br>`video.fps_num: int`<br>`video.frames: tensor` |
+| `video::encode` | `video: dict`, `audio?: dict`, `format?: string = "webm"`, `trim_audio?: bool = false`, `codec?: string = "auto"`, `quality?: int = 90`, `audio_format?: string = "pcm16"`, `metadata?: string` | `dict`<br>`data: bytes`<br>`mime_type: string` |
 | `video::join_windows` | `windows: list<tensor>`, `overlap?: int = 0` | `tensor` |
 | `video::load` | `path: string`, `max_frames?: int = 0`, `fps_num?: int = 0`, `fps_den?: int = 1`, `audio?: bool = true` | `dict`<br>`audio: dict`<br>`audio.sample_rate: int`<br>`audio.samples: tensor`<br>`video: dict`<br>`video.fps_den: int`<br>`video.fps_num: int`<br>`video.frames: tensor` |
-| `video::save` | `path: string`, `video: dict`, `audio?: dict`, `trim_audio?: bool = false`, `codec?: string = "auto"`, `quality?: int = 90`, `audio_format?: string = "f32"` | `void` |
+| `video::save` | `path: string`, `video: dict`, `audio?: dict`, `trim_audio?: bool = false`, `codec?: string = "auto"`, `quality?: int = 90`, `audio_format?: string = "f32"`, `metadata?: string` | `void` |
 | `video::split_windows` | `frames: tensor`, `size: int`, `overlap?: int = 0` | `list<tensor>` |
 | `wan::s2v_audio_window` | `embedding: tensor`, `latent_frames: int` | `tensor` |
 | `zero_out` | `condition: dict`, `fields?: list<string>` | same type as `condition` |
diff --git a/docs/dgl.md b/docs/dgl.md
index a985684..3185db5 100644
--- a/docs/dgl.md
+++ b/docs/dgl.md
@@ -7,7 +7,7 @@ Applications can generate a complete script from request settings.

 - **Getting started** · [Build and run](#build-and-run) · [Model examples](dgl/README.md)
 - **Writing scripts** · [Language syntax](#dgl-syntax) · [Tensor operations and indexing](#tensor-functions) · [Built-in catalog](dgl-builtins.md)
-- **Generation** · [Models and sampling](#independent-generation-components) · [Media I/O](#image-and-video-files) · [Regions and masks](#regions-and-masks) · [Worked examples](#advanced-component-programs)
+- **Generation** · [Models and sampling](#independent-generation-components) · [Media I/O](#media-input-and-output) · [Regions and masks](#regions-and-masks) · [Worked examples](#advanced-component-programs)
 - **Embedding DGL** · [C API](#c-api) · [Architecture](development/dgl.md)

 ## Build and run
@@ -1083,21 +1083,23 @@ Use `vae_decode(..., dtype = "f32")` to postprocess normalized float pixels in
 `[width, height, channels, batch]` or `[width, height, time, channels, batch]`
 layout. The default `"u8"` returns packed pixels.

-## Image and video files
+## Media input and output

-Media I/O uses `image::load` / `image::save`, `video::load` / `video::save`
-and `audio::load` / `audio::save`. The former global names and the aliases
-`read_image`, `read_video`, `read_audio` and `save` have been removed.
-Model loading, inference and latent operations keep their current names.
-`image::to_f32` and `image::to_u8` convert pixel representations for both images
-and video frames; ordinary tensor dtype changes use `tensor::cast`.
+DGL, the CLI and the server share the library's media codecs. Use `load` for
+files and `decode` for a `bytes` value. Use `save` to write a file or `encode`
+to return encoded bytes. Each operation is under the `image`, `audio` or `video`
+namespace. The image pixel conversions also work on video frames. Use
+`tensor::cast` for ordinary tensor dtype changes.

 ### Image files

-`image::load(path)` decodes PNG, JPEG, BMP and other formats supported by
-stb_image into a U8 tensor shaped `[channels, width, height]`. Grayscale with
-alpha is decoded as RGBA. `image::save(path, pixels)` writes a U8 pixel tensor
-to PNG and returns no value. A write failure interrupts execution.
+`image::load(path)` and `image::decode(data)` return a U8 tensor shaped
+`[channels, width, height]`. They read PNG, JPEG, BMP and other formats
+supported by stb_image. Builds with `SD_WEBP=ON` also read WebP images.
+Grayscale with alpha is decoded as RGBA. Set `channels` to 1, 3 or 4 to
+request an output layout. `strict_channels=true` rejects a source with fewer
+channels than explicitly requested. `image::save(path, image)` selects PNG,
+JPEG or WebP from the filename extension.

 ```dgl
 # version: 0.0.0
@@ -1143,44 +1145,47 @@ Both functions return tensors; they introduce no separate image value type.

 ### Encoded media and bytes

-`image::encode(image, format="png")` encodes a U8 pixel tensor in memory.
-`video::encode(video, audio?, format="webm")` encodes a complete video using
-the video dict's `fps_num` / `fps_den`. An optional audio dict is supported
-with `format="avi"`. Both return an ordinary `{data: bytes, mime_type: string}` dict.
-
-`bytes` is an immutable binary value, including embedded zero bytes. Assignments,
-arguments and return values share its buffer. It is distinct from strings and
-U8 tensors and is not converted to a flat tensor result.
+`image::encode`, `audio::encode` and `video::encode` return a dict with
+`data` (immutable bytes, including embedded zero bytes) and `mime_type`.
+The corresponding `decode` functions accept `data` directly. The
+`media::supported_formats()` result lists output formats for images, video and audio.
+The external formats in that list require the selected FFmpeg build to provide
+the requested encoder.

 ```dgl
-cover = image::encode(pixels)
-clip = video::encode(video)
-media::save("output/cover.png", cover)
-media::save("output/clip.webm", clip)
-return {cover = cover, clip = clip, latent = latent}
+clip = video::encode(video, audio=sound, format="mp4")
+media::save("output/clip.mp4", clip)
+return clip
 ```

-`media::save(path, media)` writes these exact bytes, with no re-encoding or
-metadata changes. It checks file-write permission and the extension against the
-MIME type. Omit the save calls for in-memory results only. The server's DGL
-editor displays returned media and ordinary tensor metadata in the job result.
-
-| Encoding | MIME type | Requirements |
-| --- | --- | --- |
-| PNG | `image/png` | Built in |
-| VP8 WebM | `video/webm` | `SD_WEBM=ON`; uses independent VP8 frames |
-| MJPEG + PCM16 AVI | `video/x-msvideo` | `format="avi"`; offered as a download in the editor |
-
-Unavailable encoders fail explicitly. WebM encoding rejects nonempty audio;
-use `video::encode(video, audio=sound, format="avi")` for a PCM16 soundtrack.
-Audio is never silently dropped. See [build options](build.md#webp-and-webm-support).
-`video::load` still supports only PCM16 WebM audio: pass `audio=false` to read
-frames from files with unsupported audio codecs.
-
-Encoding embeds the current program when the context's `embed_metadata` option
-is enabled. `media::save` preserves that decision. The existing `image::save`
-and `video::save` functions remain available for direct file output; AVI file
-saving continues to stream its packets instead of buffering the entire file.
+`media::save` writes the encoded bytes after checking the file-write policy
+and the extension against the MIME type. Image and video output embeds the
+current program when the context's `embed_metadata` option is enabled. Supply
+`metadata` explicitly when encoding output from another DGL run.
+
+`media::read_metadata(path, format="text", raw=false, brief=false, structural=false)`
+returns a text report or a JSON string when `format="json"`. It follows the
+context's file read policy and works without a model. See
+[generation metadata](guides/generation_metadata.md) for file metadata and
+WebUI infotext.
+
+### FFmpeg fallback
+
+Audio and video use the built-in codecs first. For unsupported media they
+try an external FFmpeg executable. Set `SD_FFMPEG_PATH` to a specific
+executable or leave it unset to search `PATH`. An unusable explicit path
+produces a configuration error. If no default executable is available, the
+original unsupported-format error is returned.
+
+FFmpeg reads local files directly when no file access callback is configured.
+Seekable MP4, MOV and M4A inputs supplied as bytes or through a file access
+callback use a file in a private temporary directory. The library removes it
+after the conversion, including on failure or cancellation. Other inputs and
+in-memory output use pipes. MP4 written to memory uses fragmented MP4. When
+file access permits a direct write, `video::save` stages the ordinary MP4 beside
+its destination and publishes it after FFmpeg succeeds.
+With a file access callback, the library checks the final path and writes the
+fragmented output itself.

 ### Reading video

@@ -1188,19 +1193,23 @@ Video frames use U8 tensors shaped `[3,width,height,frame_count]`, with
 interleaved RGB channels. Media I/O groups frames and timing in a normal video
 dict, and samples and sample rate in a normal audio dict. Computation operates
 on the tensors inside these dicts.
-`video::load` detects local files by their contents:
+`video::load` detects local files by their contents. `video::decode(data)`
+accepts bytes and uses the same frame-rate, frame-limit and audio options.
+Built-in input support includes the following.

 | Input | Supported data | Build option |
 | --- | --- | --- |
 | AVI | 24-bit RGB or MJPEG, PCM or IEEE float audio | Always available |
 | WebP | Static images or one cycle of animation; no audio | `SD_WEBP=ON` |
-| WebM | Independent VP8 keyframes and optional PCM16 audio, as written by this project's CLI | `SD_WEBM=ON` |
+| WebM | Independent VP8 keyframes, including legacy files with PCM16 audio | `SD_WEBM=ON` |

 WebP animation decoding handles partial frames, blending and disposal before
 returning full RGB canvases. Transparent pixels are composited onto black.
-WebM interframe VP8, VP9, laced packets and delayed audio are unsupported;
-unsupported audio reports an error suggesting `audio=false`. MP4 and segmented
-OpenDML AVI are unsupported. Paths support spaces and Unicode.
+The FFmpeg fallback can read formats such as H.264 MP4, VP9/Opus WebM and
+segmented OpenDML AVI. It normalizes video to a constant frame rate, using
+the rate requested by the script when present. Without FFmpeg, the built-in
+WebM path supports independent VP8 frames and the optional PCM16 track.
+Set `audio=false` to skip decoding the soundtrack.

 ```dgl
 # version: 0.0.0
@@ -1260,14 +1269,13 @@ applies when reading source video.

 ### Writing video

-`video::save(path, video, codec="auto", quality=90)` writes `.avi` only.
-The video dict requires `frames`, `fps_num` and `fps_den`. Both frame-rate
-integers must be in [1,1000000]; timing is explicit.
-Saving accepts already allocated frame tensors larger than the loading limit
-and encodes them one frame at a time. It sets the playback rate without
-resampling frames. Supply `audio` for a soundtrack. `trim_audio=true` truncates
-audio longer than the video duration;
-shorter audio is retained unchanged. The default is `false`.
+`video::save(path, video, codec="auto", quality=90)` selects AVI, WebM,
+animated WebP or MP4 from the path. `video::encode` takes the same options
+and selects the container with `format`. The video dict requires `frames`,
+`fps_num` and `fps_den`. Supply `audio` for formats that support a soundtrack.
+`trim_audio=true` truncates audio at the video duration and keeps shorter
+audio intact. The default is `false`.
+AVI file output streams frames directly to disk.

 ```dgl
 video = {frames = pixels, fps_num = 24, fps_den = 1}
@@ -1276,22 +1284,27 @@ processed = {frames = processed_frames, fps_num = input.video.fps_num, fps_den =
 video::save("upscaled.avi", processed, audio = input.audio)
 ```

-`codec="auto"` selects `mjpeg`; `quality` ranges from 1 to 90, with higher
-values preserving more detail. Use `codec="rgb"` for uncompressed, pixel-exact
-RGB output; it ignores `quality` and produces larger files. Both codecs support
-odd frame dimensions. Audio is saved as float32 by default;
-`audio_format="pcm16"` writes PCM16. AVI output is limited to less than 4 GiB.
-Saving has no return value and does not alter the supplied frames or audio.
-Return frame tensors, frame rate and audio explicitly when needed as graph
-results. Audio trimming applies only to the file. MJPEG decoding need not match
-the input pixels exactly.
+AVI defaults to MJPEG with `codec="auto"`. Set `codec="rgb"` for
+uncompressed RGB. Quality ranges from 1 to 100. AVI output supports odd
+dimensions and has a 4 GiB limit. For AVI, `audio_format` selects float32
+or PCM16. The built-in WebM encoder writes silent independent VP8 frames.
+WebM with audio uses FFmpeg and Opus. Select `codec="vp9"` to use the FFmpeg
+encoder for silent WebM as well.
+The FFmpeg MP4 encoder uses H.264/AAC and pads odd dimensions to even values.
+Animated WebP uses the built-in WebP encoder and supports video only.
+Frame boundaries are rounded to the nearest millisecond. Encoding fails if
+this leaves any frame with zero duration.

 ### Audio files

-`audio::load(path)` reads WAV with PCM8/16/24/32 or float32 samples.
-`audio::save(path, audio, format="f32")` writes WAV, with `pcm16` also available.
-`audio::load` and `audio_vae_decode` return a normal dict with `samples` (F32
-`[channels,samples]` tensor) and `sample_rate` (Hz). Construct the same dict to
+`audio::load(path)` and `audio::decode(data)` read PCM8/16/24/32 and
+float32/64 WAV, including WAVE_FORMAT_EXTENSIBLE PCM and float.
+With FFmpeg they also read formats such as MP3, FLAC and AAC.
+`audio::save(path, audio, format="f32")` writes WAV as float32 or `pcm16`.
+Select a `.flac`, `.mp3` or `.m4a` path to use FFmpeg. For an in-memory
+result, `audio::encode(audio, format="wav", pcm="f32")` supports the same
+containers. Decoding returns a dict with `samples` (F32 `[channels,samples]`)
+and `sample_rate` (Hz). Construct the same dict to
 save generated or processed samples. Rates range from 1,000 to 384,000 Hz,
 with 1..32 channels and a 256 MiB sample limit. Samples must be finite.

@@ -1714,26 +1727,29 @@ sd_dgl_ctx_free(ctx);
 Keep the context alive until all calls using it return. Free it with
 `sd_dgl_ctx_free` when its cached components are no longer needed.

-### Host tensor inputs
+### Host tensor, string and byte inputs

-Standalone scripts can read tensors with `tensor::load(path)` or embed them
-with `tensor::literal`. A C host can pass source with named tensor parameters
-directly to `sd_dgl_run`. Supply exactly one binding per parameter. Compilation
-always permits these parameters; a missing binding reports a missing input.
-Unknown or duplicate names and null tensors are also rejected.
-Bindings share the existing immutable tensor handles. The same source can be
-run with different bindings on subsequent calls; each call compiles it anew.
-Use `sd_dgl_check(source, true)` when only validation is needed.
+Pass named bindings to `sd_dgl_run` with one `sd_dgl_input_t` per parameter
+of `fn main(...)`. The input kind determines the parameter's DGL type at
+compile time. Each tensor binding retains its tensor handle. A string binding
+copies a NUL-terminated string. On Windows, pass file paths as UTF-8. On POSIX
+systems, string bindings can carry native path bytes, including paths that
+cannot be written as UTF-8 source literals. Byte bindings copy the buffers
+into DGL-owned storage, including embedded zero bytes.
+A null byte pointer is valid for an empty buffer. Use `sd_dgl_check` for
+standalone scripts or scripts with tensor parameters.

 ```c
-/* ctx is an existing DGL context and pixels is an immutable tensor. */
-const char* source = "fn main(pixels) { return { image = pixels, label = \"input\" } }";
+/* bytes and length describe an encoded image read by the host. */
+const char* source = "fn main(upload) { return image::decode(upload) }";
+sd_dgl_input_t input = {0};
+input.name = "upload";
+input.kind = SD_DGL_INPUT_BYTES;
+input.value.bytes.data = bytes;
+input.value.bytes.size = length;
 sd_dgl_result_t* result = NULL;
-const sd_dgl_tensor_input_t input = {"pixels", pixels};
-sd_status_t status = sd_dgl_run(ctx, source, &input, 1, &result);
-if (status == SD_STATUS_OK) {
-    const sd_dgl_value_t* root = sd_dgl_result_root(result);
-    const sd_tensor_t* image = sd_dgl_value_tensor(sd_dgl_value_field(root, "image"));
+if (sd_dgl_run(ctx, source, &input, 1, &result) == SD_STATUS_OK) {
+    const sd_tensor_t* image = sd_dgl_value_tensor(sd_dgl_result_root(result));
     sd_tensor_save(image, "pixels-copy.npy");
 }
 sd_dgl_result_free(result);
diff --git a/docs/guides/generation_metadata.md b/docs/guides/generation_metadata.md
index 9cdaab6..0130696 100644
--- a/docs/guides/generation_metadata.md
+++ b/docs/guides/generation_metadata.md
@@ -69,30 +69,21 @@ Memory encoding and file saving use the same metadata writer. Disabling metadata
 still disables embedding. Previously generated files with combined WebUI text
 and `SDCPP:` JSON remain readable.

-DGL `image::save` (PNG) and `video::save` (AVI) also embed the exact program
-source by default, using `dgl` and `ICMT` respectively. `image::encode` and
-`video::encode` embed it during encoding; `media::save` writes those bytes
-unchanged. WebM uses the `COMMENT` tag. These script functions store the program
-itself without deriving WebUI infotext. Set the DGL context
-option `embed_metadata` to `off` to omit it; `sd-cli -M dgl` forwards
-`--disable-image-metadata` to that option. The switch also disables embedding
-in the ordinary CLI image and video output paths. It does not affect tensor
-data or the source returned by `sd_result_get_generation_info`.
+DGL image and video encoders use the current script as the metadata source
+by default. An explicit `metadata` argument supplies a different source.
+The image writer includes WebUI infotext when it can infer image-generation
+parameters from that source. Set the DGL context option `embed_metadata` to
+`off` to disable automatic source embedding. An explicit empty `metadata`
+argument also produces output without embedded generation metadata.
+`sd-cli` uses `--disable-image-metadata` for both ordinary generation and DGL
+scripts. Server SD API responses populate `infotexts` independently of this
+setting.

 Inspect metadata with `sd-cli -M metadata --image FILE`, optionally adding
 `--metadata-format json` for a structured report. This command reads container
 metadata without loading a model.

-The C API provides the same reader through `sd_read_metadata(path, flags)`.
-Use zero for the default text report, or combine `SD_METADATA_READ_JSON`,
-`SD_METADATA_READ_RAW`, `SD_METADATA_READ_BRIEF` and
-`SD_METADATA_READ_STRUCTURAL`. A null return indicates an error; inspect
-`sd_get_last_error()`. The returned UTF-8 report is borrowed until the next
-call to this function on the same thread.
-
-For applications that encode their own files, `sd_get_metadata_chunk()` builds
-PNG iTXt chunks, JPEG COM segments, XMP text or an AVI INFO chunk. It returns
-borrowed bytes and their exact size; copy them before the next call on the same
-thread. PNG chunks are inserted after IHDR, JPEG segments after SOI, XMP is
-stored in the container's XMP field, and AVI INFO is a RIFF chunk. Empty source
-returns an empty chunk. This function does not write a file.
+DGL provides the same report through `media::read_metadata(path)` as text.
+Set `format="json"` for a JSON string. Use `raw=true` for raw payloads,
+`brief=true` for a compact text report, or `structural=true` to include
+structural entries. The read follows the DGL context's file access policy.
diff --git a/examples/cli/CMakeLists.txt b/examples/cli/CMakeLists.txt
index b93b3e7..d857bf2 100644
--- a/examples/cli/CMakeLists.txt
+++ b/examples/cli/CMakeLists.txt
@@ -4,7 +4,6 @@ add_executable(${TARGET}
     ../common/common.cpp
     ../common/log.cpp
     ../common/media_io.cpp
-    ../common/media_metadata.cpp
     main.cpp
     dgl.cpp
     media_input.cpp
@@ -17,14 +16,6 @@ target_include_directories(${TARGET} PRIVATE
 )
 install(TARGETS ${TARGET} RUNTIME)
 target_link_libraries(${TARGET} PRIVATE stable-diffusion zip ${CMAKE_THREAD_LIBS_INIT})
-if(SD_WEBP)
-    target_compile_definitions(${TARGET} PRIVATE SD_USE_WEBP)
-    target_link_libraries(${TARGET} PRIVATE webp libwebpmux)
-endif()
-if(SD_WEBM)
-    target_compile_definitions(${TARGET} PRIVATE SD_USE_WEBM)
-    target_link_libraries(${TARGET} PRIVATE webm)
-endif()
 target_compile_features(${TARGET} PUBLIC c_std_11 cxx_std_17)

 set(SD_DGL_BUILTIN_CATALOG "${PROJECT_SOURCE_DIR}/docs/dgl-builtins.md")
diff --git a/examples/cli/README.md b/examples/cli/README.md
index d8c5a0f..459c86c 100644
--- a/examples/cli/README.md
+++ b/examples/cli/README.md
@@ -32,12 +32,13 @@ upscaling use explicit DGL workflows. Their former native CLI options and the
 `--ref-video` accepts a frame directory or a video file. Directories retain
 filename order and 24 fps; files are decoded through DGL `video::load` at
 24 fps. Supported embedded audio is retained unless a matching
-`--ref-video-audio` WAV overrides it. `--control-video` accepts the same inputs;
-files are sampled at the generation `--fps` (default 16), without audio, and
-`--video-frames` limits decoding after resampling. Existing VACE frame padding
-is unchanged. File formats are AVI, static/animated WebP, and this project's
-independent-frame VP8 WebM. VP9 and Opus are unsupported; see
-[DGL media I/O](../../docs/dgl.md) for codec and build requirements.
+`--ref-video-audio` file overrides it. `--control-video` accepts the same inputs.
+Files are sampled at the generation `--fps` (default 16), without audio.
+`--video-frames` limits decoding after resampling. The built-in codecs read
+AVI, static or animated WebP, and independent-frame VP8 WebM. With FFmpeg,
+the CLI can also read H.264 MP4 and VP9/Opus WebM, and write MP4.
+See [DGL media input and output](../../docs/dgl.md#media-input-and-output)
+for codec and build requirements and the `SD_FFMPEG_PATH` override.

 Logging defaults to `info`. Use `--log-level <level>` to select `debug`, `verbose`,
 `info`, `warn`, or `error` (from most to least detailed). Each level includes
diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp
index a40c9fc..dd9089f 100644
--- a/examples/cli/main.cpp
+++ b/examples/cli/main.cpp
@@ -48,7 +48,7 @@ struct SDCliParams {

     std::string preview_method = "none";
     int preview_interval       = 1;
-    std::string preview_path   = "preview.png";
+    std::string preview_path;
     int preview_fps            = 16;
     bool preview_noisy         = false;
     bool color                 = false;
@@ -67,7 +67,7 @@ struct SDCliParams {
         options.string_options = {
             {"-o",
              "--output",
-             "path to write result image to. you can use printf-style %d format specifiers for image sequences (default: ./output.png) (eg. output_%03d.png). Single-file video outputs support .avi, .webm, and animated .webp",
+             "path to write result image to. you can use printf-style %d format specifiers for image sequences (default: ./output.png) (eg. output_%03d.png). Single-file video outputs support .avi, .webm, animated .webp, and .mp4 (FFmpeg)",
              0,
              &output_path},
             {"",
@@ -82,7 +82,7 @@ struct SDCliParams {
              &metadata_format},
             {"",
              "--preview-path",
-             "path to write preview image to (default: ./preview.png). For image generation, the filename can have %03d placeholder for sequential numbering. Multi-frame previews support .avi, .webm, and animated .webp",
+             "preview output path (default: preview.png for one frame, preview.avi for multiple frames). Image paths can use %03d for sequential numbering. Multi-frame previews support .avi, .webm, animated .webp, and .mp4 (FFmpeg)",
              0,
              &preview_path},
             {"",
@@ -352,7 +352,7 @@ void step_callback(int step, int frame_count, const sd_tensor_t* const* tensors,
     // is_noisy is set to true if the preview corresponds to noisy latents, false if it's denoised latents
     // unused in this app, it will either be always noisy or always denoised here
     if (frame_count == 1) {
-        fs::path path = fs::u8path(cli_params->preview_path);
+        fs::path path = fs::u8path(cli_params->preview_path.empty() ? "preview.png" : cli_params->preview_path);
         if (encoded_image_format_from_path(path.u8string()) == EncodedImageFormat::UNKNOWN)
             path += ".png";
         if (std::regex_search(path.u8string(), format_specifier_regex))
@@ -367,9 +367,14 @@ void step_callback(int step, int frame_count, const sd_tensor_t* const* tensors,
             LOG_ERROR("save preview image to '%s' failed", path.u8string().c_str());
         }
     } else {
-        int fps = cli_params->preview_method == "proj" ? cli_params->preview_fps / 4 : cli_params->preview_fps;
-        if (create_video_from_sd_images(cli_params->preview_path.c_str(), image, frame_count, fps, cli_params->compression_quality) != 0) {
-            LOG_ERROR("save preview video to '%s' failed", cli_params->preview_path.c_str());
+        const int fps  = cli_params->preview_method == "proj" ? cli_params->preview_fps / 4 : cli_params->preview_fps;
+        auto path      = fs::u8path(cli_params->preview_path.empty() ? "preview.avi" : cli_params->preview_path);
+        auto extension = path.extension().u8string();
+        std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+        if (extension != ".avi" && extension != ".webm" && extension != ".webp" && extension != ".mp4")
+            path.replace_extension(".avi");
+        if (create_video_from_sd_images(path.u8string().c_str(), image, frame_count, fps, cli_params->compression_quality) != 0) {
+            LOG_ERROR("save preview video to '%s' failed", path.u8string().c_str());
         }
     }
 }
@@ -386,7 +391,7 @@ static fs::path get_video_audio_sidecar_path(const SDCliParams& cli_params) {
             output_format == EncodedImageFormat::PNG ||
             output_format == EncodedImageFormat::WEBP ||
             ext_lower == ".avi" ||
-            ext_lower == ".webm") {
+            ext_lower == ".webm" || ext_lower == ".mp4") {
             base_path.replace_extension();
         }
     }
@@ -429,7 +434,7 @@ bool save_results(const SDCliParams& cli_params,
             output_format == EncodedImageFormat::PNG ||
             output_format == EncodedImageFormat::WEBP ||
             ext_lower == ".avi" ||
-            ext_lower == ".webm") {
+            ext_lower == ".webm" || ext_lower == ".mp4") {
             base_path.replace_extension();
         }
     }
@@ -486,7 +491,7 @@ bool save_results(const SDCliParams& cli_params,
     }

     if (cli_params.mode == VID_GEN && num_results > 1) {
-        if (ext_lower != ".avi" && ext_lower != ".webp" && ext_lower != ".webm")
+        if (ext_lower != ".avi" && ext_lower != ".webp" && ext_lower != ".webm" && ext_lower != ".mp4")
             ext = ".avi";
         std::string params = gen_params.embed_image_metadata
                                  ? video_info
@@ -496,8 +501,8 @@ bool save_results(const SDCliParams& cli_params,
         video_path += ext;
         std::string final_ext_lower = ext.u8string();
         std::transform(final_ext_lower.begin(), final_ext_lower.end(), final_ext_lower.begin(), ::tolower);
-        const bool mux_audio = generated_audio != nullptr && (final_ext_lower == ".avi" || final_ext_lower == ".webm");
-        if (create_video_from_sd_images(video_path.u8string().c_str(), results.data(), num_results, gen_params.fps.value(), cli_params.compression_quality, mux_audio ? generated_audio : nullptr, params) == 0) {
+        const bool mux_audio = generated_audio != nullptr && (final_ext_lower == ".avi" || final_ext_lower == ".webm" || final_ext_lower == ".mp4");
+        if (create_video_from_sd_images(video_path.u8string().c_str(), results.data(), num_results, gen_params.fps.value(), cli_params.compression_quality, mux_audio ? generated_audio : nullptr, params, results.video_frames()) == 0) {
             LOG_INFO("save result video to '%s'", video_path.u8string().c_str());
             if (generated_audio != nullptr && !mux_audio) {
                 fs::path wav_path = video_path;
@@ -550,21 +555,11 @@ int main(int argc, const char* argv[]) {
     }

     if (cli_params.mode == METADATA) {
-        uint32_t flags = 0;
-        if (cli_params.metadata_format == "json")
-            flags |= SD_METADATA_READ_JSON;
-        if (cli_params.metadata_raw)
-            flags |= SD_METADATA_READ_RAW;
-        if (cli_params.metadata_brief)
-            flags |= SD_METADATA_READ_BRIEF;
-        if (cli_params.metadata_all)
-            flags |= SD_METADATA_READ_STRUCTURAL;
-        const auto* output = sd_read_metadata(cli_params.image_path.c_str(), flags);
-        if (!output) {
-            LOG_ERROR("%s", sd_get_last_error());
+        const auto output = read_media_metadata(cli_params.image_path, cli_params.metadata_format,
+                                                cli_params.metadata_raw, cli_params.metadata_brief, cli_params.metadata_all);
+        if (!output)
             return 1;
-        }
-        print_utf8(stdout, output);
+        print_utf8(stdout, output->c_str());
         return 0;
     }

@@ -573,19 +568,6 @@ int main(int argc, const char* argv[]) {
         return 1;
     }

-    if (cli_params.mode == VID_GEN || gen_params.video_frames > 4) {
-        size_t last_dot_pos   = cli_params.preview_path.find_last_of(".");
-        std::string base_path = cli_params.preview_path;
-        std::string file_ext  = "";
-        if (last_dot_pos != std::string::npos) {  // filename has extension
-            base_path = cli_params.preview_path.substr(0, last_dot_pos);
-            file_ext  = cli_params.preview_path.substr(last_dot_pos);
-            std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), ::tolower);
-        }
-        if (file_ext == ".png") {
-            cli_params.preview_path = base_path + ".avi";
-        }
-    }
     if (gen_params.fps)
         cli_params.preview_fps = *gen_params.fps;

@@ -674,8 +656,8 @@ int main(int argc, const char* argv[]) {
         std::vector<float> samples;
         uint32_t sample_rate = 0;
         uint32_t channels    = 0;
-        if (!load_wav_from_file(path, samples, sample_rate, channels)) {
-            LOG_ERROR("load WAV audio from '%s' failed", path.c_str());
+        if (!load_audio_from_file(path, samples, sample_rate, channels)) {
+            LOG_ERROR("load audio from '%s' failed", path.c_str());
             return false;
         }
         audio.reset(std::move(samples), sample_rate, channels);
@@ -821,6 +803,7 @@ int main(int argc, const char* argv[]) {
     }

     if (ctx_params.esrgan_path.size() > 0 && gen_params.upscale_repeats > 0) {
+        results.release_video_result();
         UpscalerCtxPtr upscaler_ctx(create_sd_upscaler(ctx_params.esrgan_path.c_str(),
                                                        ctx_params.diffusion_conv_direct,
                                                        ctx_params.n_threads,
diff --git a/examples/cli/media_input.cpp b/examples/cli/media_input.cpp
index ce9d073..ece84c0 100644
--- a/examples/cli/media_input.cpp
+++ b/examples/cli/media_input.cpp
@@ -6,7 +6,6 @@
 #include <sstream>

 #include "common/media_io.h"
-#include "json.hpp"

 bool load_images_from_dir(const std::string& dir,
                           std::vector<SDImageOwner>& images,
@@ -60,7 +59,7 @@ bool load_images_from_dir(const std::string& dir,

 bool load_video_input(const std::string& path, int fps, size_t max_frames, bool audio, VideoInput& result) {
     std::ostringstream source;
-    source << "fn main() { return video::load(" << nlohmann::json(path).dump()
+    source << "fn main(path) { return video::load(path"
            << ", fps_num = " << fps << ", max_frames = " << max_frames
            << ", audio = " << (audio ? "true" : "false") << ") }";
     std::unique_ptr<sd_dgl_ctx_t, decltype(&sd_dgl_ctx_free)> context(sd_dgl_ctx_create_once(), sd_dgl_ctx_free);
@@ -69,7 +68,8 @@ bool load_video_input(const std::string& path, int fps, size_t max_frames, bool
         return false;
     }
     sd_dgl_result_t* raw_result = nullptr;
-    if (sd_dgl_run(context.get(), source.str().c_str(), nullptr, 0, &raw_result) != SD_STATUS_OK) {
+    const auto path_input       = media_path_input(path.c_str());
+    if (sd_dgl_run(context.get(), source.str().c_str(), &path_input, 1, &raw_result) != SD_STATUS_OK) {
         LOG_ERROR("cannot read video input '%s': %s", path.c_str(), sd_dgl_error());
         return false;
     }
@@ -119,8 +119,8 @@ bool load_reference_video_inputs(const std::vector<std::string>& paths, const st
         if (external_audio) {
             std::vector<float> samples;
             uint32_t rate = 0, channels = 0;
-            if (!load_wav_from_file(audio_paths[i], samples, rate, channels)) {
-                LOG_ERROR("load WAV audio from '%s' failed", audio_paths[i].c_str());
+            if (!load_audio_from_file(audio_paths[i], samples, rate, channels)) {
+                LOG_ERROR("load audio from '%s' failed", audio_paths[i].c_str());
                 return false;
             }
             const int64_t shape[] = {channels, int64_t(samples.size() / channels)};
diff --git a/examples/common/common.cpp b/examples/common/common.cpp
index 9d9ad70..1101f94 100644
--- a/examples/common/common.cpp
+++ b/examples/common/common.cpp
@@ -1592,11 +1592,11 @@ ArgOptions SDGenerationParams::get_options() {
          on_ref_video_arg},
         {"",
          "--ref-video-audio",
-         "WAV soundtrack overriding embedded audio, paired by index with --ref-video (can be used multiple times)",
+         "soundtrack overriding embedded audio, paired by index with --ref-video (can be used multiple times)",
          on_ref_video_audio_arg},
         {"",
          "--ref-audio",
-         "standalone WAV reference for MiniMax-H3 Ref2VA (can be used multiple times)",
+         "standalone audio reference for MiniMax-H3 Ref2VA (can be used multiple times)",
          on_ref_audio_arg},
         {"",
          "--audio",
@@ -1718,7 +1718,7 @@ bool decode_base64_image(const std::string& encoded_input,
     int decoded_height   = 0;
     int resolved_channel = target_channels;
     uint8_t* raw_data    = load_image_from_memory(reinterpret_cast<const char*>(image_bytes.data()),
-                                                  static_cast<int>(image_bytes.size()),
+                                                  image_bytes.size(),
                                                   decoded_width,
                                                   decoded_height,
                                                   resolved_channel,
@@ -1780,7 +1780,7 @@ static bool parse_image_array_json_field(const json& parent,
     return true;
 }

-/** Parses a JSON array of base64 WAV strings into owned audio clips. */
+/** Parses a JSON array of base64 audio strings into owned audio clips. */
 static bool parse_audio_array_json_field(const json& parent,
                                          const char* key,
                                          std::vector<SDAudioOwner>& out_audios) {
@@ -1812,7 +1812,7 @@ static bool parse_audio_array_json_field(const json& parent,
         std::vector<float> samples;
         uint32_t sample_rate = 0;
         uint32_t channels    = 0;
-        if (!load_wav_from_memory(audio_bytes.data(), audio_bytes.size(), samples, sample_rate, channels)) {
+        if (!load_audio_from_memory(audio_bytes.data(), audio_bytes.size(), samples, sample_rate, channels)) {
             return false;
         }
         SDAudioOwner audio;
diff --git a/examples/common/media_io.cpp b/examples/common/media_io.cpp
index 941c70b..0b1d942 100644
--- a/examples/common/media_io.cpp
+++ b/examples/common/media_io.cpp
@@ -1,1562 +1,300 @@
 #include "media_io.h"
-#include "log.h"
-#include "media_metadata.h"
-#include "resource_owners.hpp"

 #include <algorithm>
 #include <cctype>
-#include <cmath>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
 #include <filesystem>
-#include <fstream>
-#include <string>
-#include <vector>
+#include <sstream>

-#define STB_IMAGE_IMPLEMENTATION
-#define STB_IMAGE_STATIC
-#define STBI_WINDOWS_UTF8
-#include "stb_image.h"
+#include "json.hpp"

-#define STB_IMAGE_WRITE_IMPLEMENTATION
-#define STB_IMAGE_WRITE_STATIC
-#define STBIW_WINDOWS_UTF8
-#include "stb_image_write.h"
-
-#define STB_IMAGE_RESIZE_IMPLEMENTATION
 #define STB_IMAGE_RESIZE_STATIC
+#define STB_IMAGE_RESIZE_IMPLEMENTATION
 #include "stb_image_resize.h"

-#ifdef SD_USE_WEBP
-#include "webp/decode.h"
-#include "webp/encode.h"
-#include "webp/mux.h"
-#endif
-
-#ifdef SD_USE_WEBM
-#include "mkvmuxer/mkvmuxer.h"
-#include "mkvmuxer/mkvwriter.h"
-#endif
-
-namespace fs = std::filesystem;
-
-#ifdef SD_USE_WEBP
-struct WebPFreeDeleter {
-    void operator()(void* ptr) const {
-        if (ptr != nullptr) {
-            WebPFree(ptr);
-        }
-    }
-};
-
-struct WebPMuxDeleter {
-    void operator()(WebPMux* mux) const {
-        if (mux != nullptr) {
-            WebPMuxDelete(mux);
-        }
-    }
-};
-
-struct WebPAnimEncoderDeleter {
-    void operator()(WebPAnimEncoder* enc) const {
-        if (enc != nullptr) {
-            WebPAnimEncoderDelete(enc);
-        }
-    }
-};
-
-struct WebPDataGuard {
-    WebPDataGuard() {
-        WebPDataInit(&data);
-    }
-
-    ~WebPDataGuard() {
-        WebPDataClear(&data);
-    }
-
-    WebPData data;
-};
-
-struct WebPPictureGuard {
-    WebPPictureGuard()
-        : initialized(WebPPictureInit(&picture) != 0) {
-    }
-
-    ~WebPPictureGuard() {
-        if (initialized) {
-            WebPPictureFree(&picture);
-        }
-    }
-
-    WebPPicture picture;
-    bool initialized;
-};
-
-using WebPBufferPtr      = std::unique_ptr<uint8_t, WebPFreeDeleter>;
-using WebPMuxPtr         = std::unique_ptr<WebPMux, WebPMuxDeleter>;
-using WebPAnimEncoderPtr = std::unique_ptr<WebPAnimEncoder, WebPAnimEncoderDeleter>;
-#endif
+using MediaResult = std::unique_ptr<sd_dgl_result_t, decltype(&sd_dgl_result_free)>;

-#ifdef SD_USE_WEBM
-class MemoryMkvWriter : public mkvmuxer::IMkvWriter {
-public:
-    mkvmuxer::int32 Write(const void* buf, mkvmuxer::uint32 len) override {
-        if (buf == nullptr && len > 0) {
-            return -1;
-        }
-        const size_t end_pos = position_ + static_cast<size_t>(len);
-        if (end_pos > data_.size()) {
-            data_.resize(end_pos);
-        }
-        if (len > 0) {
-            memcpy(data_.data() + position_, buf, len);
-        }
-        position_ = end_pos;
-        return 0;
-    }
-
-    mkvmuxer::int64 Position() const override {
-        return static_cast<mkvmuxer::int64>(position_);
-    }
-
-    mkvmuxer::int32 Position(mkvmuxer::int64 position) override {
-        if (position < 0) {
-            return -1;
-        }
-        const size_t target = static_cast<size_t>(position);
-        if (target > data_.size()) {
-            data_.resize(target);
-        }
-        position_ = target;
-        return 0;
-    }
-
-    bool Seekable() const override {
-        return true;
-    }
-
-    void ElementStartNotify(mkvmuxer::uint64, mkvmuxer::int64) override {
-    }
-
-    const std::vector<uint8_t>& data() const {
-        return data_;
-    }
-
-private:
-    std::vector<uint8_t> data_;
-    size_t position_ = 0;
-};
-#endif
-
-bool read_binary_file_bytes(const char* path, std::vector<uint8_t>& data) {
-    std::ifstream fin(fs::u8path(path), std::ios::binary);
-    if (!fin) {
-        return false;
-    }
-
-    fin.seekg(0, std::ios::end);
-    std::streampos size = fin.tellg();
-    if (size < 0) {
-        return false;
-    }
-    fin.seekg(0, std::ios::beg);
-
-    data.resize(static_cast<size_t>(size));
-    if (!data.empty()) {
-        fin.read(reinterpret_cast<char*>(data.data()), size);
-        if (!fin) {
-            return false;
-        }
-    }
-    return true;
-}
-
-bool write_binary_file_bytes(const std::string& path, const std::vector<uint8_t>& data) {
-    std::ofstream fout(fs::u8path(path), std::ios::binary);
-    if (!fout) {
-        return false;
-    }
-
-    if (!data.empty()) {
-        fout.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
-        if (!fout) {
-            return false;
-        }
-    }
-    return true;
-}
-
-uint32_t read_u32_le_bytes(const uint8_t* data) {
-    return static_cast<uint32_t>(data[0]) |
-           (static_cast<uint32_t>(data[1]) << 8) |
-           (static_cast<uint32_t>(data[2]) << 16) |
-           (static_cast<uint32_t>(data[3]) << 24);
-}
-
-int stbi_ext_write_png_to_func(stbi_write_func* func,
-                               void* context,
-                               int x,
-                               int y,
-                               int comp,
-                               const void* data,
-                               int stride_bytes,
-                               const char* parameters) {
-    int len            = 0;
-    unsigned char* png = stbi_write_png_to_mem((const unsigned char*)data, stride_bytes, x, y, comp, &len, parameters);
-    if (png == nullptr) {
-        return 0;
-    }
-    func(context, png, len);
-    STBIW_FREE(png);
-    return 1;
+static MediaResult run_media(const std::string& source, const sd_dgl_input_t* inputs = nullptr, size_t count = 0) {
+    std::unique_ptr<sd_dgl_ctx_t, decltype(&sd_dgl_ctx_free)> context(sd_dgl_ctx_create_once(), sd_dgl_ctx_free);
+    sd_dgl_result_t* result = nullptr;
+    if (!context || sd_dgl_run(context.get(), source.c_str(), inputs, count, &result) != SD_STATUS_OK)
+        LOG_ERROR("media I/O failed: %s", sd_dgl_error());
+    return MediaResult(result, sd_dgl_result_free);
 }

-bool is_webp_signature(const uint8_t* data, size_t size) {
-    return size >= 12 &&
-           memcmp(data, "RIFF", 4) == 0 &&
-           memcmp(data + 8, "WEBP", 4) == 0;
+static sd_dgl_input_t tensor_input(const char* name, const sd_tensor_t* tensor) {
+    sd_dgl_input_t input{};
+    input.name         = name;
+    input.kind         = SD_DGL_INPUT_TENSOR;
+    input.value.tensor = tensor;
+    return input;
 }

-std::string xml_escape(const std::string& value) {
-    std::string escaped;
-    escaped.reserve(value.size());
-
-    for (char ch : value) {
-        switch (ch) {
-            case '&':
-                escaped += "&amp;";
-                break;
-            case '<':
-                escaped += "&lt;";
-                break;
-            case '>':
-                escaped += "&gt;";
-                break;
-            case '"':
-                escaped += "&quot;";
-                break;
-            case '\'':
-                escaped += "&apos;";
-                break;
-            default:
-                escaped += ch;
-                break;
-        }
-    }
-
-    return escaped;
+static sd_dgl_input_t bytes_input(const char* name, const void* data, size_t size) {
+    sd_dgl_input_t input{};
+    input.name        = name;
+    input.kind        = SD_DGL_INPUT_BYTES;
+    input.value.bytes = {data, size};
+    return input;
 }

-#ifdef SD_USE_WEBP
-uint8_t* decode_webp_image_to_buffer(const uint8_t* data,
-                                     size_t size,
-                                     int& width,
-                                     int& height,
-                                     int expected_channel,
-                                     int& source_channel_count) {
-    WebPBitstreamFeatures features;
-    if (WebPGetFeatures(data, size, &features) != VP8_STATUS_OK) {
-        return nullptr;
-    }
-
-    width                = features.width;
-    height               = features.height;
-    source_channel_count = features.has_alpha ? 4 : 3;
-
-    if (expected_channel == 0) {
-        expected_channel = source_channel_count;
-    }
-
-    const size_t pixel_count = static_cast<size_t>(width) * static_cast<size_t>(height);
-
-    if (expected_channel == 1) {
-        int decoded_width  = width;
-        int decoded_height = height;
-        WebPBufferPtr decoded(features.has_alpha
-                                  ? WebPDecodeRGBA(data, size, &decoded_width, &decoded_height)
-                                  : WebPDecodeRGB(data, size, &decoded_width, &decoded_height));
-        if (decoded == nullptr) {
-            return nullptr;
-        }
-
-        FreeUniquePtr<uint8_t> grayscale((uint8_t*)malloc(pixel_count));
-        if (grayscale == nullptr) {
-            return nullptr;
-        }
-
-        const int decoded_channels = features.has_alpha ? 4 : 3;
-        for (size_t i = 0; i < pixel_count; ++i) {
-            const uint8_t* src = decoded.get() + i * decoded_channels;
-            grayscale.get()[i] = static_cast<uint8_t>((77 * src[0] + 150 * src[1] + 29 * src[2] + 128) >> 8);
-        }
-
-        return grayscale.release();
-    }
-
-    if (expected_channel != 3 && expected_channel != 4) {
-        return nullptr;
-    }
-
-    int decoded_width  = width;
-    int decoded_height = height;
-    WebPBufferPtr decoded((expected_channel == 4)
-                              ? WebPDecodeRGBA(data, size, &decoded_width, &decoded_height)
-                              : WebPDecodeRGB(data, size, &decoded_width, &decoded_height));
-    if (decoded == nullptr) {
-        return nullptr;
-    }
-
-    const size_t out_size = pixel_count * static_cast<size_t>(expected_channel);
-    FreeUniquePtr<uint8_t> output((uint8_t*)malloc(out_size));
-    if (output == nullptr) {
-        return nullptr;
+static std::vector<uint8_t> encoded_result(const MediaResult& result, std::string* mime_type = nullptr) {
+    if (!result)
+        return {};
+    const auto* root  = sd_dgl_result_root(result.get());
+    const void* bytes = nullptr;
+    size_t size       = 0;
+    if (sd_dgl_value_get_bytes(sd_dgl_value_field(root, "data"), &bytes, &size) != SD_STATUS_OK || !size)
+        return {};
+    if (mime_type) {
+        const char* mime = nullptr;
+        size_t length    = 0;
+        if (sd_dgl_value_get_string(sd_dgl_value_field(root, "mime_type"), &mime, &length) != SD_STATUS_OK)
+            return {};
+        mime_type->assign(mime, length);
     }
-
-    memcpy(output.get(), decoded.get(), out_size);
-    return output.release();
+    const auto* first = static_cast<const uint8_t*>(bytes);
+    return {first, first + size};
 }

-static bool embed_webp_metadata(std::vector<uint8_t>& image, const std::string& parameters) {
-    if (parameters.empty())
-        return true;
-    WebPData data{image.data(), image.size()};
-    WebPMuxPtr mux(WebPMuxCreate(&data, 1));
-    if (!mux)
-        return false;
-    const auto xmp = generation_xmp(parameters);
-    WebPData xmp_data{reinterpret_cast<const uint8_t*>(xmp.data()), xmp.size()};
-    if (WebPMuxSetChunk(mux.get(), "XMP ", &xmp_data, 1) != WEBP_MUX_OK)
-        return false;
-    WebPDataGuard assembled;
-    if (WebPMuxAssemble(mux.get(), &assembled.data) != WEBP_MUX_OK)
-        return false;
-    image.assign(assembled.data.bytes, assembled.data.bytes + assembled.data.size);
-    return true;
+std::vector<std::string> media_output_formats(const char* kind) {
+    const auto result = run_media("fn main() { return media::supported_formats() }");
+    if (!result)
+        return {};
+    const auto* formats = sd_dgl_value_field(sd_dgl_result_root(result.get()), kind);
+    std::vector<std::string> names;
+    for (size_t i = 0; i < sd_dgl_value_count(formats); ++i) {
+        const char* value = nullptr;
+        size_t size       = 0;
+        if (sd_dgl_value_get_string(sd_dgl_value_at(formats, i), &value, &size) == SD_STATUS_OK)
+            names.emplace_back(value, size);
+    }
+    return names;
+}
+
+std::optional<std::string> read_media_metadata(const std::string& path, const std::string& format, bool raw, bool brief, bool structural) {
+    const auto input  = media_path_input(path.c_str());
+    const auto source = std::string("fn main(path) { return media::read_metadata(path") +
+                        ", format=" + nlohmann::json(format).dump() +
+                        ", raw=" + (raw ? "true" : "false") +
+                        ", brief=" + (brief ? "true" : "false") +
+                        ", structural=" + (structural ? "true" : "false") + ") }";
+    const auto result = run_media(source, &input, 1);
+    if (!result)
+        return std::nullopt;
+    const char* text = nullptr;
+    size_t size      = 0;
+    if (sd_dgl_value_get_string(sd_dgl_result_root(result.get()), &text, &size) != SD_STATUS_OK)
+        return std::nullopt;
+    return std::string(text, size);
 }

-bool encode_webp_image_to_vector(const uint8_t* image,
-                                 int width,
-                                 int height,
-                                 int channels,
-                                 const std::string& parameters,
-                                 int quality,
-                                 std::vector<uint8_t>& out) {
-    if (image == nullptr || width <= 0 || height <= 0) {
-        return false;
-    }
-
-    std::vector<uint8_t> rgb_image;
-    const uint8_t* input_image = image;
-    int input_channels         = channels;
-
-    if (channels == 1) {
-        rgb_image.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * 3);
-        for (int i = 0; i < width * height; ++i) {
-            rgb_image[i * 3 + 0] = image[i];
-            rgb_image[i * 3 + 1] = image[i];
-            rgb_image[i * 3 + 2] = image[i];
-        }
-        input_image    = rgb_image.data();
-        input_channels = 3;
-    }
-
-    if (input_channels != 3 && input_channels != 4) {
-        return false;
-    }
-
-    uint8_t* encoded_raw = nullptr;
-    size_t encoded_size  = (input_channels == 4)
-                               ? WebPEncodeRGBA(input_image, width, height, width * input_channels, static_cast<float>(quality), &encoded_raw)
-                               : WebPEncodeRGB(input_image, width, height, width * input_channels, static_cast<float>(quality), &encoded_raw);
-    WebPBufferPtr encoded(encoded_raw);
-    if (encoded == nullptr || encoded_size == 0) {
-        return false;
-    }
-
-    out.assign(encoded.get(), encoded.get() + encoded_size);
-
-    return embed_webp_metadata(out, parameters);
+EncodedImageFormat encoded_image_format_from_path(const std::string& path) {
+    auto ext = std::filesystem::u8path(path).extension().u8string();
+    std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+    if (ext == ".jpg" || ext == ".jpeg" || ext == ".jpe")
+        return EncodedImageFormat::JPEG;
+    if (ext == ".png")
+        return EncodedImageFormat::PNG;
+    if (ext == ".webp")
+        return EncodedImageFormat::WEBP;
+    return EncodedImageFormat::UNKNOWN;
 }

-#ifdef SD_USE_WEBM
-bool extract_vp8_frame_from_webp(const std::vector<uint8_t>& webp_data, std::vector<uint8_t>& vp8_frame) {
-    if (!is_webp_signature(webp_data.data(), webp_data.size())) {
-        return false;
-    }
-
-    size_t offset = 12;
-    while (offset + 8 <= webp_data.size()) {
-        const uint8_t* chunk     = webp_data.data() + offset;
-        const uint32_t chunk_len = read_u32_le_bytes(chunk + 4);
-        const size_t chunk_start = offset + 8;
-        const size_t padded_len  = static_cast<size_t>(chunk_len) + (chunk_len & 1u);
-
-        if (chunk_start + chunk_len > webp_data.size()) {
-            return false;
-        }
-
-        if (memcmp(chunk, "VP8 ", 4) == 0) {
-            vp8_frame.assign(webp_data.data() + chunk_start,
-                             webp_data.data() + chunk_start + chunk_len);
-            return !vp8_frame.empty();
-        }
-
-        offset = chunk_start + padded_len;
-    }
-
-    return false;
+std::vector<uint8_t> encode_image_to_vector(EncodedImageFormat format, const uint8_t* image, int width, int height, int channels, const std::string& parameters, int quality) {
+    const char* name = format == EncodedImageFormat::JPEG ? "jpeg" : format == EncodedImageFormat::PNG ? "png"
+                                                                 : format == EncodedImageFormat::WEBP  ? "webp"
+                                                                                                       : nullptr;
+    if (!name || !image || width < 1 || height < 1 || (channels != 1 && channels != 3 && channels != 4))
+        return {};
+    const auto tensor = image_tensor({uint32_t(width), uint32_t(height), uint32_t(channels), const_cast<uint8_t*>(image)});
+    if (!tensor)
+        return {};
+    const auto input  = tensor_input("pixels", tensor.get());
+    const auto source = "fn main(pixels) { return image::encode(pixels, format=" + nlohmann::json(name).dump() +
+                        ", metadata=" + nlohmann::json(parameters).dump() +
+                        ", quality=" + std::to_string(std::clamp(quality, 1, 100)) + ") }";
+    return encoded_result(run_media(source, &input, 1));
 }

-bool encode_sd_image_to_vp8_frame(const SDImage& image, int quality, std::vector<uint8_t>& vp8_frame) {
-    if (image.data == nullptr || image.width == 0 || image.height == 0) {
-        return false;
-    }
-
-    const int width         = static_cast<int>(image.width);
-    const int height        = static_cast<int>(image.height);
-    const int input_channel = static_cast<int>(image.channel);
-    if (input_channel != 1 && input_channel != 3 && input_channel != 4) {
+bool write_image_to_file(const std::string& path, const uint8_t* image, int width, int height, int channels, const std::string& parameters, int quality) {
+    if (!image || width < 1 || height < 1 || (channels != 1 && channels != 3 && channels != 4))
         return false;
-    }
-
-    std::vector<uint8_t> rgb_buffer;
-    const uint8_t* rgb_data = image.data;
-    if (input_channel == 1) {
-        rgb_buffer.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * 3);
-        for (int i = 0; i < width * height; ++i) {
-            rgb_buffer[i * 3 + 0] = image.data[i];
-            rgb_buffer[i * 3 + 1] = image.data[i];
-            rgb_buffer[i * 3 + 2] = image.data[i];
-        }
-        rgb_data = rgb_buffer.data();
-    } else if (input_channel == 4) {
-        rgb_buffer.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * 3);
-        for (int i = 0; i < width * height; ++i) {
-            rgb_buffer[i * 3 + 0] = image.data[i * 4 + 0];
-            rgb_buffer[i * 3 + 1] = image.data[i * 4 + 1];
-            rgb_buffer[i * 3 + 2] = image.data[i * 4 + 2];
-        }
-        rgb_data = rgb_buffer.data();
-    }
-
-    std::vector<uint8_t> encoded_webp;
-    if (!encode_webp_image_to_vector(rgb_data, width, height, 3, "", quality, encoded_webp)) {
+    const auto tensor = image_tensor({uint32_t(width), uint32_t(height), uint32_t(channels), const_cast<uint8_t*>(image)});
+    if (!tensor)
         return false;
-    }
-
-    return extract_vp8_frame_from_webp(encoded_webp, vp8_frame);
+    const sd_dgl_input_t inputs[] = {tensor_input("pixels", tensor.get()), media_path_input(path.c_str())};
+    const auto source             = "fn main(pixels,path) { image::save(path, pixels, metadata=" + nlohmann::json(parameters).dump() +
+                        ", quality=" + std::to_string(std::clamp(quality, 1, 100)) + ") }";
+    return bool(run_media(source, inputs, 2));
 }
-#endif
-#endif
-
-uint8_t* load_image_common(bool from_memory,
-                           const char* image_path_or_bytes,
-                           int len,
-                           int& width,
-                           int& height,
-                           int expected_width,
-                           int expected_height,
-                           int expected_channel,
-                           int& out_channel) {
-    const char* image_path;
-    FreeUniquePtr<uint8_t> image_buffer;
-    int source_channel_count = 0;
-
-#ifdef SD_USE_WEBP
-    if (from_memory) {
-        image_path = "memory";
-        if (len > 0 && is_webp_signature(reinterpret_cast<const uint8_t*>(image_path_or_bytes), static_cast<size_t>(len))) {
-            image_buffer.reset(decode_webp_image_to_buffer(reinterpret_cast<const uint8_t*>(image_path_or_bytes),
-                                                           static_cast<size_t>(len),
-                                                           width,
-                                                           height,
-                                                           expected_channel,
-                                                           source_channel_count));
-        }
-    } else {
-        image_path = image_path_or_bytes;
-        if (encoded_image_format_from_path(image_path_or_bytes) == EncodedImageFormat::WEBP) {
-            std::vector<uint8_t> file_bytes;
-            if (!read_binary_file_bytes(image_path_or_bytes, file_bytes)) {
-                LOG_ERROR("load image from '%s' failed", image_path_or_bytes);
-                return nullptr;
-            }
-            if (!is_webp_signature(file_bytes.data(), file_bytes.size())) {
-                LOG_ERROR("load image from '%s' failed", image_path_or_bytes);
-                return nullptr;
-            }
-            image_buffer.reset(decode_webp_image_to_buffer(file_bytes.data(),
-                                                           file_bytes.size(),
-                                                           width,
-                                                           height,
-                                                           expected_channel,
-                                                           source_channel_count));
-        }
-    }
-#endif

-    if (from_memory) {
-        image_path = "memory";
-        if (image_buffer == nullptr) {
-            int c = 0;
-            image_buffer.reset((uint8_t*)stbi_load_from_memory((const stbi_uc*)image_path_or_bytes, len, &width, &height, &c, expected_channel));
-            source_channel_count = c;
-        }
-    } else {
-        image_path = image_path_or_bytes;
-        if (image_buffer == nullptr) {
-            int c = 0;
-            image_buffer.reset((uint8_t*)stbi_load(image_path_or_bytes, &width, &height, &c, expected_channel));
-            source_channel_count = c;
-        }
-    }
-    if (image_buffer == nullptr) {
-        LOG_ERROR("load image from '%s' failed", image_path);
+static uint8_t* image_pixels(const MediaResult& result, int& width, int& height, int& channels, int expected_width, int expected_height, bool promote_gray) {
+    if (!result)
         return nullptr;
-    }
-    if (expected_channel == 0) {
-        expected_channel = source_channel_count == 2 ? 4 : (source_channel_count == 1 ? 3 : source_channel_count);
-        if (expected_channel != source_channel_count) {
-            FreeUniquePtr<uint8_t> promoted((uint8_t*)malloc((size_t)width * height * expected_channel));
-            if (promoted == nullptr) {
-                LOG_ERROR("error: allocate memory for channel promotion, image_path = %s", image_path);
-                return nullptr;
-            }
-            const size_t pixel_count = (size_t)width * (size_t)height;
-            for (size_t i = 0; i < pixel_count; ++i) {
-                if (source_channel_count == 1) {
-                    promoted.get()[i * 3 + 0] = image_buffer.get()[i];
-                    promoted.get()[i * 3 + 1] = image_buffer.get()[i];
-                    promoted.get()[i * 3 + 2] = image_buffer.get()[i];
-                } else {
-                    promoted.get()[i * 4 + 0] = image_buffer.get()[i * 2];
-                    promoted.get()[i * 4 + 1] = image_buffer.get()[i * 2];
-                    promoted.get()[i * 4 + 2] = image_buffer.get()[i * 2];
-                    promoted.get()[i * 4 + 3] = image_buffer.get()[i * 2 + 1];
-                }
-            }
-            image_buffer         = std::move(promoted);
-            source_channel_count = expected_channel;
-        }
-    }
-    // stb reports the source channel count even when it converts the output.
-    if (source_channel_count < expected_channel) {
-        fprintf(stderr,
-                "the number of channels for the input image must be >= %d,"
-                "but got %d channels, image_path = %s",
-                expected_channel,
-                source_channel_count,
-                image_path);
+    const auto* tensor = sd_dgl_result_tensor(result.get(), "image");
+    if (!tensor)
         return nullptr;
-    }
-    if (width <= 0) {
-        LOG_ERROR("error: the width of image must be greater than 0, image_path = %s", image_path);
+    const auto view = tensor_image_view(tensor);
+    width           = int(view.width);
+    height          = int(view.height);
+    channels        = promote_gray && view.channel == 1 ? 3 : int(view.channel);
+    int crop_x = 0, crop_y = 0, crop_w = width, crop_h = height;
+    const bool resize = expected_width > 0 && expected_height > 0 && (width != expected_width || height != expected_height);
+    if (resize) {
+        const float src_aspect = float(width) / height;
+        const float dst_aspect = float(expected_width) / expected_height;
+        if (src_aspect > dst_aspect)
+            crop_w = std::max(1, int(height * dst_aspect));
+        else if (src_aspect < dst_aspect)
+            crop_h = std::max(1, int(width / dst_aspect));
+        crop_x = (width - crop_w) / 2;
+        crop_y = (height - crop_h) / 2;
+    }
+
+    const uint8_t* pixels = view.data;
+    std::vector<uint8_t> rgb;
+    if (view.channel == 1 && channels == 3) {
+        rgb.resize(size_t(width) * height * 3);
+        for (size_t i = 0; i < rgb.size(); ++i)
+            rgb[i] = pixels[i / 3];
+        pixels = rgb.data();
+    }
+    pixels += (size_t(crop_y) * width + crop_x) * channels;
+    const int out_width  = resize ? expected_width : width;
+    const int out_height = resize ? expected_height : height;
+    if (out_width > 16384 || out_height > 16384 || uint64_t(out_width) * out_height > 64 * 1024 * 1024)
         return nullptr;
-    }
-    if (height <= 0) {
-        LOG_ERROR("error: the height of image must be greater than 0, image_path = %s", image_path);
+    std::unique_ptr<uint8_t, FreeDeleter> out(static_cast<uint8_t*>(malloc(size_t(out_width) * out_height * channels)));
+    if (!out)
         return nullptr;
-    }
-
-    if ((expected_width > 0 && expected_height > 0) && (height != expected_height || width != expected_width)) {
-        float dst_aspect = (float)expected_width / (float)expected_height;
-        float src_aspect = (float)width / (float)height;
-
-        int crop_x = 0, crop_y = 0;
-        int crop_w = width, crop_h = height;
-
-        if (src_aspect > dst_aspect) {
-            crop_w = (int)(height * dst_aspect);
-            crop_x = (width - crop_w) / 2;
-        } else if (src_aspect < dst_aspect) {
-            crop_h = (int)(width / dst_aspect);
-            crop_y = (height - crop_h) / 2;
-        }
-
-        if (crop_x != 0 || crop_y != 0) {
-            LOG_INFO("crop input image from %dx%d to %dx%d, image_path = %s", width, height, crop_w, crop_h, image_path);
-            FreeUniquePtr<uint8_t> cropped_image_buffer((uint8_t*)malloc(crop_w * crop_h * expected_channel));
-            if (cropped_image_buffer == nullptr) {
-                LOG_ERROR("error: allocate memory for crop\n");
-                return nullptr;
-            }
-            for (int row = 0; row < crop_h; row++) {
-                uint8_t* src = image_buffer.get() + ((crop_y + row) * width + crop_x) * expected_channel;
-                uint8_t* dst = cropped_image_buffer.get() + (row * crop_w) * expected_channel;
-                memcpy(dst, src, crop_w * expected_channel);
-            }
-
-            width        = crop_w;
-            height       = crop_h;
-            image_buffer = std::move(cropped_image_buffer);
-        }
-
-        LOG_INFO("resize input image from %dx%d to %dx%d", width, height, expected_width, expected_height);
-        FreeUniquePtr<uint8_t> resized_image_buffer((uint8_t*)malloc(expected_height * expected_width * expected_channel));
-        if (resized_image_buffer == nullptr) {
-            LOG_ERROR("error: allocate memory for resize input image\n");
+    if (resize) {
+        if (!stbir_resize(pixels, crop_w, crop_h, width * channels, out.get(), out_width, out_height, 0, STBIR_TYPE_UINT8,
+                          channels, channels == 4 ? 3 : STBIR_ALPHA_CHANNEL_NONE, 0,
+                          STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_SRGB, nullptr))
             return nullptr;
-        }
-        stbir_resize(image_buffer.get(), width, height, 0,
-                     resized_image_buffer.get(), expected_width, expected_height, 0, STBIR_TYPE_UINT8,
-                     expected_channel, expected_channel == 4 ? 3 : STBIR_ALPHA_CHANNEL_NONE, 0,
-                     STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP,
-                     STBIR_FILTER_BOX, STBIR_FILTER_BOX,
-                     STBIR_COLORSPACE_SRGB, nullptr);
-        width        = expected_width;
-        height       = expected_height;
-        image_buffer = std::move(resized_image_buffer);
-    }
-    out_channel = expected_channel;
-    return image_buffer.release();
-}
-
-typedef struct {
-    uint32_t offset;
-    uint32_t size;
-} avi_index_entry;
-
-typedef struct {
-    char fourcc[4];
-    uint32_t flags;
-    uint32_t offset;
-    uint32_t size;
-} avi_chunk_index_entry;
-
-void write_u32_le(FILE* f, uint32_t val) {
-    fwrite(&val, 4, 1, f);
-}
-
-void write_u16_le(FILE* f, uint16_t val) {
-    fwrite(&val, 2, 1, f);
-}
-
-void write_u32_le(std::vector<uint8_t>& data, uint32_t val) {
-    data.push_back(static_cast<uint8_t>(val & 0xFF));
-    data.push_back(static_cast<uint8_t>((val >> 8) & 0xFF));
-    data.push_back(static_cast<uint8_t>((val >> 16) & 0xFF));
-    data.push_back(static_cast<uint8_t>((val >> 24) & 0xFF));
-}
-
-void write_u16_le(std::vector<uint8_t>& data, uint16_t val) {
-    data.push_back(static_cast<uint8_t>(val & 0xFF));
-    data.push_back(static_cast<uint8_t>((val >> 8) & 0xFF));
-}
-
-void patch_u32_le(std::vector<uint8_t>& data, size_t offset, uint32_t val) {
-    if (offset + 4 > data.size()) {
-        return;
-    }
-    data[offset + 0] = static_cast<uint8_t>(val & 0xFF);
-    data[offset + 1] = static_cast<uint8_t>((val >> 8) & 0xFF);
-    data[offset + 2] = static_cast<uint8_t>((val >> 16) & 0xFF);
-    data[offset + 3] = static_cast<uint8_t>((val >> 24) & 0xFF);
-}
-
-void write_fourcc(std::vector<uint8_t>& data, const char* fourcc) {
-    data.insert(data.end(), fourcc, fourcc + 4);
-}
-
-static std::vector<uint8_t> audio_to_pcm16_bytes(const SDAudio* audio) {
-    if (audio == nullptr || audio->data == nullptr || audio->sample_count == 0 || audio->channels == 0 || audio->sample_rate == 0) {
-        return {};
-    }
-
-    const size_t pcm_samples = static_cast<size_t>(audio->sample_count) * static_cast<size_t>(audio->channels);
-    std::vector<uint8_t> bytes(pcm_samples * sizeof(int16_t));
-    auto* pcm = reinterpret_cast<int16_t*>(bytes.data());
-    for (size_t i = 0; i < pcm_samples; ++i) {
-        const float sample = std::clamp(audio->data[i], -1.0f, 1.0f);
-        pcm[i]             = static_cast<int16_t>(std::lrint(sample * 32767.0f));
-    }
-    return bytes;
-}
-
-static std::pair<uint64_t, uint64_t> audio_sample_range_for_video_frame(const SDAudio* audio, int frame_idx, int num_frames, int fps) {
-    if (audio == nullptr || fps <= 0 || num_frames <= 0) {
-        return {0, 0};
-    }
-    const uint64_t total = audio->sample_count;
-    const uint64_t start = static_cast<uint64_t>((static_cast<long double>(frame_idx) * total) / num_frames);
-    const uint64_t end   = frame_idx + 1 == num_frames
-                               ? total
-                               : static_cast<uint64_t>((static_cast<long double>(frame_idx + 1) * total) / num_frames);
-    return {start, std::max(start, end)};
-}
-
-EncodedImageFormat encoded_image_format_from_path(const std::string& path) {
-    std::string ext = fs::u8path(path).extension().u8string();
-    std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
-
-    if (ext == ".jpg" || ext == ".jpeg" || ext == ".jpe") {
-        return EncodedImageFormat::JPEG;
-    }
-    if (ext == ".png") {
-        return EncodedImageFormat::PNG;
-    }
-    if (ext == ".webp") {
-        return EncodedImageFormat::WEBP;
-    }
-    return EncodedImageFormat::UNKNOWN;
-}
-
-std::vector<uint8_t> encode_image_to_vector(EncodedImageFormat format,
-                                            const uint8_t* image,
-                                            int width,
-                                            int height,
-                                            int channels,
-                                            const std::string& parameters,
-                                            int quality) {
-    std::vector<uint8_t> buffer;
-
-    auto write_func = [&buffer](void* context, void* data, int size) {
-        (void)context;
-        uint8_t* src = reinterpret_cast<uint8_t*>(data);
-        buffer.insert(buffer.end(), src, src + size);
-    };
-
-    struct ContextWrapper {
-        decltype(write_func)& func;
-    } ctx{write_func};
-
-    auto c_func = [](void* context, void* data, int size) {
-        auto* wrapper = reinterpret_cast<ContextWrapper*>(context);
-        wrapper->func(context, data, size);
-    };
-
-    int result = 0;
-    switch (format) {
-        case EncodedImageFormat::JPEG:
-            result = stbi_write_jpg_to_func(c_func, &ctx, width, height, channels, image, quality);
-            break;
-        case EncodedImageFormat::PNG:
-            result = stbi_ext_write_png_to_func(c_func, &ctx, width, height, channels, image, width * channels, nullptr);
-            break;
-        case EncodedImageFormat::WEBP:
-#ifdef SD_USE_WEBP
-            if (!encode_webp_image_to_vector(image, width, height, channels, parameters, quality, buffer)) {
-                buffer.clear();
-            }
-            result = buffer.empty() ? 0 : 1;
-            break;
-#else
-            result = 0;
-            break;
-#endif
-        default:
-            result = 0;
-            break;
-    }
-
-    if (result && ((format == EncodedImageFormat::JPEG && !embed_jpeg_metadata(buffer, parameters)) ||
-                   (format == EncodedImageFormat::PNG && !embed_png_metadata(buffer, parameters)))) {
-        LOG_ERROR("generation metadata exceeds the container capacity or the encoded image is invalid");
-        result = 0;
+    } else {
+        std::memcpy(out.get(), pixels, size_t(width) * height * channels);
     }
-    if (!result)
-        buffer.clear();
-    return buffer;
+    width  = out_width;
+    height = out_height;
+    return out.release();
 }

-bool write_image_to_file(const std::string& path,
-                         const uint8_t* image,
-                         int width,
-                         int height,
-                         int channels,
-                         const std::string& parameters,
-                         int quality) {
-    const EncodedImageFormat format = encoded_image_format_from_path(path);
-
-    const auto encoded = encode_image_to_vector(format, image, width, height, channels, parameters, quality);
-    return !encoded.empty() && write_binary_file_bytes(path, encoded);
+uint8_t* load_image_from_file(const char* path, int& width, int& height, int& out_channel, int expected_width, int expected_height, int expected_channel) {
+    const auto input  = media_path_input(path);
+    const auto source = "fn main(path) { return { image=image::load(path, channels=" +
+                        std::to_string(expected_channel) + ", strict_channels=true) } }";
+    return image_pixels(run_media(source, &input, 1), width, height, out_channel, expected_width, expected_height, expected_channel == 0);
 }

-uint8_t* load_image_from_file(const char* image_path,
-                              int& width,
-                              int& height,
-                              int& out_channel,
-                              int expected_width,
-                              int expected_height,
-                              int expected_channel) {
-    return load_image_common(false, image_path, 0, width, height, expected_width, expected_height, expected_channel, out_channel);
-}
-
-bool load_sd_image_from_file(SDImage* image,
-                             const char* image_path,
-                             int expected_width,
-                             int expected_height,
-                             int expected_channel) {
-    int width;
-    int height;
-    int resolved_channel = expected_channel;
-    image->data          = load_image_common(false, image_path, 0, width, height, expected_width, expected_height, expected_channel, resolved_channel);
-    if (image->data == nullptr) {
+bool load_sd_image_from_file(SDImage* image, const char* path, int expected_width, int expected_height, int expected_channel) {
+    int width = 0, height = 0, channels = 0;
+    auto* pixels = load_image_from_file(path, width, height, channels, expected_width, expected_height, expected_channel);
+    if (!pixels)
         return false;
-    }
-    image->width   = width;
-    image->height  = height;
-    image->channel = resolved_channel;
+    *image = {uint32_t(width), uint32_t(height), uint32_t(channels), pixels};
     return true;
 }

-uint8_t* load_image_from_memory(const char* image_bytes,
-                                int len,
-                                int& width,
-                                int& height,
-                                int& out_channel,
-                                int expected_width,
-                                int expected_height,
-                                int expected_channel) {
-    return load_image_common(true, image_bytes, len, width, height, expected_width, expected_height, expected_channel, out_channel);
-}
-
-static void append_avi_metadata(std::vector<uint8_t>& data, const std::string& parameters) {
-    const void* info = nullptr;
-    size_t size      = 0;
-    if (sd_get_metadata_chunk(parameters.c_str(), SD_METADATA_AVI, &info, &size) != SD_STATUS_OK)
-        throw std::runtime_error(sd_get_last_error());
-    const auto* bytes = static_cast<const uint8_t*>(info);
-    if (size)
-        data.insert(data.end(), bytes, bytes + size);
-}
-
-std::vector<uint8_t> create_mjpg_avi_from_sd_images_to_vector(SDImage* images, int num_images, int fps, int quality, const SDAudio* audio, const std::string& parameters) {
-    if (num_images == 0) {
-        fprintf(stderr, "Error: Image array is empty.\n");
-        return {};
-    }
-
-    uint32_t width    = images[0].width;
-    uint32_t height   = images[0].height;
-    uint32_t channels = images[0].channel;
-    if (channels != 3 && channels != 4) {
-        fprintf(stderr, "Error: Unsupported channel count: %u\n", channels);
-        return {};
-    }
-
-    // stb_image_write changes JPEG sampling behavior above quality 90.
-    // MJPG AVI playback is more compatible when we keep the encoder on the
-    // <= 90 path.
-    const int mjpg_quality               = std::clamp(quality, 1, 90);
-    const bool has_audio                 = audio != nullptr && audio->data != nullptr && audio->sample_count > 0 && audio->channels > 0 && audio->sample_rate > 0;
-    const std::vector<uint8_t> audio_pcm = audio_to_pcm16_bytes(audio);
-    const uint16_t audio_bits_per_sample = 16;
-    const uint16_t audio_block_align     = has_audio ? static_cast<uint16_t>(audio->channels * (audio_bits_per_sample / 8)) : 0;
-    const uint32_t audio_byte_rate       = has_audio ? static_cast<uint32_t>(audio->sample_rate * audio_block_align) : 0;
-    const uint32_t audio_data_size       = has_audio ? static_cast<uint32_t>(audio_pcm.size()) : 0;
-
-    if (mjpg_quality != quality)
-        LOG_VERBOSE("create_mjpg_avi...(): compression quality was limited from %i to %i", quality, mjpg_quality);
-
-    std::vector<uint8_t> avi_data;
-    avi_data.reserve(static_cast<size_t>(num_images) * 1024);
-
-    write_fourcc(avi_data, "RIFF");
-    const size_t riff_size_pos = avi_data.size();
-    write_u32_le(avi_data, 0);
-    write_fourcc(avi_data, "AVI ");
-
-    write_fourcc(avi_data, "LIST");
-    uint32_t hdrl_size = 4 + 8 + 56 + 8 + 4 + 8 + 56 + 8 + 40;
-    if (has_audio) {
-        hdrl_size += 8 + (4 + 8 + 56 + 8 + 16);
-    }
-    write_u32_le(avi_data, hdrl_size);
-    write_fourcc(avi_data, "hdrl");
-
-    write_fourcc(avi_data, "avih");
-    write_u32_le(avi_data, 56);
-    write_u32_le(avi_data, 1000000 / fps);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0x110);
-    write_u32_le(avi_data, num_images);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, has_audio ? 2 : 1);
-    write_u32_le(avi_data, width * height * 3);
-    write_u32_le(avi_data, width);
-    write_u32_le(avi_data, height);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-
-    write_fourcc(avi_data, "LIST");
-    write_u32_le(avi_data, 4 + 8 + 56 + 8 + 40);
-    write_fourcc(avi_data, "strl");
-
-    write_fourcc(avi_data, "strh");
-    write_u32_le(avi_data, 56);
-    write_fourcc(avi_data, "vids");
-    write_fourcc(avi_data, "MJPG");
-    write_u32_le(avi_data, 0);
-    write_u16_le(avi_data, 0);
-    write_u16_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 1);
-    write_u32_le(avi_data, fps);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, num_images);
-    write_u32_le(avi_data, width * height * 3);
-    write_u32_le(avi_data, static_cast<uint32_t>(-1));
-    write_u32_le(avi_data, 0);
-    write_u16_le(avi_data, 0);
-    write_u16_le(avi_data, 0);
-    write_u16_le(avi_data, 0);
-    write_u16_le(avi_data, 0);
-
-    write_fourcc(avi_data, "strf");
-    write_u32_le(avi_data, 40);
-    write_u32_le(avi_data, 40);
-    write_u32_le(avi_data, width);
-    write_u32_le(avi_data, height);
-    write_u16_le(avi_data, 1);
-    write_u16_le(avi_data, 24);
-    write_fourcc(avi_data, "MJPG");
-    write_u32_le(avi_data, width * height * 3);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-    write_u32_le(avi_data, 0);
-
-    if (has_audio) {
-        write_fourcc(avi_data, "LIST");
-        write_u32_le(avi_data, 4 + 8 + 56 + 8 + 16);
-        write_fourcc(avi_data, "strl");
-
-        write_fourcc(avi_data, "strh");
-        write_u32_le(avi_data, 56);
-        write_fourcc(avi_data, "auds");
-        write_u32_le(avi_data, 0);
-        write_u32_le(avi_data, 0);
-        write_u16_le(avi_data, 0);
-        write_u16_le(avi_data, 0);
-        write_u32_le(avi_data, 0);
-        write_u32_le(avi_data, audio_block_align);
-        write_u32_le(avi_data, audio_byte_rate);
-        write_u32_le(avi_data, 0);
-        write_u32_le(avi_data, static_cast<uint32_t>(audio->sample_count));
-        write_u32_le(avi_data, audio_data_size);
-        write_u32_le(avi_data, static_cast<uint32_t>(-1));
-        write_u32_le(avi_data, audio_block_align);
-        write_u16_le(avi_data, 0);
-        write_u16_le(avi_data, 0);
-        write_u16_le(avi_data, 0);
-        write_u16_le(avi_data, 0);
-
-        write_fourcc(avi_data, "strf");
-        write_u32_le(avi_data, 16);
-        write_u16_le(avi_data, 1);
-        write_u16_le(avi_data, static_cast<uint16_t>(audio->channels));
-        write_u32_le(avi_data, audio->sample_rate);
-        write_u32_le(avi_data, audio_byte_rate);
-        write_u16_le(avi_data, audio_block_align);
-        write_u16_le(avi_data, audio_bits_per_sample);
-    }
-
-    write_fourcc(avi_data, "LIST");
-    const size_t movi_size_pos = avi_data.size();
-    write_u32_le(avi_data, 0);
-    write_fourcc(avi_data, "movi");
-
-    std::vector<avi_chunk_index_entry> index;
-    index.reserve(static_cast<size_t>(num_images) + (has_audio ? 1 : 0));
-    std::vector<uint8_t> jpeg_data;
-
-    for (int i = 0; i < num_images; i++) {
-        jpeg_data.clear();
-
-        auto write_to_buf = [](void* context, void* data, int size) {
-            auto* buffer       = reinterpret_cast<std::vector<uint8_t>*>(context);
-            const uint8_t* src = reinterpret_cast<const uint8_t*>(data);
-            buffer->insert(buffer->end(), src, src + size);
-        };
-
-        if (!stbi_write_jpg_to_func(write_to_buf, &jpeg_data, images[i].width, images[i].height, channels, images[i].data, mjpg_quality)) {
-            fprintf(stderr, "Error: Failed to encode JPEG frame.\n");
-            return {};
-        }
-
-        avi_chunk_index_entry video_entry = {};
-        memcpy(video_entry.fourcc, "00dc", 4);
-        video_entry.flags  = 0x10;
-        video_entry.offset = static_cast<uint32_t>(avi_data.size());
-        write_fourcc(avi_data, "00dc");
-        write_u32_le(avi_data, static_cast<uint32_t>(jpeg_data.size()));
-        video_entry.size = static_cast<uint32_t>(jpeg_data.size());
-        avi_data.insert(avi_data.end(), jpeg_data.begin(), jpeg_data.end());
-        index.push_back(video_entry);
-
-        if (jpeg_data.size() % 2) {
-            avi_data.push_back(0);
-        }
-    }
-
-    if (has_audio && !audio_pcm.empty()) {
-        avi_chunk_index_entry audio_entry = {};
-        memcpy(audio_entry.fourcc, "01wb", 4);
-        audio_entry.flags  = 0;
-        audio_entry.offset = static_cast<uint32_t>(avi_data.size());
-        audio_entry.size   = static_cast<uint32_t>(audio_pcm.size());
-        write_fourcc(avi_data, "01wb");
-        write_u32_le(avi_data, static_cast<uint32_t>(audio_pcm.size()));
-        avi_data.insert(avi_data.end(), audio_pcm.begin(), audio_pcm.end());
-        index.push_back(audio_entry);
-        if (audio_pcm.size() % 2 != 0) {
-            avi_data.push_back(0);
-        }
-    }
-
-    const size_t movi_size = avi_data.size() - movi_size_pos - 4;
-    patch_u32_le(avi_data, movi_size_pos, static_cast<uint32_t>(movi_size));
-
-    append_avi_metadata(avi_data, parameters);
-
-    write_fourcc(avi_data, "idx1");
-    write_u32_le(avi_data, static_cast<uint32_t>(index.size() * 16));
-    for (const auto& entry : index) {
-        write_fourcc(avi_data, entry.fourcc);
-        write_u32_le(avi_data, entry.flags);
-        write_u32_le(avi_data, entry.offset);
-        write_u32_le(avi_data, entry.size);
-    }
-
-    const size_t file_size = avi_data.size() - riff_size_pos - 4;
-    patch_u32_le(avi_data, riff_size_pos, static_cast<uint32_t>(file_size));
-
-    return avi_data;
-}
-
-int create_mjpg_avi_from_sd_images(const char* filename, SDImage* images, int num_images, int fps, int quality, const SDAudio* audio, const std::string& parameters) {
-    std::vector<uint8_t> avi_data = create_mjpg_avi_from_sd_images_to_vector(images, num_images, fps, quality, audio, parameters);
-    if (avi_data.empty()) {
-        return -1;
-    }
-    if (!write_binary_file_bytes(filename, avi_data)) {
-        perror("Error opening file for writing");
-        return -1;
-    }
-    return 0;
-}
-
-#ifdef SD_USE_WEBP
-std::vector<uint8_t> create_animated_webp_from_sd_images_to_vector(SDImage* images, int num_images, int fps, int quality) {
-    if (num_images == 0) {
-        fprintf(stderr, "Error: Image array is empty.\n");
-        return {};
-    }
-    if (fps <= 0) {
-        fprintf(stderr, "Error: FPS must be positive.\n");
-        return {};
-    }
-
-    const int width    = static_cast<int>(images[0].width);
-    const int height   = static_cast<int>(images[0].height);
-    const int channels = static_cast<int>(images[0].channel);
-    if (channels != 1 && channels != 3 && channels != 4) {
-        fprintf(stderr, "Error: Unsupported channel count: %d\n", channels);
-        return {};
-    }
-
-    WebPAnimEncoderOptions anim_options;
-    WebPConfig config;
-    if (!WebPAnimEncoderOptionsInit(&anim_options) || !WebPConfigInit(&config)) {
-        fprintf(stderr, "Error: Failed to initialize WebP animation encoder.\n");
-        return {};
-    }
-
-    config.quality      = static_cast<float>(quality);
-    config.method       = 4;
-    config.thread_level = 1;
-    if (channels == 4) {
-        config.exact = 1;
-    }
-    if (!WebPValidateConfig(&config)) {
-        fprintf(stderr, "Error: Invalid WebP encoder configuration.\n");
-        return {};
-    }
-
-    WebPAnimEncoderPtr enc(WebPAnimEncoderNew(width, height, &anim_options));
-    if (enc == nullptr) {
-        fprintf(stderr, "Error: Could not create WebPAnimEncoder object.\n");
-        return {};
-    }
-
-    const int frame_duration_ms = std::max(1, static_cast<int>(std::lround(1000.0 / static_cast<double>(fps))));
-    int timestamp_ms            = 0;
-
-    for (int i = 0; i < num_images; ++i) {
-        const SDImage& image = images[i];
-        if (static_cast<int>(image.width) != width || static_cast<int>(image.height) != height) {
-            fprintf(stderr, "Error: Frame dimensions do not match.\n");
-            return {};
-        }
-
-        WebPPictureGuard picture;
-        if (!picture.initialized) {
-            fprintf(stderr, "Error: Failed to initialize WebPPicture.\n");
-            return {};
-        }
-        picture.picture.use_argb = 1;
-        picture.picture.width    = width;
-        picture.picture.height   = height;
-
-        bool picture_ok = false;
-        std::vector<uint8_t> rgb_buffer;
-        if (image.channel == 1) {
-            rgb_buffer.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * 3);
-            for (int p = 0; p < width * height; ++p) {
-                rgb_buffer[p * 3 + 0] = image.data[p];
-                rgb_buffer[p * 3 + 1] = image.data[p];
-                rgb_buffer[p * 3 + 2] = image.data[p];
-            }
-            picture_ok = WebPPictureImportRGB(&picture.picture, rgb_buffer.data(), width * 3) != 0;
-        } else if (image.channel == 4) {
-            picture_ok = WebPPictureImportRGBA(&picture.picture, image.data, width * 4) != 0;
-        } else {
-            picture_ok = WebPPictureImportRGB(&picture.picture, image.data, width * 3) != 0;
-        }
-
-        if (!picture_ok) {
-            fprintf(stderr, "Error: Failed to import frame into WebPPicture.\n");
-            return {};
-        }
-
-        if (!WebPAnimEncoderAdd(enc.get(), &picture.picture, timestamp_ms, &config)) {
-            fprintf(stderr, "Error: Failed to add frame to animated WebP: %s\n", WebPAnimEncoderGetError(enc.get()));
-            return {};
-        }
-
-        timestamp_ms += frame_duration_ms;
-    }
-
-    if (!WebPAnimEncoderAdd(enc.get(), nullptr, timestamp_ms, nullptr)) {
-        fprintf(stderr, "Error: Failed to finalize animated WebP frames: %s\n", WebPAnimEncoderGetError(enc.get()));
-        return {};
-    }
-
-    WebPDataGuard webp_data;
-    if (!WebPAnimEncoderAssemble(enc.get(), &webp_data.data)) {
-        fprintf(stderr, "Error: Failed to assemble animated WebP: %s\n", WebPAnimEncoderGetError(enc.get()));
-        return {};
-    }
-
-    return std::vector<uint8_t>(webp_data.data.bytes, webp_data.data.bytes + webp_data.data.size);
-}
-
-int create_animated_webp_from_sd_images(const char* filename, SDImage* images, int num_images, int fps, int quality) {
-    std::vector<uint8_t> webp_data = create_animated_webp_from_sd_images_to_vector(images, num_images, fps, quality);
-    if (webp_data.empty()) {
-        return -1;
-    }
-    if (!write_binary_file_bytes(filename, webp_data)) {
-        perror("Error opening file for writing");
-        return -1;
-    }
-    return 0;
-}
-#endif
-
-#ifdef SD_USE_WEBM
-std::vector<uint8_t> create_webm_from_sd_images_to_vector(SDImage* images, int num_images, int fps, int quality, const SDAudio* audio, const std::string& parameters) {
-    if (num_images == 0) {
-        fprintf(stderr, "Error: Image array is empty.\n");
-        return {};
-    }
-    if (fps <= 0) {
-        fprintf(stderr, "Error: FPS must be positive.\n");
-        return {};
-    }
-
-    const int width  = static_cast<int>(images[0].width);
-    const int height = static_cast<int>(images[0].height);
-    if (width <= 0 || height <= 0) {
-        fprintf(stderr, "Error: Invalid frame dimensions.\n");
-        return {};
-    }
-
-    MemoryMkvWriter writer;
-
-    const int ret = [&]() -> int {
-        mkvmuxer::Segment segment;
-        if (!segment.Init(&writer)) {
-            fprintf(stderr, "Error: Failed to initialize WebM muxer.\n");
-            return -1;
-        }
-
-        segment.set_mode(mkvmuxer::Segment::kFile);
-        segment.OutputCues(true);
-
-        const uint64_t track_number = segment.AddVideoTrack(width, height, 0);
-        if (track_number == 0) {
-            fprintf(stderr, "Error: Failed to add VP8 video track.\n");
-            return -1;
-        }
-        if (!segment.CuesTrack(track_number)) {
-            fprintf(stderr, "Error: Failed to set WebM cues track.\n");
-            return -1;
-        }
-
-        mkvmuxer::VideoTrack* video_track = static_cast<mkvmuxer::VideoTrack*>(segment.GetTrackByNumber(track_number));
-        if (video_track != nullptr) {
-            video_track->set_display_width(static_cast<uint64_t>(width));
-            video_track->set_display_height(static_cast<uint64_t>(height));
-            video_track->set_frame_rate(static_cast<double>(fps));
-        }
-
-        uint64_t audio_track_number    = 0;
-        std::vector<uint8_t> audio_pcm = audio_to_pcm16_bytes(audio);
-        if (audio != nullptr && !audio_pcm.empty()) {
-            audio_track_number = segment.AddAudioTrack(static_cast<int32_t>(audio->sample_rate), static_cast<int32_t>(audio->channels), 0);
-            if (audio_track_number == 0) {
-                fprintf(stderr, "Error: Failed to add audio track.\n");
-                return -1;
-            }
-            auto* audio_track = static_cast<mkvmuxer::AudioTrack*>(segment.GetTrackByNumber(audio_track_number));
-            if (audio_track == nullptr) {
-                fprintf(stderr, "Error: Failed to get audio track.\n");
-                return -1;
-            }
-            audio_track->set_codec_id("A_PCM/INT/LIT");
-            audio_track->set_bit_depth(16);
-            audio_track->set_sample_rate(static_cast<double>(audio->sample_rate));
-            audio_track->set_channels(audio->channels);
-        }
-        segment.GetSegmentInfo()->set_writing_app("stable-diffusion.cpp");
-        segment.GetSegmentInfo()->set_muxing_app("stable-diffusion.cpp");
-
-        LOG_DEBUG("Embedding parameters to metadata: %s", parameters.c_str());
-        if (!parameters.empty()) {
-            mkvmuxer::Tag* tag = segment.AddTag();
-
-            if (tag) {
-                if (!tag->add_simple_tag("COMMENT", parameters.c_str())) {
-                    LOG_WARN("Failed to add COMMENT simple tag.");
-                }
-            } else {
-                LOG_WARN("Failed to add tag to segment.");
-            }
-        } else {
-            LOG_INFO("Paramaters is empty, COMMENT tag not embedded.\n");
-        }
-
-        const uint64_t frame_duration_ns = std::max<uint64_t>(
-            1, static_cast<uint64_t>(std::llround(1000000000.0 / static_cast<double>(fps))));
-        uint64_t timestamp_ns = 0;
-
-        for (int i = 0; i < num_images; ++i) {
-            const SDImage& image = images[i];
-            if (static_cast<int>(image.width) != width || static_cast<int>(image.height) != height) {
-                fprintf(stderr, "Error: Frame dimensions do not match.\n");
-                return -1;
-            }
-
-            std::vector<uint8_t> vp8_frame;
-            if (!encode_sd_image_to_vp8_frame(image, quality, vp8_frame)) {
-                fprintf(stderr, "Error: Failed to encode frame %d as VP8.\n", i);
-                return -1;
-            }
-
-            if (!segment.AddFrame(vp8_frame.data(),
-                                  static_cast<uint64_t>(vp8_frame.size()),
-                                  track_number,
-                                  timestamp_ns,
-                                  true)) {
-                fprintf(stderr, "Error: Failed to mux frame %d into WebM.\n", i);
-                return -1;
-            }
-
-            if (audio_track_number != 0) {
-                auto [audio_begin, audio_end] = audio_sample_range_for_video_frame(audio, i, num_images, fps);
-                const uint64_t frame_samples  = audio_end - audio_begin;
-                if (frame_samples > 0) {
-                    const uint64_t frame_bytes = frame_samples * audio->channels * sizeof(int16_t);
-                    const uint8_t* frame_ptr   = audio_pcm.data() + audio_begin * audio->channels * sizeof(int16_t);
-                    if (!segment.AddFrame(frame_ptr,
-                                          frame_bytes,
-                                          audio_track_number,
-                                          timestamp_ns,
-                                          true)) {
-                        fprintf(stderr, "Error: Failed to mux audio chunk %d into WebM.\n", i);
-                        return -1;
-                    }
-                }
-            }
-
-            timestamp_ns += frame_duration_ns;
-        }
-
-        if (!segment.Finalize()) {
-            fprintf(stderr, "Error: Failed to finalize WebM output.\n");
-            return -1;
-        }
-        return 0;
-    }();
-    if (ret != 0) {
-        return {};
-    }
-    return writer.data();
-}
-
-int create_webm_from_sd_images(const char* filename, SDImage* images, int num_images, int fps, int quality, const SDAudio* audio, const std::string& parameters) {
-    std::vector<uint8_t> webm_data = create_webm_from_sd_images_to_vector(images, num_images, fps, quality, audio, parameters);
-    if (webm_data.empty()) {
-        return -1;
-    }
-    if (!write_binary_file_bytes(filename, webm_data)) {
-        perror("Error opening file for writing");
-        return -1;
-    }
-    return 0;
-}
-#endif
-
-std::vector<uint8_t> create_video_from_sd_images_to_vector(const std::string& output_format,
-                                                           SDImage* images,
-                                                           int num_images,
-                                                           int fps,
-                                                           int quality,
-                                                           const SDAudio* audio,
-                                                           const std::string& parameters) {
-    std::string format = output_format;
-    std::transform(format.begin(), format.end(), format.begin(),
-                   [](unsigned char c) { return static_cast<char>(tolower(c)); });
-    if (!format.empty() && format[0] == '.') {
-        format.erase(format.begin());
-    }
-
-#ifdef SD_USE_WEBM
-    if (format == "webm") {
-        return create_webm_from_sd_images_to_vector(images, num_images, fps, quality, audio, parameters);
-    }
-#endif
-
-#ifdef SD_USE_WEBP
-    if (format == "webp") {
-        auto data = create_animated_webp_from_sd_images_to_vector(images, num_images, fps, quality);
-        if (!data.empty() && !embed_webp_metadata(data, parameters))
-            return {};
-        return data;
-    }
-#endif
-
-    return create_mjpg_avi_from_sd_images_to_vector(images, num_images, fps, quality, audio, parameters);
-}
-
-int create_video_from_sd_images(const char* filename, SDImage* images, int num_images, int fps, int quality, const SDAudio* audio, const std::string& parameters) {
-    std::string path                = filename ? filename : "";
-    auto pos                        = path.find_last_of('.');
-    std::string ext                 = pos == std::string::npos ? "" : path.substr(pos);
-    std::vector<uint8_t> video_data = create_video_from_sd_images_to_vector(ext, images, num_images, fps, quality, audio, parameters);
-    if (video_data.empty()) {
-        return -1;
-    }
-    if (!write_binary_file_bytes(filename, video_data)) {
-        perror("Error opening file for writing");
-        return -1;
-    }
-    return 0;
-}
-
-bool write_wav_to_file(const std::string& path,
-                       const float* interleaved_samples,
-                       uint64_t sample_count,
-                       uint32_t channels,
-                       uint32_t sample_rate) {
-    if (interleaved_samples == nullptr || sample_count == 0 || channels == 0 || sample_rate == 0) {
-        return false;
-    }
-
-    std::ofstream file(fs::u8path(path), std::ios::binary);
-    if (!file.is_open()) {
+uint8_t* load_image_from_memory(const char* bytes, size_t size, int& width, int& height, int& out_channel, int expected_width, int expected_height, int expected_channel) {
+    const auto input  = bytes_input("data", bytes, size);
+    const auto source = "fn main(data) { return { image=image::decode(data, channels=" +
+                        std::to_string(expected_channel) + ", strict_channels=true) } }";
+    return image_pixels(run_media(source, &input, 1), width, height, out_channel, expected_width, expected_height, expected_channel == 0);
+}
+
+static MediaResult write_video(const char* filename, const std::string& format, const SDImage* images, int count, int fps, int quality, const SDAudio* audio, const std::string& parameters, const sd_tensor_t* packed_frames) {
+    if (!images || count < 1 || (images[0].channel != 1 && images[0].channel != 3 && images[0].channel != 4))
+        return MediaResult(nullptr, sd_dgl_result_free);
+    auto frames = packed_frames ? SDTensorPtr(sd_tensor_retain(packed_frames)) : frames_tensor(images, size_t(count));
+    if (!frames)
+        return MediaResult(nullptr, sd_dgl_result_free);
+    const auto channels = sd_tensor_dim(frames.get(), 0);
+    if (format != "webp" && channels != 3) {
+        const auto* pixels = static_cast<const uint8_t*>(sd_tensor_data(frames.get()));
+        const size_t n     = sd_tensor_byte_size(frames.get()) / size_t(channels);
+        std::vector<uint8_t> rgb(n * 3);
+        for (size_t i = 0; i < n; ++i) {
+            for (size_t c = 0; c < 3; ++c)
+                rgb[3 * i + c] = pixels[size_t(channels) * i + (channels == 1 ? 0 : c)];
+        }
+        const int64_t shape[] = {3, sd_tensor_dim(frames.get(), 1), sd_tensor_dim(frames.get(), 2), count};
+        frames.reset(sd_tensor_create(SD_TENSOR_U8, 4, shape, rgb.data(), rgb.size()));
+        if (!frames)
+            return MediaResult(nullptr, sd_dgl_result_free);
+    }
+    SDTensorPtr samples;
+    if (audio && audio->sample_count && format != "webp") {
+        samples = audio_tensor(*audio);
+        if (!samples)
+            return MediaResult(nullptr, sd_dgl_result_free);
+    }
+    std::vector<sd_dgl_input_t> inputs{tensor_input("frames", frames.get())};
+    if (samples)
+        inputs.push_back(tensor_input("samples", samples.get()));
+    if (filename)
+        inputs.push_back(media_path_input(filename));
+    std::ostringstream source;
+    source << "fn main(frames" << (samples ? ",samples" : "") << (filename ? ",path" : "") << ") { ";
+    if (filename)
+        source << "video::save(path, ";
+    else
+        source << "return video::encode(";
+    source << "{ frames=frames, fps_num=" << fps << ", fps_den=1 }";
+    if (samples)
+        source << ", audio={ samples=samples, sample_rate=" << audio->sample_rate << " }";
+    if (!filename)
+        source << ", format=" << nlohmann::json(format).dump();
+    source << ", quality=" << std::clamp(quality, 1, 100) << ", audio_format=\"pcm16\", metadata="
+           << nlohmann::json(parameters).dump() << ") }";
+    return run_media(source.str(), inputs.data(), inputs.size());
+}
+
+std::vector<uint8_t> create_video_from_sd_images_to_vector(const std::string& format, SDImage* images, int count, int fps, int quality, const SDAudio* audio, const std::string& parameters, std::string* mime_type, const sd_tensor_t* packed_frames) {
+    return encoded_result(write_video(nullptr, format, images, count, fps, quality, audio, parameters, packed_frames), mime_type);
+}
+
+int create_video_from_sd_images(const char* filename, SDImage* images, int count, int fps, int quality, const SDAudio* audio, const std::string& parameters, const sd_tensor_t* packed_frames) {
+    auto format = std::filesystem::u8path(filename).extension().u8string();
+    std::transform(format.begin(), format.end(), format.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+    if (!format.empty())
+        format.erase(0, 1);
+    return write_video(filename, format, images, count, fps, quality, audio, parameters, packed_frames) ? 0 : -1;
+}
+
+bool write_wav_to_file(const std::string& path, const float* samples, uint64_t count, uint32_t channels, uint32_t rate) {
+    const auto tensor = audio_tensor({rate, channels, count, const_cast<float*>(samples)});
+    if (!tensor)
         return false;
-    }
-
-    uint32_t bits_per_sample  = 16;
-    uint32_t bytes_per_sample = bits_per_sample / 8;
-    uint32_t block_align      = channels * bytes_per_sample;
-    uint32_t byte_rate        = sample_rate * block_align;
-    uint32_t data_size        = static_cast<uint32_t>(sample_count * channels * bytes_per_sample);
-    uint32_t riff_size        = 36 + data_size;
-
-    file.write("RIFF", 4);
-    file.write(reinterpret_cast<const char*>(&riff_size), sizeof(riff_size));
-    file.write("WAVE", 4);
-    file.write("fmt ", 4);
-
-    uint32_t fmt_size            = 16;
-    uint16_t audio_format        = 1;
-    uint16_t wav_channels        = static_cast<uint16_t>(channels);
-    uint16_t wav_block_align     = static_cast<uint16_t>(block_align);
-    uint16_t wav_bits_per_sample = static_cast<uint16_t>(bits_per_sample);
-    file.write(reinterpret_cast<const char*>(&fmt_size), sizeof(fmt_size));
-    file.write(reinterpret_cast<const char*>(&audio_format), sizeof(audio_format));
-    file.write(reinterpret_cast<const char*>(&wav_channels), sizeof(wav_channels));
-    file.write(reinterpret_cast<const char*>(&sample_rate), sizeof(sample_rate));
-    file.write(reinterpret_cast<const char*>(&byte_rate), sizeof(byte_rate));
-    file.write(reinterpret_cast<const char*>(&wav_block_align), sizeof(wav_block_align));
-    file.write(reinterpret_cast<const char*>(&wav_bits_per_sample), sizeof(wav_bits_per_sample));
-
-    file.write("data", 4);
-    file.write(reinterpret_cast<const char*>(&data_size), sizeof(data_size));
-
-    std::vector<int16_t> pcm(sample_count * channels);
-    for (size_t i = 0; i < pcm.size(); ++i) {
-        float sample = std::max(-1.0f, std::min(1.0f, interleaved_samples[i]));
-        pcm[i]       = static_cast<int16_t>(std::lrint(sample * 32767.0f));
-    }
-    file.write(reinterpret_cast<const char*>(pcm.data()), static_cast<std::streamsize>(pcm.size() * sizeof(int16_t)));
-    return file.good();
-}
-
-static uint16_t read_le16(const uint8_t* data) {
-    return static_cast<uint16_t>(data[0]) |
-           (static_cast<uint16_t>(data[1]) << 8);
-}
-
-static uint32_t read_le32(const uint8_t* data) {
-    return static_cast<uint32_t>(data[0]) |
-           (static_cast<uint32_t>(data[1]) << 8) |
-           (static_cast<uint32_t>(data[2]) << 16) |
-           (static_cast<uint32_t>(data[3]) << 24);
+    const sd_dgl_input_t inputs[] = {tensor_input("samples", tensor.get()), media_path_input(path.c_str())};
+    const auto source             = "fn main(samples,path) { audio::save(path, { samples=samples, sample_rate=" +
+                        std::to_string(rate) + " }, format=\"pcm16\") }";
+    return bool(run_media(source, inputs, 2));
 }

-/** Loads a WAV file from disk and delegates decoding to load_wav_from_memory(). */
-bool load_wav_from_file(const std::string& path,
-                        std::vector<float>& interleaved_samples,
-                        uint32_t& sample_rate,
-                        uint32_t& channels) {
-    std::ifstream file(fs::u8path(path), std::ios::binary);
-    if (!file) {
-        interleaved_samples.clear();
-        sample_rate = 0;
-        channels    = 0;
+static bool read_audio_result(const MediaResult& result, std::vector<float>& samples, uint32_t& rate, uint32_t& channels) {
+    if (!result)
         return false;
-    }
-    file.seekg(0, std::ios::end);
-    const std::streamoff file_size = file.tellg();
-    file.seekg(0, std::ios::beg);
-    if (file_size < 0) {
-        interleaved_samples.clear();
-        sample_rate = 0;
-        channels    = 0;
+    const auto* tensor  = sd_dgl_result_tensor(result.get(), "samples");
+    int64_t sample_rate = 0;
+    if (!tensor || sd_dgl_value_get_int(sd_dgl_value_field(sd_dgl_result_root(result.get()), "sample_rate"), &sample_rate) != SD_STATUS_OK)
         return false;
-    }
-    std::vector<uint8_t> buffer(static_cast<size_t>(file_size));
-    if (file_size > 0 && !file.read(reinterpret_cast<char*>(buffer.data()), file_size)) {
-        interleaved_samples.clear();
-        sample_rate = 0;
-        channels    = 0;
+    const auto* first = static_cast<const float*>(sd_tensor_data(tensor));
+    const auto count  = sd_tensor_byte_size(tensor) / sizeof(*first);
+    if (!count)
         return false;
-    }
-    return load_wav_from_memory(buffer.data(), buffer.size(), interleaved_samples, sample_rate, channels);
+    samples.assign(first, first + count);
+    rate     = uint32_t(sample_rate);
+    channels = uint32_t(sd_tensor_dim(tensor, 0));
+    return true;
 }

-/** Parses a RIFF/WAVE buffer in place; compares chunk sizes against the remaining
- * bytes so payload-controlled sizes cannot wrap size_t on 32-bit builds. */
-bool load_wav_from_memory(const uint8_t* data,
-                          size_t size,
-                          std::vector<float>& interleaved_samples,
-                          uint32_t& sample_rate,
-                          uint32_t& channels) {
-    interleaved_samples.clear();
-    sample_rate = 0;
-    channels    = 0;
-
-    if (data == nullptr ||
-        size < 12 ||
-        std::memcmp(data, "RIFF", 4) != 0 ||
-        std::memcmp(data + 8, "WAVE", 4) != 0) {
-        return false;
-    }
-
-    uint16_t audio_format    = 0;
-    uint16_t bits_per_sample = 0;
-    uint16_t block_align     = 0;
-    size_t data_pos          = SIZE_MAX;
-    uint32_t data_size       = 0;
-
-    size_t pos = 12;
-    while (pos + 8 <= size) {
-        uint32_t chunk_size    = read_le32(data + pos + 4);
-        size_t chunk_data_pos  = pos + 8;
-        const size_t remaining = size - chunk_data_pos;  // safe: chunk_data_pos <= size
-        // Chunk sizes come from the payload, so compare against the remaining bytes
-        // instead of adding them to offsets (avoids size_t wrap on 32-bit builds).
-        const bool data_fits = static_cast<size_t>(chunk_size) <= remaining;
-
-        if (std::memcmp(data + pos, "fmt ", 4) == 0) {
-            if (chunk_size < 16 || !data_fits) {
-                return false;
-            }
-            audio_format    = read_le16(data + chunk_data_pos);
-            channels        = read_le16(data + chunk_data_pos + 2);
-            sample_rate     = read_le32(data + chunk_data_pos + 4);
-            block_align     = read_le16(data + chunk_data_pos + 12);
-            bits_per_sample = read_le16(data + chunk_data_pos + 14);
-            if (audio_format == 0xfffe && chunk_size >= 40) {
-                audio_format = read_le16(data + chunk_data_pos + 24);
-            }
-        } else if (std::memcmp(data + pos, "data", 4) == 0) {
-            data_pos  = chunk_data_pos;
-            data_size = chunk_size;
-        }
-        // Only advance past a chunk whose size and pad byte fully fit (keeps the sum
-        // overflow-free); a chunk truncated at the buffer end terminates the walk.
-        const bool chunk_fits = data_fits && ((chunk_size & 1) == 0 || static_cast<size_t>(chunk_size) < remaining);
-        pos                   = chunk_fits ? chunk_data_pos + static_cast<size_t>(chunk_size) + (chunk_size & 1) : size;
-    }
-
-    const uint32_t bytes_per_sample = (bits_per_sample + 7) / 8;
-    if (data_pos == SIZE_MAX || data_size == 0 || channels == 0 || sample_rate == 0 ||
-        block_align == 0 || bytes_per_sample == 0 || block_align < channels * bytes_per_sample ||
-        (audio_format != 1 && audio_format != 3)) {
-        return false;
-    }
-
-    const uint64_t frame_count = data_size / block_align;
-    if (frame_count == 0 || frame_count > SIZE_MAX / channels) {
-        return false;
-    }
-    if (static_cast<size_t>(data_size) > size - data_pos) {
-        return false;
-    }
-    const uint8_t* pcm = data + data_pos;
+bool load_audio_from_file(const std::string& path, std::vector<float>& samples, uint32_t& rate, uint32_t& channels) {
+    const auto input = media_path_input(path.c_str());
+    return read_audio_result(run_media("fn main(path) { return audio::load(path) }", &input, 1), samples, rate, channels);
+}

-    interleaved_samples.resize(static_cast<size_t>(frame_count * channels));
-    for (uint64_t frame = 0; frame < frame_count; ++frame) {
-        const uint8_t* frame_data = pcm + frame * block_align;
-        for (uint32_t channel = 0; channel < channels; ++channel) {
-            const uint8_t* sample_data = frame_data + channel * bytes_per_sample;
-            float sample               = 0.0f;
-            if (audio_format == 3 && bits_per_sample == 32) {
-                std::memcpy(&sample, sample_data, sizeof(sample));
-            } else if (audio_format == 3 && bits_per_sample == 64) {
-                double value;
-                std::memcpy(&value, sample_data, sizeof(value));
-                sample = static_cast<float>(value);
-            } else if (audio_format == 1 && bits_per_sample == 8) {
-                sample = (static_cast<int>(sample_data[0]) - 128) / 128.0f;
-            } else if (audio_format == 1 && bits_per_sample == 16) {
-                sample = static_cast<int16_t>(read_le16(sample_data)) / 32768.0f;
-            } else if (audio_format == 1 && bits_per_sample == 24) {
-                int32_t value = static_cast<int32_t>(sample_data[0]) |
-                                (static_cast<int32_t>(sample_data[1]) << 8) |
-                                (static_cast<int32_t>(sample_data[2]) << 16);
-                if ((value & 0x800000) != 0) {
-                    value |= ~0xffffff;
-                }
-                sample = value / 8388608.0f;
-            } else if (audio_format == 1 && bits_per_sample == 32) {
-                int32_t value = static_cast<int32_t>(read_le32(sample_data));
-                sample        = value / 2147483648.0f;
-            } else {
-                interleaved_samples.clear();
-                return false;
-            }
-            interleaved_samples[static_cast<size_t>(frame * channels + channel)] = sample;
-        }
-    }
-    return true;
+bool load_audio_from_memory(const uint8_t* data, size_t size, std::vector<float>& samples, uint32_t& rate, uint32_t& channels) {
+    const auto input = bytes_input("data", data, size);
+    return read_audio_result(run_media("fn main(data) { return audio::decode(data) }", &input, 1), samples, rate, channels);
 }
diff --git a/examples/common/media_io.h b/examples/common/media_io.h
index 5951f39..d3f210c 100644
--- a/examples/common/media_io.h
+++ b/examples/common/media_io.h
@@ -2,6 +2,7 @@
 #define __MEDIA_IO_H__

 #include <cstdint>
+#include <optional>
 #include <string>
 #include <vector>

@@ -15,6 +16,15 @@ enum class EncodedImageFormat {
 };

 EncodedImageFormat encoded_image_format_from_path(const std::string& path);
+inline sd_dgl_input_t media_path_input(const char* path) {
+    sd_dgl_input_t input{};
+    input.name         = "path";
+    input.kind         = SD_DGL_INPUT_STRING;
+    input.value.string = path;
+    return input;
+}
+std::vector<std::string> media_output_formats(const char* kind);
+std::optional<std::string> read_media_metadata(const std::string& path, const std::string& format, bool raw, bool brief, bool structural);

 // parameters is the executed DGL source; empty disables generation metadata.
 std::vector<uint8_t> encode_image_to_vector(EncodedImageFormat format,
@@ -50,7 +60,7 @@ bool load_sd_image_from_file(SDImage* image,
                              int expected_channel = 3);

 uint8_t* load_image_from_memory(const char* image_bytes,
-                                int len,
+                                size_t size,
                                 int& width,
                                 int& height,
                                 int& out_channel,
@@ -58,62 +68,23 @@ uint8_t* load_image_from_memory(const char* image_bytes,
                                 int expected_height  = 0,
                                 int expected_channel = 3);

-int create_mjpg_avi_from_sd_images(const char* filename,
-                                   SDImage* images,
-                                   int num_images,
-                                   int fps,
-                                   int quality                   = 90,
-                                   const SDAudio* audio          = nullptr,
-                                   const std::string& parameters = "");
-std::vector<uint8_t> create_mjpg_avi_from_sd_images_to_vector(SDImage* images,
-                                                              int num_images,
-                                                              int fps,
-                                                              int quality                   = 90,
-                                                              const SDAudio* audio          = nullptr,
-                                                              const std::string& parameters = "");
-
-#ifdef SD_USE_WEBP
-int create_animated_webp_from_sd_images(const char* filename,
-                                        SDImage* images,
-                                        int num_images,
-                                        int fps,
-                                        int quality = 90);
-std::vector<uint8_t> create_animated_webp_from_sd_images_to_vector(SDImage* images,
-                                                                   int num_images,
-                                                                   int fps,
-                                                                   int quality = 90);
-#endif
-
-#ifdef SD_USE_WEBM
-int create_webm_from_sd_images(const char* filename,
-                               SDImage* images,
-                               int num_images,
-                               int fps,
-                               int quality                   = 90,
-                               const SDAudio* audio          = nullptr,
-                               const std::string& parameters = "");
-std::vector<uint8_t> create_webm_from_sd_images_to_vector(SDImage* images,
-                                                          int num_images,
-                                                          int fps,
-                                                          int quality                   = 90,
-                                                          const SDAudio* audio          = nullptr,
-                                                          const std::string& parameters = "");
-#endif
-
 int create_video_from_sd_images(const char* filename,
                                 SDImage* images,
                                 int num_images,
                                 int fps,
-                                int quality                   = 90,
-                                const SDAudio* audio          = nullptr,
-                                const std::string& parameters = "");
+                                int quality                      = 90,
+                                const SDAudio* audio             = nullptr,
+                                const std::string& parameters    = "",
+                                const sd_tensor_t* packed_frames = nullptr);
 std::vector<uint8_t> create_video_from_sd_images_to_vector(const std::string& output_format,
                                                            SDImage* images,
                                                            int num_images,
                                                            int fps,
-                                                           int quality                   = 90,
-                                                           const SDAudio* audio          = nullptr,
-                                                           const std::string& parameters = "");
+                                                           int quality                      = 90,
+                                                           const SDAudio* audio             = nullptr,
+                                                           const std::string& parameters    = "",
+                                                           std::string* mime_type           = nullptr,
+                                                           const sd_tensor_t* packed_frames = nullptr);

 bool write_wav_to_file(const std::string& path,
                        const float* interleaved_samples,
@@ -121,16 +92,16 @@ bool write_wav_to_file(const std::string& path,
                        uint32_t channels,
                        uint32_t sample_rate);

-bool load_wav_from_file(const std::string& path,
-                        std::vector<float>& interleaved_samples,
-                        uint32_t& sample_rate,
-                        uint32_t& channels);
-
-/** Decodes a WAV buffer (PCM 8/16/24/32 or IEEE float 32/64) into interleaved samples. */
-bool load_wav_from_memory(const uint8_t* data,
-                          size_t size,
+bool load_audio_from_file(const std::string& path,
                           std::vector<float>& interleaved_samples,
                           uint32_t& sample_rate,
                           uint32_t& channels);

+/** Decodes audio into interleaved samples. */
+bool load_audio_from_memory(const uint8_t* data,
+                            size_t size,
+                            std::vector<float>& interleaved_samples,
+                            uint32_t& sample_rate,
+                            uint32_t& channels);
+
 #endif  // __MEDIA_IO_H__
diff --git a/examples/common/media_metadata.cpp b/examples/common/media_metadata.cpp
deleted file mode 100644
index d665c28..0000000
--- a/examples/common/media_metadata.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "media_metadata.h"
-
-#include <cstring>
-
-#include "stable-diffusion.h"
-
-std::string generation_xmp(const std::string& source) {
-    const void* data = nullptr;
-    size_t size      = 0;
-    if (sd_get_metadata_chunk(source.c_str(), SD_METADATA_XMP, &data, &size) != SD_STATUS_OK || !size)
-        return "";
-    return std::string(static_cast<const char*>(data), size);
-}
-
-bool embed_jpeg_metadata(std::vector<uint8_t>& image, const std::string& source) {
-    if (source.empty())
-        return true;
-    if (image.size() < 2)
-        return false;
-    const void* data = nullptr;
-    size_t size      = 0;
-    if (sd_get_metadata_chunk(source.c_str(), SD_METADATA_JPEG, &data, &size) != SD_STATUS_OK)
-        return false;
-    const auto* bytes = static_cast<const uint8_t*>(data);
-    if (size)
-        image.insert(image.begin() + 2, bytes, bytes + size);
-    return true;
-}
-
-bool embed_png_metadata(std::vector<uint8_t>& image, const std::string& source) {
-    if (source.empty())
-        return true;
-    if (image.size() < 33 || std::memcmp(image.data() + 12, "IHDR", 4))
-        return false;
-    const void* data = nullptr;
-    size_t size      = 0;
-    if (sd_get_metadata_chunk(source.c_str(), SD_METADATA_PNG, &data, &size) != SD_STATUS_OK)
-        return false;
-    const auto* bytes = static_cast<const uint8_t*>(data);
-    if (size)
-        image.insert(image.begin() + 33, bytes, bytes + size);
-    return true;
-}
diff --git a/examples/common/media_metadata.h b/examples/common/media_metadata.h
deleted file mode 100644
index 1ca49dc..0000000
--- a/examples/common/media_metadata.h
+++ /dev/null
@@ -1,12 +0,0 @@
-#ifndef __EXAMPLES_COMMON_MEDIA_METADATA_H__
-#define __EXAMPLES_COMMON_MEDIA_METADATA_H__
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-std::string generation_xmp(const std::string& parameters);
-bool embed_png_metadata(std::vector<uint8_t>& image, const std::string& source);
-bool embed_jpeg_metadata(std::vector<uint8_t>& image, const std::string& parameters);
-
-#endif  // __EXAMPLES_COMMON_MEDIA_METADATA_H__
diff --git a/examples/common/resource_owners.hpp b/examples/common/resource_owners.hpp
index 83f2dca..93eba97 100644
--- a/examples/common/resource_owners.hpp
+++ b/examples/common/resource_owners.hpp
@@ -98,16 +98,17 @@ static inline SDTensorPtr frames_tensor(const SDImage* frames, size_t count) {
         LOG_ERROR("invalid video frame storage size");
         return {};
     }
-    std::vector<uint8_t> pixels(frame_bytes * count);
+    std::vector<const void*> pixels;
+    pixels.reserve(count);
     for (size_t i = 0; i < count; ++i) {
         if (!frames[i].data || frames[i].width != first.width || frames[i].height != first.height || frames[i].channel != first.channel) {
             LOG_ERROR("video frames must have matching dimensions and channels");
             return {};
         }
-        memcpy(pixels.data() + i * frame_bytes, frames[i].data, frame_bytes);
+        pixels.push_back(frames[i].data);
     }
     const int64_t shape[] = {first.channel, first.width, first.height, static_cast<int64_t>(count)};
-    return SDTensorPtr(sd_tensor_create(SD_TENSOR_U8, 4, shape, pixels.data(), pixels.size()));
+    return SDTensorPtr(sd_tensor_create_from_chunks(SD_TENSOR_U8, 4, shape, pixels.data(), pixels.size(), frame_bytes));
 }

 static inline SDAudio* retain_result_audio(const sd_result_t* result) {
@@ -481,6 +482,7 @@ class SDImageVec {
 private:
     std::vector<SDImage> images_;
     std::vector<std::string> generation_infos_;
+    SDResultPtr video_result_;

 public:
     SDImageVec() = default;
@@ -489,7 +491,7 @@ public:
     SDImageVec& operator=(const SDImageVec&) = delete;

     SDImageVec(SDImageVec&& other) noexcept
-        : images_(std::move(other.images_)), generation_infos_(std::move(other.generation_infos_)) {
+        : images_(std::move(other.images_)), generation_infos_(std::move(other.generation_infos_)), video_result_(std::move(other.video_result_)) {
     }

     SDImageVec& operator=(SDImageVec&& other) noexcept {
@@ -497,6 +499,7 @@ public:
             clear();
             images_           = std::move(other.images_);
             generation_infos_ = std::move(other.generation_infos_);
+            video_result_     = std::move(other.video_result_);
         }
         return *this;
     }
@@ -543,7 +546,29 @@ public:
     }

     void adopt_video(sd_result_t* result) {
-        adopt(result);
+        if (!result) {
+            clear();
+            return;
+        }
+        clear();
+        video_result_.reset(result);
+        const size_t count = sd_result_get_image_count(result);
+        images_.reserve(count);
+        for (size_t i = 0; i < count; ++i)
+            images_.push_back(take_result_image(result, i));
+        const auto* source = count ? sd_result_get_generation_info(result, 0) : nullptr;
+        generation_infos_.resize(count, source ? source : "");
+    }
+
+    const sd_tensor_t* video_frames() const {
+        if (!video_result_)
+            return nullptr;
+        const auto* video = sd_result_get_video(video_result_.get());
+        return video ? video->data : nullptr;
+    }
+
+    void release_video_result() {
+        video_result_.reset();
     }

     void adopt(SDImage* images, int count) {
@@ -607,6 +632,7 @@ public:
         }
         images_.clear();
         generation_infos_.clear();
+        video_result_.reset();
     }
 };

diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt
index ccf290a..9345ac2 100644
--- a/examples/server/CMakeLists.txt
+++ b/examples/server/CMakeLists.txt
@@ -66,7 +66,6 @@ add_executable(${TARGET}
     ../common/common.cpp
     ../common/log.cpp
     ../common/media_io.cpp
-    ../common/media_metadata.cpp
     main.cpp
     server_access.cpp
     runtime.cpp
@@ -107,14 +106,6 @@ target_include_directories(${TARGET} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")

 install(TARGETS ${TARGET} RUNTIME)
 target_link_libraries(${TARGET} PRIVATE stable-diffusion ${CMAKE_THREAD_LIBS_INIT})
-if(SD_WEBP)
-    target_compile_definitions(${TARGET} PRIVATE SD_USE_WEBP)
-    target_link_libraries(${TARGET} PRIVATE webp libwebpmux)
-endif()
-if(SD_WEBM)
-    target_compile_definitions(${TARGET} PRIVATE SD_USE_WEBM)
-    target_link_libraries(${TARGET} PRIVATE webm)
-endif()

 # due to httplib; it contains a pragma for MSVC, but other things need explicit flags
 if(WIN32 AND NOT MSVC)
diff --git a/examples/server/api.md b/examples/server/api.md
index 77cb807..5a08131 100644
--- a/examples/server/api.md
+++ b/examples/server/api.md
@@ -1642,13 +1642,15 @@ Allowed `output_format` values:
 - `webm`
 - `webp`
 - `avi`
+- `mp4` with FFmpeg

 Output format behavior:

-- `output_format` defaults to `webm`
+- `output_format` defaults to the first available video format
 - `webp` means animated WebP
 - `avi` means MJPG AVI
-- `webm` requires the server to be built with WebM support; otherwise the request returns `400`
+- `webm` uses built-in WebM support when available and otherwise requires FFmpeg
+- `mp4` uses FFmpeg and returns fragmented H.264/AAC MP4

 ### Result Payload

@@ -1669,6 +1671,7 @@ Expected MIME types:
 | `webm` | `video/webm` |
 | `webp` | `image/webp` |
 | `avi` | `video/x-msvideo` |
+| `mp4` | `video/mp4` |

 ### Optional Field Handling

@@ -1837,7 +1840,9 @@ finish first. A terminal job returns its current status.
 The existing job result has `type`, `outputs` and `media`. `outputs` retains
 the flat tensor descriptions. `media` recognizes a root `{data, mime_type}`
 dict or such dicts in the root's named fields. `data` must be DGL `bytes`, and
-the supported MIME types are `image/png`, `video/webm` and `video/x-msvideo`.
+the supported MIME types are `image/png`, `image/jpeg`, `image/webp`,
+`video/webm`, `video/x-msvideo`, `video/mp4`, `audio/wav`, `audio/flac`,
+`audio/mpeg` and `audio/mp4`.
 Bare bytes, U8 tensors and more deeply nested dicts are not inferred as media.
 The name of a root media dict is `result`.

@@ -1861,8 +1866,8 @@ remaining budget has no `b64_json`; it instead contains
 `error: {code: "inline_too_large", message: "..."}`. Other media and tensor
 outputs remain available, and any file already written by `media::save`
 remains intact. Encoder failures fail the script through the ordinary DGL
-execution error path. WebM encoding rejects nonempty audio instead of silently
-removing it. Use AVI encoding for a PCM16 soundtrack.
+execution error path. AVI supports PCM16 audio. FFmpeg supports H.264/AAC
+MP4 and VP9/Opus WebM. See [DGL media input and output](../../docs/dgl.md#media-input-and-output).

 ## Actual generation parameters

diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp
index 329cf29..6e7275b 100644
--- a/examples/server/async_jobs.cpp
+++ b/examples/server/async_jobs.cpp
@@ -511,15 +511,17 @@ bool execute_vid_gen_job(ServerRuntime& runtime,
                                                                              output_fps,
                                                                              job.vid_gen.output_compression,
                                                                              generated_audio,
-                                                                             str_params);
+                                                                             str_params,
+                                                                             &output_media_mime_type,
+                                                                             results.video_frames());
     free_sd_audio(generated_audio);
     if (video_bytes.empty()) {
-        error_message = "failed to encode generated video container";
+        const auto* detail = sd_dgl_error();
+        error_message      = detail && *detail ? detail : "failed to encode generated video container";
         return false;
     }

     output_media_b64       = base64_encode(video_bytes);
-    output_media_mime_type = video_mime_type(job.vid_gen.output_format);
     output_frame_count     = num_results;
     return true;
 }
@@ -557,7 +559,9 @@ static json describe_dgl_media(const sd_dgl_result_t* result) {
             sd_dgl_value_get_bytes(data, &bytes, &size) != SD_STATUS_OK)
             throw std::runtime_error(sd_get_last_error());
         const std::string mime_type(mime_text, mime_size);
-        if (mime_type != "image/png" && mime_type != "video/webm" && mime_type != "video/x-msvideo")
+        if (mime_type != "image/png" && mime_type != "image/jpeg" && mime_type != "image/webp" &&
+            mime_type != "video/webm" && mime_type != "video/x-msvideo" && mime_type != "video/mp4" &&
+            mime_type != "audio/wav" && mime_type != "audio/flac" && mime_type != "audio/mpeg" && mime_type != "audio/mp4")
             return;
         json item = {{"name", name}, {"mime_type", mime_type}};
         if (size > remaining) {
diff --git a/examples/server/routes_openai.cpp b/examples/server/routes_openai.cpp
index 0fe6537..b5307d1 100644
--- a/examples/server/routes_openai.cpp
+++ b/examples/server/routes_openai.cpp
@@ -160,7 +160,7 @@ static bool build_openai_edit_request(const httplib::Request& req,
         int resolved_channel = 0;
         uint8_t* raw_pixels  = load_image_from_memory(
             reinterpret_cast<const char*>(bytes.data()),
-            static_cast<int>(bytes.size()),
+            bytes.size(),
             img_w, img_h, resolved_channel,
             0, 0,
             0);
@@ -181,7 +181,7 @@ static bool build_openai_edit_request(const httplib::Request& req,

         uint8_t* mask_raw = load_image_from_memory(
             reinterpret_cast<const char*>(mask_bytes.data()),
-            static_cast<int>(mask_bytes.size()),
+            mask_bytes.size(),
             mask_w, mask_h, mask_channel,
             0, 0, 1);
         request.gen_params.mask_image.reset({(uint32_t)mask_w, (uint32_t)mask_h, 1, mask_raw});
diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp
index c513ab9..b34f48a 100644
--- a/examples/server/runtime.cpp
+++ b/examples/server/runtime.cpp
@@ -1,5 +1,7 @@
 #include "runtime.h"

+#include "common/media_io.h"
+
 #include <algorithm>
 #include <cctype>
 #include <charconv>
@@ -127,26 +129,18 @@ std::string normalize_output_format(std::string output_format) {
 }

 std::vector<std::string> supported_img_output_formats(bool allow_webp) {
-    std::vector<std::string> formats = {"png", "jpeg"};
-#ifdef SD_USE_WEBP
-    if (allow_webp) {
-        formats.push_back("webp");
-    }
-#else
-    (void)allow_webp;
-#endif
+    auto formats = media_output_formats("image");
+    if (!allow_webp)
+        formats.erase(std::remove(formats.begin(), formats.end(), "webp"), formats.end());
+    if (formats.empty())
+        return {"png", "jpeg"};
     return formats;
 }

 std::vector<std::string> supported_vid_output_formats() {
-    std::vector<std::string> formats;
-#ifdef SD_USE_WEBM
-    formats.push_back("webm");
-#endif
-#ifdef SD_USE_WEBP
-    formats.push_back("webp");
-#endif
-    formats.push_back("avi");
+    auto formats = media_output_formats("video");
+    if (formats.empty())
+        return {"avi"};
     return formats;
 }

@@ -198,42 +192,13 @@ bool assign_output_options(VidGenJobRequest& request,
     request.output_format      = normalize_output_format(std::move(output_format));
     request.output_compression = std::clamp(output_compression, 0, 100);

-    if (request.output_format == "avi") {
-        return true;
-    }
-
-    if (request.output_format == "webm") {
-#ifdef SD_USE_WEBM
-        return true;
-#else
-        error_message = valid_vid_output_formats_message();
-        return false;
-#endif
-    }
-
-    if (request.output_format == "webp") {
-#ifdef SD_USE_WEBP
+    const auto formats = supported_vid_output_formats();
+    if (std::find(formats.begin(), formats.end(), request.output_format) != formats.end())
         return true;
-#else
-        error_message = valid_vid_output_formats_message();
-        return false;
-#endif
-    }
-
     error_message = valid_vid_output_formats_message();
     return false;
 }

-std::string video_mime_type(const std::string& output_format) {
-    if (output_format == "webm") {
-        return "video/webm";
-    }
-    if (output_format == "webp") {
-        return "image/webp";
-    }
-    return "video/x-msvideo";
-}
-
 bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) {
     if (!has_current_model(runtime)) {
         return false;
diff --git a/examples/server/runtime.h b/examples/server/runtime.h
index 7c20ec2..2b133ab 100644
--- a/examples/server/runtime.h
+++ b/examples/server/runtime.h
@@ -147,7 +147,6 @@ bool assign_output_options(VidGenJobRequest& request,
                            std::string output_format,
                            int output_compression,
                            std::string& error_message);
-std::string video_mime_type(const std::string& output_format);
 bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode);
 bool has_current_model(const ServerRuntime& runtime);
 void configure_server_file_access(ServerModels& models, const SDSvrParams& params, const SDContextParams& config);
diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index 9829afe..50c3267 100644
--- a/include/stable-diffusion.h
+++ b/include/stable-diffusion.h
@@ -67,32 +67,6 @@ SD_API const char* sd_get_last_error(void);
 // Returns NULL on failure; see sd_get_last_error().
 SD_API const char* sd_get_generation_metadata(const char* source);

-typedef enum {
-    SD_METADATA_READ_JSON       = 1u << 0,
-    SD_METADATA_READ_RAW        = 1u << 1,
-    SD_METADATA_READ_BRIEF      = 1u << 2,
-    SD_METADATA_READ_STRUCTURAL = 1u << 3,
-} sd_metadata_read_flags_t;
-
-// Reads container metadata without loading a model. Flags may be ORed together;
-// zero selects the default text report. Returns NULL on failure.
-// Borrowed until the next call to this function on the same thread.
-SD_API const char* sd_read_metadata(const char* path, uint32_t flags);
-
-typedef enum {
-    SD_METADATA_PNG,
-    SD_METADATA_JPEG,
-    SD_METADATA_XMP,
-    SD_METADATA_AVI,
-} sd_metadata_format_t;
-
-// Builds PNG iTXt chunks, JPEG COM segments, UTF-8 XMP or an AVI INFO chunk.
-// PNG/JPEG/XMP contain the DGL source and inferred infotext; AVI stores source.
-// Does not write files. Borrowed bytes remain valid until the next call to this
-// function on the same thread. Empty source succeeds with NULL, 0.
-// Output pointers are required and cleared on failure.
-SD_API sd_status_t sd_get_metadata_chunk(const char* source, sd_metadata_format_t format, const void** data_out, size_t* size_out);
-
 // File access for generation and DGL contexts

 typedef enum {
@@ -134,6 +108,9 @@ SD_API sd_tensor_t* sd_tensor_create(
     const void* data,
     size_t data_size);

+// Creates an immutable tensor by copying consecutive equal-sized chunks.
+SD_API sd_tensor_t* sd_tensor_create_from_chunks(sd_tensor_type_t type, size_t rank, const int64_t* shape, const void* const* chunks, size_t chunk_count, size_t chunk_bytes);
+
 // retain returns the same immutable handle with one additional ownership reference.
 SD_API sd_tensor_t* sd_tensor_retain(const sd_tensor_t* tensor);
 SD_API void sd_tensor_free(sd_tensor_t* tensor);
@@ -396,23 +373,38 @@ SD_API sd_status_t sd_dgl_ctx_set_preview_callback(
     bool noisy,
     void* userdata);

+typedef enum {
+    SD_DGL_INPUT_TENSOR,
+    SD_DGL_INPUT_BYTES,
+    SD_DGL_INPUT_STRING,
+} sd_dgl_input_kind_t;
+
 typedef struct {
     const char* name;
-    const sd_tensor_t* tensor;
-} sd_dgl_tensor_input_t;
+    sd_dgl_input_kind_t kind;
+    union {
+        const sd_tensor_t* tensor;
+        struct {
+            const void* data;
+            size_t size;
+        } bytes;
+        const char* string;
+    } value;
+} sd_dgl_input_t;

 // Checks syntax and types without creating a context or loading models.
 // Set allow_tensor_inputs to accept named tensor parameters in fn main(name, ...).
 SD_API sd_status_t sd_dgl_check(const char* source, bool allow_tensor_inputs);

 // Compiles source once per call, binds inputs and executes in the required context.
-// Supply every declared tensor parameter exactly once, or NULL, 0 for no inputs.
-// The run retains tensors as needed; result tensors can share their storage.
+// Supply every main parameter exactly once, or NULL, 0 for no inputs.
+// The run retains tensors and copies strings and byte inputs. Strings are
+// NUL-terminated. Byte inputs can contain NUL.
 // On failure, *result_out is NULL. Compare the return value with SD_STATUS_OK.
 SD_API sd_status_t sd_dgl_run(
     sd_dgl_ctx_t* ctx,
     const char* source,
-    const sd_dgl_tensor_input_t* inputs,
+    const sd_dgl_input_t* inputs,
     size_t input_count,
     sd_dgl_result_t** result_out);
 // Thread-safe. Requests cooperative cancellation of the current run only,
diff --git a/src/api/image_metadata.cpp b/src/api/image_metadata.cpp
index 5924800..c793e82 100644
--- a/src/api/image_metadata.cpp
+++ b/src/api/image_metadata.cpp
@@ -1,4 +1,4 @@
-#include "api/api.h"
+#include "api/metadata.h"

 #include <algorithm>
 #include <cctype>
@@ -13,6 +13,7 @@
 #include <map>
 #include <set>
 #include <sstream>
+#include <stdexcept>
 #include <string>
 #include <utility>
 #include <vector>
@@ -1432,29 +1433,20 @@ namespace sd::metadata_reader {

 }  // namespace sd::metadata_reader

-static thread_local std::string metadata_report_text;
-
-const char* sd_read_metadata(const char* path, uint32_t flags) {
-    const char* result = nullptr;
-    sd::api::call([&] {
-        constexpr uint32_t allowed = SD_METADATA_READ_JSON | SD_METADATA_READ_RAW | SD_METADATA_READ_BRIEF | SD_METADATA_READ_STRUCTURAL;
-        if (!path || (flags & ~allowed))
-            return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "path is required and metadata flags must be recognized");
+namespace sd::metadata {
+    std::string read_report(const std::string& path, const ReportOptions& options) {
         json report;
         std::string error;
-        if (!sd::metadata_reader::build_metadata_report(path, flags & SD_METADATA_READ_RAW, report, error))
-            return sd::api::error(SD_STATUS_LOAD_FAILED, nullptr, error.c_str());
-        auto visible_report = sd::metadata_reader::filter_visible_entries(report, flags & SD_METADATA_READ_STRUCTURAL);
+        if (!metadata_reader::build_metadata_report(path, options.raw, report, error))
+            throw std::runtime_error(error);
+        auto visible_report = metadata_reader::filter_visible_entries(report, options.structural);
         std::ostringstream output;
-        if (flags & SD_METADATA_READ_JSON) {
+        if (options.json) {
             visible_report["file"] = path;
             output << visible_report.dump(2, ' ', false, json::error_handler_t::replace) << "\n";
         } else {
-            sd::metadata_reader::print_text_report(path, visible_report, flags & SD_METADATA_READ_STRUCTURAL, flags & SD_METADATA_READ_BRIEF, output);
+            metadata_reader::print_text_report(path, visible_report, options.structural, options.brief, output);
         }
-        metadata_report_text = output.str();
-        result               = metadata_report_text.c_str();
-        return SD_STATUS_OK;
-    });
-    return result;
+        return output.str();
+    }
 }
diff --git a/src/api/media_metadata.cpp b/src/api/media_metadata.cpp
index ce3e5fc..68ab7a2 100644
--- a/src/api/media_metadata.cpp
+++ b/src/api/media_metadata.cpp
@@ -4,8 +4,6 @@
 #include <limits>
 #include <stdexcept>

-#include "api/api.h"
-
 namespace sd::metadata {
     static std::string xml_text(const std::string& info) {
         std::string escaped;
@@ -45,6 +43,7 @@ namespace sd::metadata {
     }

     static bool jpeg_comment(std::vector<uint8_t>& comments, const std::string& label, const std::string& value) {
+        constexpr size_t jpeg_comment_max_bytes = 65533;
         if (value.empty())
             return true;
         const size_t size = label.size() + 1 + value.size() + 1;
@@ -60,7 +59,7 @@ namespace sd::metadata {
         return true;
     }

-    bool jpeg_metadata(std::vector<uint8_t>& comments, const std::string& source, const std::string& parameters) {
+    static bool jpeg_metadata(std::vector<uint8_t>& comments, const std::string& source, const std::string& parameters) {
         return source.empty() || (jpeg_comment(comments, "parameters", parameters) && jpeg_comment(comments, "dgl", source));
     }

@@ -101,7 +100,7 @@ namespace sd::metadata {
         return true;
     }

-    bool png_metadata(std::vector<uint8_t>& chunks, const std::string& source, const std::string& parameters) {
+    static bool png_metadata(std::vector<uint8_t>& chunks, const std::string& source, const std::string& parameters) {
         return source.empty() || (png_text(chunks, "dgl", source) && png_text(chunks, "parameters", parameters));
     }

@@ -138,36 +137,3 @@ namespace sd::metadata {
         return bytes;
     }
 }
-
-static thread_local std::vector<uint8_t> metadata_chunk_bytes;
-
-sd_status_t sd_get_metadata_chunk(const char* source, sd_metadata_format_t format, const void** data_out, size_t* size_out) {
-    if (data_out)
-        *data_out = nullptr;
-    if (size_out)
-        *size_out = 0;
-    return sd::api::call([&] {
-        if (!source || !data_out || !size_out)
-            return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "source, data_out and size_out are required");
-        auto& bytes = metadata_chunk_bytes;
-        bytes.clear();
-        if (format == SD_METADATA_AVI) {
-            bytes = sd::metadata::avi_info(source);
-        } else {
-            if (format != SD_METADATA_PNG && format != SD_METADATA_JPEG && format != SD_METADATA_XMP)
-                return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "unknown metadata format");
-            const auto info       = sd::api::generation_metadata(source);
-            const auto parameters = info.value("infotext", "");
-            if (format == SD_METADATA_XMP) {
-                const auto text = sd::metadata::generation_xmp(source, parameters);
-                bytes.assign(text.begin(), text.end());
-            } else if (!(format == SD_METADATA_PNG ? sd::metadata::png_metadata(bytes, source, parameters)
-                                                   : sd::metadata::jpeg_metadata(bytes, source, parameters))) {
-                return sd::api::error(SD_STATUS_OUT_OF_RANGE, nullptr, "generation metadata exceeds container capacity");
-            }
-        }
-        *data_out = bytes.empty() ? nullptr : bytes.data();
-        *size_out = bytes.size();
-        return SD_STATUS_OK;
-    });
-}
diff --git a/src/api/metadata.h b/src/api/metadata.h
index b33837c..4e2dd2e 100644
--- a/src/api/metadata.h
+++ b/src/api/metadata.h
@@ -1,7 +1,6 @@
 #ifndef __SD_API_METADATA_H__
 #define __SD_API_METADATA_H__

-#include <cstddef>
 #include <cstdint>
 #include <string>
 #include <vector>
@@ -13,10 +12,15 @@ namespace sd::api {
 }

 namespace sd::metadata {
-    constexpr std::size_t jpeg_comment_max_bytes = 65533;
+    struct ReportOptions {
+        bool json       = false;
+        bool raw        = false;
+        bool brief      = false;
+        bool structural = false;
+    };
+
+    std::string read_report(const std::string& path, const ReportOptions& options);
     std::string generation_xmp(const std::string& source, const std::string& parameters = {});
-    bool png_metadata(std::vector<uint8_t>& chunks, const std::string& source, const std::string& parameters);
-    bool jpeg_metadata(std::vector<uint8_t>& comments, const std::string& source, const std::string& parameters);
     bool embed_png_metadata(std::vector<uint8_t>& image, const std::string& source, const std::string& parameters = {});
     bool embed_jpeg_metadata(std::vector<uint8_t>& image, const std::string& source, const std::string& parameters = {});
     std::vector<uint8_t> avi_info(const std::string& source);
diff --git a/src/api/tensor.cpp b/src/api/tensor.cpp
index 7f0db51..f783346 100644
--- a/src/api/tensor.cpp
+++ b/src/api/tensor.cpp
@@ -168,6 +168,30 @@ sd_tensor_t* sd_tensor_create(sd_tensor_type_t type, size_t rank, const int64_t*
     return result;
 }

+sd_tensor_t* sd_tensor_create_from_chunks(sd_tensor_type_t type, size_t rank, const int64_t* shape, const void* const* chunks, size_t chunk_count, size_t chunk_bytes) {
+    sd_tensor_t* result = nullptr;
+    sd::api::call([&] {
+        if (rank > 8 || (rank && !shape) || !chunks || !chunk_count || !chunk_bytes)
+            return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "invalid tensor shape or chunks");
+        std::vector<int64_t> dimensions;
+        if (rank)
+            dimensions.assign(shape, shape + rank);
+        const auto bytes = sd::api::tensor_byte_size(type, dimensions);
+        if (bytes % chunk_bytes || bytes / chunk_bytes != chunk_count)
+            return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "chunk sizes do not match the tensor shape");
+        for (size_t i = 0; i < chunk_count; ++i)
+            if (!chunks[i])
+                return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "tensor chunk data is required");
+        auto tensor       = std::make_unique<sd_tensor_t>(type, std::move(dimensions));
+        auto* destination = static_cast<uint8_t*>(tensor->mutable_data());
+        for (size_t i = 0; i < chunk_count; ++i)
+            std::memcpy(destination + i * chunk_bytes, chunks[i], chunk_bytes);
+        result = tensor.release();
+        return SD_STATUS_OK;
+    });
+    return result;
+}
+
 sd_tensor_t* sd_tensor_retain(const sd_tensor_t* tensor) {
     if (tensor)
         tensor->references.fetch_add(1, std::memory_order_relaxed);
diff --git a/src/core/temporary_output.h b/src/core/temporary_output.h
new file mode 100644
index 0000000..51c07a2
--- /dev/null
+++ b/src/core/temporary_output.h
@@ -0,0 +1,39 @@
+#ifndef __SD_CORE_TEMPORARY_OUTPUT_H__
+#define __SD_CORE_TEMPORARY_OUTPUT_H__
+
+#include <atomic>
+#include <chrono>
+#include <cstdint>
+#include <filesystem>
+#include <string>
+
+namespace sd {
+    class TemporaryOutput {
+        std::filesystem::path directory_;
+        std::filesystem::path path_;
+
+    public:
+        TemporaryOutput(const std::filesystem::path& destination, const std::string& prefix) {
+            static std::atomic<uint64_t> sequence{0};
+            const auto timestamp = std::chrono::steady_clock::now().time_since_epoch().count();
+            const auto name      = prefix + std::to_string(timestamp) + "-";
+            do {
+                directory_ = destination.parent_path() / (name + std::to_string(sequence.fetch_add(1, std::memory_order_relaxed)));
+                path_      = directory_ / destination.filename();
+            } while (!std::filesystem::create_directory(directory_));
+        }
+
+        TemporaryOutput(const TemporaryOutput&)            = delete;
+        TemporaryOutput& operator=(const TemporaryOutput&) = delete;
+
+        const std::filesystem::path& path() const { return path_; }
+
+        ~TemporaryOutput() {
+            std::error_code ignored;
+            std::filesystem::remove(path_, ignored);
+            std::filesystem::remove(directory_, ignored);
+        }
+    };
+}
+
+#endif  // __SD_CORE_TEMPORARY_OUTPUT_H__
diff --git a/src/dgl/bindings/audio.cpp b/src/dgl/bindings/audio.cpp
index f53369f..f8657d4 100644
--- a/src/dgl/bindings/audio.cpp
+++ b/src/dgl/bindings/audio.cpp
@@ -1,8 +1,9 @@
 #include "dgl/bindings/audio.h"

-#include <algorithm>
-#include <cctype>
 #include "dgl/bindings/conversion.h"
+#include "dgl/bytes.h"
+#include "dgl/ops/ffmpeg.h"
+#include "dgl/ops/media_encoding.h"

 namespace sd::dgl {
     OutputSignature audio_signature() {
@@ -29,16 +30,19 @@ namespace sd::dgl {
     }

     Value execute_load_audio(Values& args, RunState&) {
-        return audio_result(read_wav(std::filesystem::u8path(get_string(args, "path"))));
+        ops::MediaInput input(std::filesystem::u8path(get_string(args, "path")));
+        return audio_result(ops::decode_audio(input));
+    }
+    Value execute_decode_audio(Values& args, RunState&) {
+        ops::MediaInput input(object<Bytes>(args, "data")->data);
+        return audio_result(ops::decode_audio(input));
     }
     Value execute_save_audio(Values& args, RunState&) {
-        auto path      = std::filesystem::u8path(get_string(args, "path"));
-        auto extension = path.extension().u8string();
-        std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
-        if (extension != ".wav")
-            throw std::runtime_error("audio output supports .wav only");
+        const auto path = get_string(args, "path");
+        require_file_access(path, SD_DGL_FILE_WRITE);
+        const auto output = std::filesystem::u8path(path);
         const auto audio = read_audio_dict(args.at("audio"));
-        write_wav(*audio.samples, audio.sample_rate, path, get_string(args, "format") == "pcm16");
+        ops::write_media_file(output, ops::encode_audio(audio, ops::media_path_format(output), get_string(args, "format") == "pcm16"));
         return Value::void_value();
     }
 }
diff --git a/src/dgl/bindings/audio.h b/src/dgl/bindings/audio.h
index 0a1ae9a..3b6a4b1 100644
--- a/src/dgl/bindings/audio.h
+++ b/src/dgl/bindings/audio.h
@@ -9,6 +9,7 @@ namespace sd::dgl {
     Value audio_result(ops::AudioReadResult audio);
     ops::AudioReadResult read_audio_dict(const Value& value, bool allow_empty = false);
     Value execute_load_audio(Values& args, RunState&);
+    Value execute_decode_audio(Values& args, RunState&);
     Value execute_save_audio(Values& args, RunState&);
 }  // namespace sd::dgl

diff --git a/src/dgl/bindings/conversion.h b/src/dgl/bindings/conversion.h
index 43e2292..5ad40f8 100644
--- a/src/dgl/bindings/conversion.h
+++ b/src/dgl/bindings/conversion.h
@@ -26,8 +26,6 @@ namespace sd::dgl {
     using ops::image_view;
     using ops::interpolate_tensor;
     using ops::read_image_tensor;
-    using ops::read_wav;
-    using ops::write_wav;

     const sd_tensor_t& i64_vector(const Value& value);
     std::vector<int64_t> read_int_vector(const Value& value);
diff --git a/src/dgl/bindings/image.cpp b/src/dgl/bindings/image.cpp
index 7d4cc8c..5f00aab 100644
--- a/src/dgl/bindings/image.cpp
+++ b/src/dgl/bindings/image.cpp
@@ -3,6 +3,8 @@
 #include "core/image_tensor.h"
 #include "dgl/bindings/arguments.h"
 #include "dgl/bindings/conversion.h"
+#include "dgl/bindings/media.h"
+#include "dgl/bytes.h"

 namespace sd::dgl {
     Value execute_image_to_u8(Values& args, RunState&) {
@@ -28,7 +30,10 @@ namespace sd::dgl {
     }

     Value execute_load_image(Values& args, RunState&) {
-        return Value::object(read_image_tensor(get_string(args, "path")));
+        return Value::object(read_image_tensor(get_string(args, "path"), int(get_int(args, "channels")), get_bool(args, "strict_channels")));
+    }
+    Value execute_decode_image(Values& args, RunState&) {
+        return Value::object(ops::decode_image(object<Bytes>(args, "data")->data, int(get_int(args, "channels")), get_bool(args, "strict_channels")));
     }
     Value execute_load_images(Values& args, RunState&) {
         std::vector<Value> images;
@@ -37,7 +42,7 @@ namespace sd::dgl {
         return Value::list(std::move(images));
     }
     Value execute_save_image(Values& args, RunState& state) {
-        ops::save_image(*object<sd_tensor_t>(args, "image"), get_string(args, "path"), state.metadata);
+        ops::save_image(*object<sd_tensor_t>(args, "image"), get_string(args, "path"), media_metadata(args, state), int(get_int(args, "quality")));
         return Value::void_value();
     }
 }
diff --git a/src/dgl/bindings/image.h b/src/dgl/bindings/image.h
index 71629ad..ec763f8 100644
--- a/src/dgl/bindings/image.h
+++ b/src/dgl/bindings/image.h
@@ -9,6 +9,7 @@ namespace sd::dgl {
     Value execute_image_to_f32(Values& args, RunState&);
     Value execute_image_to_u8(Values& args, RunState&);
     Value execute_load_image(Values& args, RunState&);
+    Value execute_decode_image(Values& args, RunState&);
     Value execute_load_images(Values& args, RunState&);
     Value execute_save_image(Values& args, RunState&);
 }  // namespace sd::dgl
diff --git a/src/dgl/bindings/media.cpp b/src/dgl/bindings/media.cpp
index 6bf6859..22fe643 100644
--- a/src/dgl/bindings/media.cpp
+++ b/src/dgl/bindings/media.cpp
@@ -1,9 +1,12 @@
 #include "dgl/bindings/media.h"

+#include "api/metadata.h"
 #include "core/file_access.h"
 #include "dgl/bindings/audio.h"
 #include "dgl/bindings/conversion.h"
 #include "dgl/bindings/video.h"
+#include "dgl/ops/ffmpeg.h"
+#include "dgl/ops/ffmpeg_process.h"
 #include "dgl/ops/image.h"
 #include "dgl/ops/media_encoding.h"

@@ -17,22 +20,64 @@ namespace sd::dgl {
                             {"mime_type", Value::literal(mime_type)}});
     }

+    std::string media_metadata(const Values& args, const RunState& state) {
+        return args.count("metadata") ? get_string(args, "metadata") : state.metadata;
+    }
+
     Value execute_encode_image(Values& args, RunState& state) {
-        return media_result(ops::encode_image(*object<sd_tensor_t>(args, "image"), state.metadata), "image/png");
+        const auto format = get_string(args, "format");
+        return media_result(ops::encode_image(*object<sd_tensor_t>(args, "image"), media_metadata(args, state), format, int(get_int(args, "quality"))),
+                            ops::media_mime_type(format));
     }

     Value execute_encode_video(Values& args, RunState& state) {
         const auto video = read_video_dict(args.at("video"));
-        ops::VideoSaveOptions options;
-        options.fps_num  = video.fps_num;
-        options.fps_den  = video.fps_den;
-        options.metadata = state.metadata;
-        options.pcm16    = true;
-        if (args.count("audio"))
-            options.audio = read_audio_dict(args.at("audio"), true);
-        if (get_string(args, "format") == "avi")
-            return media_result(ops::encode_avi(*video.frames, options), "video/x-msvideo");
-        return media_result(ops::encode_webm(*video.frames, options), "video/webm");
+        const auto format = get_string(args, "format");
+        return media_result(ops::encode_video(*video.frames, video_save_options(args, state, video), format), ops::media_mime_type(format));
+    }
+
+    Value execute_encode_audio(Values& args, RunState&) {
+        const auto format = get_string(args, "format");
+        const auto audio  = read_audio_dict(args.at("audio"));
+        return media_result(ops::encode_audio(audio, format, get_string(args, "pcm") == "pcm16"), ops::media_mime_type(format));
+    }
+
+    Value execute_media_supported_formats(Values&, RunState&) {
+        std::vector<Value> images{Value::literal("png"), Value::literal("jpeg")};
+        std::vector<Value> video;
+        std::vector<Value> audio{Value::literal("wav")};
+#ifdef SD_USE_WEBM
+        video.push_back(Value::literal("webm"));
+#endif
+#ifdef SD_USE_WEBP
+        images.push_back(Value::literal("webp"));
+        video.push_back(Value::literal("webp"));
+#endif
+        video.push_back(Value::literal("avi"));
+        if (ops::ffmpeg_available()) {
+#ifndef SD_USE_WEBM
+            video.push_back(Value::literal("webm"));
+#endif
+            video.push_back(Value::literal("mp4"));
+            for (const char* format : {"flac", "mp3", "m4a"})
+                audio.push_back(Value::literal(format));
+        }
+        return Value::dict({{"image", Value::list(std::move(images), Kind::String)},
+                            {"video", Value::list(std::move(video), Kind::String)},
+                            {"audio", Value::list(std::move(audio), Kind::String)}});
+    }
+
+    Value execute_read_metadata(Values& args, RunState&) {
+        const auto path = get_string(args, "path");
+        if (path.find('\0') != std::string::npos)
+            throw std::runtime_error("metadata path contains a NUL byte");
+        require_file_access(path, SD_DGL_FILE_READ);
+        metadata::ReportOptions options;
+        options.json       = get_string(args, "format") == "json";
+        options.raw        = get_bool(args, "raw");
+        options.brief      = get_bool(args, "brief");
+        options.structural = get_bool(args, "structural");
+        return Value::literal(metadata::read_report(path, options));
     }

     Value execute_save_media(Values& args, RunState&) {
@@ -42,7 +87,6 @@ namespace sd::dgl {
             mime == media.fields.end() || mime->second.type().kind != Kind::String)
             throw std::runtime_error("media::save requires a dict with data (bytes) and mime_type (string)");
         const auto path = get_string(args, "path");
-        require_file_access(path, SD_DGL_FILE_WRITE);
         ops::save_media(path, data->second.as<Bytes>()->data, mime->second.scalar.get<std::string>());
         return Value::void_value();
     }
diff --git a/src/dgl/bindings/media.h b/src/dgl/bindings/media.h
index 4e52716..3362c7e 100644
--- a/src/dgl/bindings/media.h
+++ b/src/dgl/bindings/media.h
@@ -7,7 +7,11 @@ namespace sd::dgl {
     OutputSignature media_signature();
     Value execute_encode_image(Values& args, RunState& state);
     Value execute_encode_video(Values& args, RunState& state);
+    Value execute_encode_audio(Values& args, RunState& state);
+    Value execute_media_supported_formats(Values& args, RunState& state);
+    Value execute_read_metadata(Values& args, RunState& state);
     Value execute_save_media(Values& args, RunState& state);
+    std::string media_metadata(const Values& args, const RunState& state);
 }

 #endif
diff --git a/src/dgl/bindings/registration.cpp b/src/dgl/bindings/registration.cpp
index 52e2430..104fa7e 100644
--- a/src/dgl/bindings/registration.cpp
+++ b/src/dgl/bindings/registration.cpp
@@ -259,14 +259,21 @@ namespace sd::dgl {
         registry["image::to_u8"] = make_operation(
             {required("pixels", Kind::Tensor)}, {Kind::Tensor}, execute_image_to_u8);
         registry["image::load"] = make_operation(
-            {required("path", Kind::String)}, {Kind::Tensor}, execute_load_image);
+            {required("path", Kind::String), integer("channels", 0, 4, 0), optional("strict_channels", Kind::Boolean, false)},
+            {Kind::Tensor}, execute_load_image);
+        registry["image::decode"] = make_operation(
+            {required("data", Kind::Bytes), integer("channels", 0, 4, 0), optional("strict_channels", Kind::Boolean, false)},
+            {Kind::Tensor}, execute_decode_image);
         registry["image::load_dir"] = make_operation(
             {required("path", Kind::String), integer("max_images", 0, 100000, 0)},
             {Kind::List, Kind::Tensor}, execute_load_images);
         registry["image::save"] = make_operation(
-            {required("path", Kind::String), required("image", Kind::Tensor)}, {Kind::Void}, execute_save_image);
+            {required("path", Kind::String), required("image", Kind::Tensor), integer("quality", 1, 100, 90), optional("metadata", Kind::String)},
+            {Kind::Void}, execute_save_image);
         registry["image::encode"] = make_operation(
-            {required("image", Kind::Tensor), choice("format", {"png"}, "png")}, media_signature(), execute_encode_image);
+            {required("image", Kind::Tensor), choice("format", {"png", "jpeg", "webp"}, "png"), integer("quality", 1, 100, 90),
+             optional("metadata", Kind::String)},
+            media_signature(), execute_encode_image);
         registry["image::canny"] = make_operation(
             {
                 required("image", Kind::Tensor),
@@ -294,7 +301,9 @@ namespace sd::dgl {

     static void register_video_operations(Registry& registry) {
         registry["video::encode"] = make_operation(
-            {required("video", Kind::Dict), optional("audio", Kind::Dict), choice("format", {"webm", "avi"}, "webm")},
+            {required("video", Kind::Dict), optional("audio", Kind::Dict), choice("format", {"webm", "avi", "webp", "mp4"}, "webm"),
+             optional("trim_audio", Kind::Boolean, false), choice("codec", {"auto", "mjpeg", "rgb", "vp9"}, "auto"),
+             integer("quality", 1, 100, 90), choice("audio_format", {"f32", "pcm16"}, "pcm16"), optional("metadata", Kind::String)},
             media_signature(), execute_encode_video);
         registry["video::load"] = make_operation(
             {
@@ -306,15 +315,20 @@ namespace sd::dgl {
             },
             {{Kind::Dict}, {{"video", video_signature()}, {"audio", audio_signature()}}},
             execute_load_video);
+        registry["video::decode"] = make_operation(
+            {required("data", Kind::Bytes), integer("max_frames", 0, 100000, 0), integer("fps_num", 0, 1000000, 0),
+             integer("fps_den", 1, 1000000, 1), optional("audio", Kind::Boolean, true)},
+            {{Kind::Dict}, {{"video", video_signature()}, {"audio", audio_signature()}}}, execute_decode_video);
         registry["video::save"] = make_operation(
             {
                 required("path", Kind::String),
                 required("video", Kind::Dict),
                 optional("audio", Kind::Dict),
                 optional("trim_audio", Kind::Boolean, false),
-                choice("codec", {"auto", "mjpeg", "rgb"}, "auto"),
-                integer("quality", 1, 90, 90),
+                choice("codec", {"auto", "mjpeg", "rgb", "vp9"}, "auto"),
+                integer("quality", 1, 100, 90),
                 choice("audio_format", {"f32", "pcm16"}, "f32"),
+                optional("metadata", Kind::String),
             },
             {Kind::Void},
             execute_save_video);
@@ -327,6 +341,11 @@ namespace sd::dgl {
     }

     static void register_audio_operations(Registry& registry) {
+        registry["audio::decode"] = make_operation(
+            {required("data", Kind::Bytes)}, audio_signature(), execute_decode_audio);
+        registry["audio::encode"] = make_operation(
+            {required("audio", Kind::Dict), choice("format", {"wav", "flac", "mp3", "m4a"}, "wav"), choice("pcm", {"f32", "pcm16"}, "f32")},
+            media_signature(), execute_encode_audio);
         registry["audio::load"] = make_operation(
             {
                 required("path", Kind::String),
@@ -742,6 +761,13 @@ namespace sd::dgl {
     }

     void register_builtin_operations(Registry& registry) {
+        registry["media::supported_formats"] = make_operation(
+            {}, {{Kind::Dict}, {{"image", {Kind::List, Kind::String}}, {"video", {Kind::List, Kind::String}}, {"audio", {Kind::List, Kind::String}}}},
+            execute_media_supported_formats);
+        registry["media::read_metadata"] = make_operation(
+            {required("path", Kind::String), choice("format", {"text", "json"}, "text"), optional("raw", Kind::Boolean, false),
+             optional("brief", Kind::Boolean, false), optional("structural", Kind::Boolean, false)},
+            {Kind::String}, execute_read_metadata);
         registry["media::save"] = make_operation(
             {required("path", Kind::String), required("media", Kind::Dict)}, {Kind::Void}, execute_save_media);
         register_value_operations(registry);
diff --git a/src/dgl/bindings/video.cpp b/src/dgl/bindings/video.cpp
index 86b2bd9..40a372a 100644
--- a/src/dgl/bindings/video.cpp
+++ b/src/dgl/bindings/video.cpp
@@ -2,6 +2,9 @@

 #include "dgl/bindings/audio.h"
 #include "dgl/bindings/conversion.h"
+#include "dgl/bindings/media.h"
+#include "dgl/bytes.h"
+#include "dgl/ops/ffmpeg.h"

 namespace sd::dgl {
     OutputSignature video_signature() {
@@ -28,6 +31,11 @@ namespace sd::dgl {
         return result;
     }

+    static Value video_read_result(ops::VideoReadResult result) {
+        return Value::dict({{"video", video_result(std::move(result.frames), result.fps_num, result.fps_den)},
+                            {"audio", audio_result(std::move(result.audio))}});
+    }
+
     Value execute_load_video(Values& args, RunState&) {
         const auto source = get_string(args, "path");
         require_file_access(source, SD_DGL_FILE_READ);
@@ -36,23 +44,33 @@ namespace sd::dgl {
         const auto fps_num = get_int(args, "fps_num"), fps_den = get_int(args, "fps_den");
         auto result = std::filesystem::is_directory(path) ? ops::load_frame_directory(path, max_frames, fps_num, fps_den)
                                                           : ops::load_video(path, max_frames, fps_num, fps_den, get_bool(args, "audio"));
-        return Value::dict({{"video", video_result(std::move(result.frames), result.fps_num, result.fps_den)},
-                            {"audio", audio_result(std::move(result.audio))}});
+        return video_read_result(std::move(result));
     }

-    Value execute_save_video(Values& args, RunState& state) {
+    Value execute_decode_video(Values& args, RunState&) {
+        ops::MediaInput input(object<Bytes>(args, "data")->data);
+        return video_read_result(ops::decode_video_with_fallback(input, size_t(get_int(args, "max_frames")),
+                                                                 get_int(args, "fps_num"), get_int(args, "fps_den"), get_bool(args, "audio")));
+    }
+
+    ops::VideoSaveOptions video_save_options(Values& args, RunState& state, const ops::VideoReadResult& video) {
         ops::VideoSaveOptions options;
-        options.metadata = state.metadata;
-        const auto video = read_video_dict(args.at("video"));
+        options.metadata = media_metadata(args, state);
         options.fps_num  = video.fps_num;
         options.fps_den  = video.fps_den;
         if (args.count("audio"))
             options.audio = read_audio_dict(args.at("audio"), true);
         options.trim_audio = get_bool(args, "trim_audio");
         options.jpeg       = get_string(args, "codec") != "rgb";
+        options.vp9        = get_string(args, "codec") == "vp9";
         options.quality    = int(get_int(args, "quality"));
         options.pcm16      = get_string(args, "audio_format") == "pcm16";
-        ops::save_video(*video.frames, std::filesystem::u8path(get_string(args, "path")), options);
+        return options;
+    }
+
+    Value execute_save_video(Values& args, RunState& state) {
+        const auto video = read_video_dict(args.at("video"));
+        ops::save_video(*video.frames, std::filesystem::u8path(get_string(args, "path")), video_save_options(args, state, video));
         return Value::void_value();
     }
 }
diff --git a/src/dgl/bindings/video.h b/src/dgl/bindings/video.h
index b5dde7e..b2d7b0a 100644
--- a/src/dgl/bindings/video.h
+++ b/src/dgl/bindings/video.h
@@ -9,7 +9,9 @@ namespace sd::dgl {
     Value video_result(std::shared_ptr<sd_tensor_t> frames, int64_t fps_num, int64_t fps_den);
     ops::VideoReadResult read_video_dict(const Value& value);
     Value execute_load_video(Values& args, RunState&);
+    Value execute_decode_video(Values& args, RunState&);
     Value execute_save_video(Values& args, RunState&);
+    ops::VideoSaveOptions video_save_options(Values& args, RunState& state, const ops::VideoReadResult& video);
 }  // namespace sd::dgl

 #endif  // __SD_DGL_BINDINGS_VIDEO_H__
diff --git a/src/dgl/dgl.cpp b/src/dgl/dgl.cpp
index fec039e..697a556 100644
--- a/src/dgl/dgl.cpp
+++ b/src/dgl/dgl.cpp
@@ -1,9 +1,10 @@
 #include "stable-diffusion.h"

-#include <algorithm>
+#include <cstring>
 #include <mutex>

 #include "api/api.h"
+#include "bytes.h"
 #include "context.h"
 #include "diagnostic.h"
 #include "executor.h"
@@ -68,25 +69,57 @@ namespace {
         }
     };

-    Values bind_inputs(const Graph& graph, const sd_dgl_tensor_input_t* inputs, size_t input_count) {
+    static HostInputKinds input_kinds(const sd_dgl_input_t* inputs, size_t input_count) {
         if (!inputs && input_count)
-            throw Error(SD_STATUS_INVALID_ARGUMENT, "tensor input array is required");
-        const auto& names = graph.syntax.entry.parameters;
+            throw Error(SD_STATUS_INVALID_ARGUMENT, "input array is required");
+        HostInputKinds kinds;
+        for (size_t i = 0; i < input_count; ++i) {
+            const auto& input = inputs[i];
+            if (!input.name || !*input.name)
+                throw Error(SD_STATUS_INVALID_ARGUMENT, "each input requires a name");
+            Kind kind;
+            switch (input.kind) {
+                case SD_DGL_INPUT_TENSOR:
+                    if (!input.value.tensor)
+                        throw Error(SD_STATUS_INVALID_ARGUMENT, "tensor input requires a tensor");
+                    kind = Kind::Tensor;
+                    break;
+                case SD_DGL_INPUT_BYTES:
+                    if (!input.value.bytes.data && input.value.bytes.size)
+                        throw Error(SD_STATUS_INVALID_ARGUMENT, "nonempty byte input requires data");
+                    kind = Kind::Bytes;
+                    break;
+                case SD_DGL_INPUT_STRING:
+                    if (!input.value.string)
+                        throw Error(SD_STATUS_INVALID_ARGUMENT, "string input requires a string");
+                    kind = Kind::String;
+                    break;
+                default:
+                    throw Error(SD_STATUS_INVALID_ARGUMENT, "unknown input kind");
+            }
+            if (!kinds.emplace(input.name, kind).second)
+                throw Error(SD_STATUS_INVALID_ARGUMENT, "duplicate input '" + std::string(input.name) + "'");
+        }
+        return kinds;
+    }
+
+    static Values bind_inputs(const sd_dgl_input_t* inputs, size_t input_count) {
         Values bound;
         for (size_t i = 0; i < input_count; ++i) {
             const auto& input = inputs[i];
-            if (!input.name || !*input.name || !input.tensor)
-                throw Error(SD_STATUS_INVALID_ARGUMENT, "each tensor input requires a name and tensor");
-            if (std::find(names.begin(), names.end(), input.name) == names.end())
-                throw Error(SD_STATUS_INVALID_ARGUMENT, "unknown tensor input '" + std::string(input.name) + "'");
-            if (bound.count(input.name))
-                throw Error(SD_STATUS_INVALID_ARGUMENT, "duplicate tensor input '" + std::string(input.name) + "'");
-            auto retained = std::shared_ptr<sd_tensor_t>(sd_tensor_retain(input.tensor), sd_tensor_free);
-            bound.emplace(input.name, Value::object(std::move(retained)));
+            if (input.kind == SD_DGL_INPUT_TENSOR) {
+                auto retained = std::shared_ptr<sd_tensor_t>(sd_tensor_retain(input.value.tensor), sd_tensor_free);
+                bound.emplace(input.name, Value::object(std::move(retained)));
+            } else if (input.kind == SD_DGL_INPUT_STRING) {
+                bound.emplace(input.name, Value::literal(input.value.string));
+            } else {
+                const auto bytes = input.value.bytes;
+                std::vector<uint8_t> data(bytes.size);
+                if (!data.empty())
+                    std::memcpy(data.data(), bytes.data, data.size());
+                bound.emplace(input.name, Value::object(std::make_shared<Bytes>(std::move(data))));
+            }
         }
-        for (const auto& name : names)
-            if (!bound.count(name))
-                throw Error(SD_STATUS_INVALID_ARGUMENT, "missing tensor input '" + name + "'");
         return bound;
     }

@@ -204,7 +237,7 @@ sd_status_t sd_dgl_check(const char* source, bool allow_tensor_inputs) {
     });
 }

-sd_status_t sd_dgl_run(sd_dgl_ctx_t* ctx, const char* source, const sd_dgl_tensor_input_t* inputs, size_t input_count, sd_dgl_result_t** result_out) {
+sd_status_t sd_dgl_run(sd_dgl_ctx_t* ctx, const char* source, const sd_dgl_input_t* inputs, size_t input_count, sd_dgl_result_t** result_out) {
     if (result_out)
         *result_out = nullptr;
     return api_call([&] {
@@ -213,9 +246,10 @@ sd_status_t sd_dgl_run(sd_dgl_ctx_t* ctx, const char* source, const sd_dgl_tenso
         auto lock = lock_idle(ctx);
         ActiveRun active(*ctx);
         lock.unlock();
-        auto graph = compile(source, operations(), true);
+        const auto kinds = input_kinds(inputs, input_count);
+        auto graph       = compile(source, operations(), true, &kinds);
         active.events.check_cancelled();
-        auto bound  = bind_inputs(graph, inputs, input_count);
+        auto bound  = bind_inputs(inputs, input_count);
         auto result = execute(*ctx, active.events, graph, std::move(bound));
         active.complete(result, result_out);
     });
diff --git a/src/dgl/graph.cpp b/src/dgl/graph.cpp
index b607163..35f8ec8 100644
--- a/src/dgl/graph.cpp
+++ b/src/dgl/graph.cpp
@@ -713,7 +713,7 @@ namespace sd::dgl {
         return counts;
     }

-    Graph compile(const std::string& source, const Registry& registry, bool host_inputs) {
+    Graph compile(const std::string& source, const Registry& registry, bool host_inputs, const HostInputKinds* input_kinds) {
         Graph graph;
         graph.source = source;
         graph.syntax = parse_syntax(source, host_inputs);
@@ -723,8 +723,22 @@ namespace sd::dgl {
         }
         Checker checker(graph, registry);
         Types parameters;
-        for (const auto& name : graph.syntax.entry.parameters)
-            parameters.emplace(name, Checked{{Kind::Tensor}});
+        for (const auto& name : graph.syntax.entry.parameters) {
+            auto kind = Kind::Tensor;
+            if (input_kinds) {
+                const auto input = input_kinds->find(name);
+                if (input == input_kinds->end())
+                    throw std::runtime_error("missing input '" + name + "'");
+                kind = input->second;
+            }
+            parameters.emplace(name, Checked{{kind}});
+        }
+        if (input_kinds && input_kinds->size() != parameters.size()) {
+            for (const auto& input : *input_kinds) {
+                if (!parameters.count(input.first))
+                    throw std::runtime_error("unknown input '" + input.first + "'");
+            }
+        }
         checker.body(graph.syntax.entry.body, std::move(parameters));
         graph.references.emplace("main", reference_counts(graph.syntax.entry, graph));
         for (const auto& [name, function] : graph.syntax.functions)
diff --git a/src/dgl/graph.h b/src/dgl/graph.h
index 4121b79..d83b040 100644
--- a/src/dgl/graph.h
+++ b/src/dgl/graph.h
@@ -76,7 +76,8 @@ namespace sd::dgl {
     std::vector<BoundArgument> bind_arguments(const Expr& expr, const std::vector<std::string>& names, bool all_required = false);
     std::vector<std::string> argument_names(const Operation& operation);
     IterationCall bind_iteration(const Expr& expr, const Syntax& syntax);
-    Graph compile(const std::string& source, const Registry& registry, bool host_inputs = false);
+    using HostInputKinds = std::map<std::string, Kind>;
+    Graph compile(const std::string& source, const Registry& registry, bool host_inputs = false, const HostInputKinds* input_kinds = nullptr);
     void analyze_resources(Graph& graph);

 }  // namespace sd::dgl
diff --git a/src/dgl/ops/audio.cpp b/src/dgl/ops/audio.cpp
index b4055c0..2c0bdc4 100644
--- a/src/dgl/ops/audio.cpp
+++ b/src/dgl/ops/audio.cpp
@@ -1,13 +1,10 @@
 #include "dgl/ops/audio.h"

 #include <algorithm>
-#include <cctype>
 #include <cmath>
 #include <cstring>
-#include <filesystem>
-#include <fstream>

-#include "core/file_access.h"
+#include "dgl/ops/media_input.h"

 namespace sd::dgl::ops {
     sd::Audio audio_view(const sd_tensor_t& tensor, int64_t sample_rate) {
@@ -42,31 +39,60 @@ namespace sd::dgl::ops {
         return uint16_t(data[0]) | (uint16_t(data[1]) << 8);
     }

-    AudioReadResult read_wav(const std::filesystem::path& path) {
-        require_file_access(path.u8string(), SD_DGL_FILE_READ);
-        std::ifstream file(path, std::ios::binary | std::ios::ate);
-        if (!file || file.tellg() < 12 || uint64_t(file.tellg()) > 256 * 1024 * 1024)
-            throw std::runtime_error("cannot read WAV file or file exceeds 256 MiB");
-        std::vector<uint8_t> bytes(size_t(file.tellg()));
-        file.seekg(0);
-        if (!file.read(reinterpret_cast<char*>(bytes.data()), std::streamsize(bytes.size())))
-            throw std::runtime_error("cannot read WAV bytes");
-        if (std::memcmp(bytes.data(), "RIFF", 4) || std::memcmp(bytes.data() + 8, "WAVE", 4) || uint64_t(audio_u32(bytes.data() + 4)) + 8 != bytes.size())
-            throw std::runtime_error("audio input requires a RIFF WAV file");
+    int pcm_format_tag(const uint8_t* format, size_t size) {
+        const auto tag = audio_u16(format);
+        if (tag != 0xfffe)
+            return tag;
+        constexpr uint8_t guid_suffix[] = {0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71};
+        if (size < 40 || audio_u16(format + 16) < 22 || std::memcmp(format + 26, guid_suffix, sizeof(guid_suffix)))
+            return tag;
+        return audio_u16(format + 24);
+    }
+
+    static bool supported_pcm_format(int encoding, int bits) {
+        return (encoding == 1 && (bits == 8 || bits == 16 || bits == 24 || bits == 32)) ||
+               (encoding == 3 && (bits == 32 || bits == 64));
+    }
+
+    AudioReadResult decode_wav(MediaInput& input, bool streaming) {
+        uint8_t header[12]{};
+        if (input.size() >= sizeof(header))
+            input.read(0, header, sizeof(header));
+        if (std::memcmp(header, "RIFF", 4) || std::memcmp(header + 8, "WAVE", 4))
+            throw UnsupportedMedia("audio input requires a RIFF WAV file");
+        if (input.size() > media_decode_limit + wav_container_overhead)
+            throw std::runtime_error("WAV container exceeds the media size limit");
+        const auto* memory = input.bytes();
+        std::vector<uint8_t> file_bytes;
+        if (!memory) {
+            file_bytes.resize(size_t(input.size()));
+            input.read(0, file_bytes.data(), file_bytes.size());
+        }
+        const auto& bytes    = memory ? *memory : file_bytes;
+        const auto riff_size = audio_u32(bytes.data() + 4);
+        if (uint64_t(riff_size) + 8 != bytes.size() && !(streaming && riff_size == UINT32_MAX))
+            throw std::runtime_error("invalid WAV size");
         const uint8_t* format = nullptr;
+        size_t format_size    = 0;
         const uint8_t* data   = nullptr;
         size_t count          = 0;
         for (size_t offset = 12; offset < bytes.size();) {
             if (bytes.size() - offset < 8)
                 throw std::runtime_error("truncated WAV chunk");
-            uint64_t size = audio_u32(bytes.data() + offset + 4), padded = size + (size & 1);
+            const bool sample_chunk = !std::memcmp(bytes.data() + offset, "data", 4);
+            uint64_t size           = audio_u32(bytes.data() + offset + 4);
+            const bool until_eof    = sample_chunk && streaming && size == UINT32_MAX;
+            if (until_eof)
+                size = bytes.size() - offset - 8;
+            const uint64_t padded = size + (until_eof ? 0 : (size & 1));
             if (padded > bytes.size() - offset - 8)
                 throw std::runtime_error("WAV chunk exceeds its container");
             if (!std::memcmp(bytes.data() + offset, "fmt ", 4)) {
                 if (format || size < 16)
                     throw std::runtime_error("invalid WAV format chunk");
                 format = bytes.data() + offset + 8;
-            } else if (!std::memcmp(bytes.data() + offset, "data", 4)) {
+                format_size = size_t(size);
+            } else if (sample_chunk) {
                 if (data)
                     throw std::runtime_error("multiple WAV data chunks are unsupported");
                 data  = bytes.data() + offset + 8;
@@ -76,25 +102,32 @@ namespace sd::dgl::ops {
         }
         if (!format || !data || !count)
             throw std::runtime_error("WAV has no format or samples");
-        int encoding = audio_u16(format), channels = audio_u16(format + 2), bits = audio_u16(format + 14), block = audio_u16(format + 12);
+        int encoding = pcm_format_tag(format, format_size), channels = audio_u16(format + 2), bits = audio_u16(format + 14), block = audio_u16(format + 12);
         uint32_t rate = audio_u32(format + 4);
-        if (channels < 1 || channels > 32 || rate < 1000 || rate > 384000 ||
-            !((encoding == 1 && (bits == 8 || bits == 16 || bits == 24 || bits == 32)) || (encoding == 3 && bits == 32)) || block != channels * (bits / 8) || count % block)
-            throw std::runtime_error("WAV requires interleaved PCM8/16/24/32 or float32 audio");
+        if (!supported_pcm_format(encoding, bits))
+            throw UnsupportedMedia("WAV requires interleaved PCM8/16/24/32 or float32/64 audio");
+        if (channels < 1 || channels > 32 || rate < 1000 || rate > 384000 || block != channels * (bits / 8) || count % block)
+            throw std::runtime_error("invalid WAV audio format or samples");
         return decode_pcm_audio(data, count, encoding, bits, channels, rate);
     }

     AudioReadResult decode_pcm_audio(const uint8_t* data, size_t bytes, int encoding, int bits, int channels, int64_t rate) {
         if (!data || !bytes || channels < 1 || channels > 32 || rate < 1000 || rate > 384000 ||
-            !((encoding == 1 && (bits == 8 || bits == 16 || bits == 24 || bits == 32)) || (encoding == 3 && bits == 32)) || bytes % (channels * (bits / 8)))
+            !supported_pcm_format(encoding, bits) || bytes % (channels * (bits / 8)))
             throw std::runtime_error("invalid PCM/float audio format or samples");
-        size_t samples = bytes / size_t(bits / 8);
-        if (samples > 256 * 1024 * 1024 / sizeof(float))
+        const size_t samples = bytes / size_t(bits / 8);
+        if (samples > media_decode_limit / sizeof(float))
             throw std::runtime_error("decoded WAV exceeds 256 MiB");
-        std::vector<float> decoded(samples);
+        auto tensor   = make_tensor(SD_TENSOR_F32, std::vector<int64_t>{channels, int64_t(samples / channels)});
+        auto* decoded = static_cast<float*>(tensor->mutable_data());
         for (size_t i = 0; i < samples; ++i) {
             const uint8_t* src = data + i * size_t(bits / 8);
-            if (encoding == 3) {
+            if (encoding == 3 && bits == 64) {
+                const uint64_t word = uint64_t(audio_u32(src)) | (uint64_t(audio_u32(src + 4)) << 32);
+                double sample;
+                std::memcpy(&sample, &word, sizeof(sample));
+                decoded[i] = float(sample);
+            } else if (encoding == 3) {
                 uint32_t word = audio_u32(src);
                 std::memcpy(&decoded[i], &word, 4);
             } else if (bits == 8)
@@ -109,12 +142,8 @@ namespace sd::dgl::ops {
                 decoded[i] = float(double(signed_value) / double(int64_t(1) << (bits - 1)));
             }
         }
-        sd::Audio view{};
-        view.data         = decoded.data();
-        view.channels     = channels;
-        view.sample_count = samples / channels;
-        view.sample_rate  = rate;
-        return copy_audio(view);
+        audio_view(*tensor, rate);
+        return {std::move(tensor), rate};
     }

     std::vector<uint8_t> encode_pcm_audio(const sd::Audio& view, bool pcm16, uint64_t first, uint64_t count) {
@@ -135,47 +164,38 @@ namespace sd::dgl::ops {
         return bytes;
     }

-    void write_wav(const sd_tensor_t& samples, int64_t sample_rate, const std::filesystem::path& path, bool pcm16) {
-        require_file_access(path.u8string(), SD_DGL_FILE_WRITE);
-        auto view          = audio_view(samples, sample_rate);
-        uint64_t data_size = view.sample_count * view.channels * (pcm16 ? 2 : 4);
+    std::vector<uint8_t> encode_wav(const sd_tensor_t& samples, int64_t sample_rate, bool pcm16) {
+        const auto view      = audio_view(samples, sample_rate);
+        const uint32_t block = view.channels * (pcm16 ? 2 : 4);
+        const auto data_size = view.sample_count * block;
         if (data_size > UINT32_MAX - 48)
             throw std::runtime_error("WAV exceeds RIFF size limit");
-        std::ofstream file(path, std::ios::binary | std::ios::trunc);
-        if (!file)
-            throw std::runtime_error("cannot open WAV output");
-        auto u32 = [&](uint32_t value) {uint8_t data[]={uint8_t(value),uint8_t(value>>8),uint8_t(value>>16),uint8_t(value>>24)};file.write(reinterpret_cast<char*>(data),4); };
-        auto u16 = [&](uint16_t value) {uint8_t data[]={uint8_t(value),uint8_t(value>>8)};file.write(reinterpret_cast<char*>(data),2); };
-        file.write("RIFF", 4);
+        auto bytes = encode_pcm_audio(view, pcm16, 0, view.sample_count);
+        std::vector<uint8_t> header;
+        auto tag = [&](const char* name) { header.insert(header.end(), name, name + 4); };
+        auto u32 = [&](uint32_t value) {
+            header.insert(header.end(), {uint8_t(value), uint8_t(value >> 8), uint8_t(value >> 16), uint8_t(value >> 24)});
+        };
+        auto u16 = [&](uint16_t value) { header.insert(header.end(), {uint8_t(value), uint8_t(value >> 8)}); };
+        tag("RIFF");
         u32(uint32_t(data_size) + (pcm16 ? 36 : 48));
-        file.write("WAVEfmt ", 8);
+        tag("WAVE");
+        tag("fmt ");
         u32(16);
         u16(pcm16 ? 1 : 3);
         u16(uint16_t(view.channels));
         u32(view.sample_rate);
-        u32(view.sample_rate * view.channels * (pcm16 ? 2 : 4));
-        u16(uint16_t(view.channels * (pcm16 ? 2 : 4)));
+        u32(view.sample_rate * block);
+        u16(uint16_t(block));
         u16(pcm16 ? 16 : 32);
         if (!pcm16) {
-            file.write("fact", 4);
+            tag("fact");
             u32(4);
             u32(uint32_t(view.sample_count));
         }
-        file.write("data", 4);
+        tag("data");
         u32(uint32_t(data_size));
-        for (uint64_t i = 0; i < view.sample_count * view.channels; ++i) {
-            if (pcm16) {
-                int value = int(std::lround(std::clamp(view.data[i], -1.f, 1.f) * 32768));
-                u16(uint16_t(std::clamp(value, -32768, 32767)));
-            } else {
-                uint32_t word;
-                std::memcpy(&word, &view.data[i], 4);
-                u32(word);
-            }
-        }
-        file.close();
-        if (!file)
-            throw std::runtime_error("cannot write WAV output");
+        header.insert(header.end(), bytes.begin(), bytes.end());
+        return header;
     }
-
 }
diff --git a/src/dgl/ops/audio.h b/src/dgl/ops/audio.h
index f5a31d3..59ae3b5 100644
--- a/src/dgl/ops/audio.h
+++ b/src/dgl/ops/audio.h
@@ -1,11 +1,12 @@
 #ifndef __SD_DGL_OPS_AUDIO_H__
 #define __SD_DGL_OPS_AUDIO_H__

-#include <filesystem>
 #include "core/media.h"
 #include "dgl/tensor.h"

 namespace sd::dgl::ops {
+    constexpr size_t wav_container_overhead = 64 * 1024;
+    class MediaInput;
     struct AudioReadResult {
         std::shared_ptr<sd_tensor_t> samples;
         int64_t sample_rate = 0;
@@ -13,8 +14,9 @@ namespace sd::dgl::ops {

     sd::Audio audio_view(const sd_tensor_t& samples, int64_t sample_rate);
     AudioReadResult copy_audio(const sd::Audio& audio);
-    AudioReadResult read_wav(const std::filesystem::path& path);
-    void write_wav(const sd_tensor_t& samples, int64_t sample_rate, const std::filesystem::path& path, bool pcm16);
+    AudioReadResult decode_wav(MediaInput& input, bool streaming = false);
+    int pcm_format_tag(const uint8_t* format, size_t size);
+    std::vector<uint8_t> encode_wav(const sd_tensor_t& samples, int64_t sample_rate, bool pcm16);
     AudioReadResult decode_pcm_audio(const uint8_t* data, size_t bytes, int encoding, int bits, int channels, int64_t rate);
     std::vector<uint8_t> encode_pcm_audio(const sd::Audio& audio, bool pcm16, uint64_t first, uint64_t count);
 }
diff --git a/src/dgl/ops/ffmpeg.cpp b/src/dgl/ops/ffmpeg.cpp
new file mode 100644
index 0000000..c829193
--- /dev/null
+++ b/src/dgl/ops/ffmpeg.cpp
@@ -0,0 +1,253 @@
+#include "dgl/ops/ffmpeg.h"
+
+#include <algorithm>
+#include <array>
+#include <cstring>
+#include <fstream>
+#include <memory>
+#include <random>
+
+#include "core/file_access.h"
+#include "dgl/ops/ffmpeg_process.h"
+#include "dgl/run_events.h"
+
+#ifdef _WIN32
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <sddl.h>
+#else
+#include <cerrno>
+#include <sys/stat.h>
+#endif
+
+namespace sd::dgl::ops {
+    class TemporaryMediaInput {
+        std::filesystem::path directory_;
+        std::filesystem::path path_;
+
+    public:
+        TemporaryMediaInput() {
+            const auto parent = std::filesystem::absolute(std::filesystem::temp_directory_path());
+            std::random_device random;
+#ifdef _WIN32
+            // Restrict access to the owner and inherit that rule on the media file.
+            PSECURITY_DESCRIPTOR descriptor = nullptr;
+            if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;OW)", SDDL_REVISION_1, &descriptor, nullptr))
+                throw std::runtime_error("cannot configure FFmpeg temporary input permissions");
+            const std::unique_ptr<void, decltype(&LocalFree)> security(descriptor, LocalFree);
+            SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), descriptor, FALSE};
+#endif
+            for (int attempt = 0; attempt < 32; ++attempt) {
+                directory_ = parent / (".dgl-ffmpeg-" + std::to_string(random()) + "-" + std::to_string(random()));
+                path_ = directory_ / "input.mov";
+#ifdef _WIN32
+                if (CreateDirectoryW(directory_.c_str(), &attributes))
+                    return;
+                if (GetLastError() != ERROR_ALREADY_EXISTS)
+                    break;
+#else
+                if (mkdir(directory_.c_str(), S_IRWXU) == 0)
+                    return;
+                if (errno != EEXIST)
+                    break;
+#endif
+            }
+            throw std::runtime_error("cannot create a private FFmpeg temporary input directory");
+        }
+
+        TemporaryMediaInput(const TemporaryMediaInput&) = delete;
+        TemporaryMediaInput& operator=(const TemporaryMediaInput&) = delete;
+        ~TemporaryMediaInput() {
+            std::error_code ignored;
+            std::filesystem::remove(path_, ignored);
+            std::filesystem::remove(directory_, ignored);
+        }
+
+        const std::filesystem::path& path() const { return path_; }
+
+        void write(MediaInput& input) const {
+            std::ofstream file(path_, std::ios::binary);
+            if (!file)
+                throw std::runtime_error("cannot open FFmpeg temporary input");
+            std::array<char, 65536> buffer;
+            for (uint64_t offset = 0; offset < input.size();) {
+                check_run_cancelled();
+                const auto count = size_t(std::min<uint64_t>(input.size() - offset, buffer.size()));
+                input.read(offset, buffer.data(), count);
+                if (!file.write(buffer.data(), std::streamsize(count)))
+                    throw std::runtime_error("cannot write FFmpeg temporary input");
+                offset += count;
+            }
+            file.close();
+            if (!file)
+                throw std::runtime_error("cannot finish FFmpeg temporary input");
+        }
+    };
+
+    static uint64_t box_size(const uint8_t* data, size_t size) {
+        uint64_t value = 0;
+        for (size_t i = 0; i < size; ++i)
+            value = (value << 8) | data[i];
+        return value;
+    }
+
+    static bool is_mov(MediaInput& input) {
+        for (uint64_t offset = 0, boxes = 0; boxes < 128 && input.size() - offset >= 8; ++boxes) {
+            uint8_t header[8];
+            input.read(offset, header, sizeof(header));
+            const auto* type     = header + 4;
+            auto size            = box_size(header, 4);
+            uint64_t header_size = 8;
+            if (size == 1) {
+                if (input.size() - offset < 16)
+                    return false;
+                uint8_t extended[8];
+                input.read(offset + 8, extended, sizeof(extended));
+                size        = box_size(extended, sizeof(extended));
+                header_size = 16;
+            } else if (!size) {
+                size = input.size() - offset;
+            }
+            if (size < header_size || size > input.size() - offset)
+                return false;
+            if (!std::memcmp(type, "ftyp", 4) || !std::memcmp(type, "moov", 4))
+                return true;
+            offset += size;
+        }
+        return false;
+    }
+
+    using FFmpegArgs = std::vector<std::filesystem::path>;
+
+    static FFmpegArgs ffmpeg_args() {
+        return {"-hide_banner", "-nostdin", "-loglevel", "error", "-xerror"};
+    }
+
+    static FFmpegOutput convert_input(MediaInput& input, const FFmpegArgs& output_args, size_t limit) {
+        if (!ffmpeg_available(true))
+            return {};
+        auto args = ffmpeg_args();
+        args.insert(args.end(), {"-format_whitelist", "aac,aiff,avi,flac,matroska,webm,mov,mp4,m4a,3gp,3g2,mj2,mp3,mpeg,mpegts,ogg,wav,webp,webp_pipe"});
+        const auto run = [&](const std::vector<uint8_t>& data) {
+            args.insert(args.end(), output_args.begin(), output_args.end());
+            check_run_cancelled();
+            return run_ffmpeg(args, data, limit);
+        };
+        if (!input.path().empty() && !active_file_access.callback) {
+            args.insert(args.end(), {"-protocol_whitelist", "file", "-i", std::filesystem::absolute(input.path())});
+            return run({});
+        }
+        if (is_mov(input)) {
+            const TemporaryMediaInput temporary;
+            temporary.write(input);
+            args.insert(args.end(), {"-protocol_whitelist", "file", "-f", "mov", "-enable_drefs", "0", "-i", temporary.path()});
+            return run({});
+        }
+        args.insert(args.end(), {"-protocol_whitelist", "pipe", "-i", "pipe:0"});
+        if (const auto* bytes = input.bytes())
+            return run(*bytes);
+        if (input.size() > media_decode_limit)
+            throw std::runtime_error("FFmpeg input exceeds 256 MiB");
+        return run(input.read(0, size_t(input.size())));
+    }
+
+    AudioReadResult decode_audio(MediaInput& input) {
+        try {
+            return decode_wav(input);
+        } catch (const UnsupportedMedia&) {
+            const auto converted = convert_input(input, {"-map", "0:a:0", "-c:a", "pcm_f32le", "-f", "wav", "pipe:1"}, media_decode_limit + wav_container_overhead);
+            if (!converted.available)
+                throw;
+            MediaInput wav(converted.bytes);
+            return decode_wav(wav, true);
+        }
+    }
+
+    VideoReadResult decode_video_with_fallback(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
+        try {
+            return decode_video(input, max_frames, fps_num, fps_den, include_audio);
+        } catch (const UnsupportedMedia&) {
+            FFmpegArgs output = {"-map", "0:V:0", "-c:v", "rawvideo", "-pix_fmt", "bgr24"};
+            if (include_audio) {
+                output.insert(output.end(), {"-map", "0:a:0?", "-c:a", "pcm_f32le", "-af", "aresample=async=1:first_pts=0"});
+            } else {
+                output.emplace_back("-an");
+            }
+            if (fps_num) {
+                const auto filter = "fps=" + std::to_string(fps_num) + "/" + std::to_string(fps_den) + ":round=up:start_time=0";
+                output.insert(output.end(), {"-vf", filter});
+            }
+            output.insert(output.end(), {"-vsync", "1"});
+            if (max_frames)
+                output.insert(output.end(), {"-frames:v", std::to_string(max_frames)});
+            output.insert(output.end(), {"-f", "avi", "pipe:1"});
+            const auto converted = convert_input(input, output, media_decode_limit * 2);
+            if (!converted.available)
+                throw;
+            MediaInput avi(converted.bytes);
+            return decode_avi(avi, max_frames, fps_num, fps_den, include_audio, true);
+        }
+    }
+
+    std::vector<uint8_t> encode_audio(const AudioReadResult& audio, const std::string& format, bool pcm16) {
+        if (format == "wav")
+            return encode_wav(*audio.samples, audio.sample_rate, pcm16);
+        auto args       = ffmpeg_args();
+        const auto view = audio_view(*audio.samples, audio.sample_rate);
+        args.insert(args.end(), {"-f", "f32le", "-ar", std::to_string(view.sample_rate), "-ac", std::to_string(view.channels),
+                                 "-i", "pipe:0", "-map", "0:a:0"});
+        if (format == "flac") {
+            args.insert(args.end(), {"-c:a", "flac", "-f", "flac"});
+        } else if (format == "mp3") {
+            args.insert(args.end(), {"-c:a", "libmp3lame", "-f", "mp3"});
+        } else if (format == "m4a") {
+            args.insert(args.end(), {"-c:a", "aac", "-movflags", "+empty_moov+default_base_moof", "-f", "mp4"});
+        } else {
+            throw UnsupportedMedia("unsupported audio output format '" + format + "'");
+        }
+        if (!ffmpeg_available(true))
+            throw UnsupportedMedia("audio output supports .wav only without FFmpeg");
+        args.emplace_back("pipe:1");
+        auto converted = run_ffmpeg(args, encode_pcm_audio(view, false, 0, view.sample_count), media_decode_limit);
+        if (!converted.available)
+            throw UnsupportedMedia("audio output supports .wav only without FFmpeg");
+        return std::move(converted.bytes);
+    }
+
+    std::vector<uint8_t> encode_video_with_ffmpeg(const sd_tensor_t& frames, const VideoSaveOptions& options, const std::string& format, const std::filesystem::path* path) {
+        const bool audio = options.audio.samples && options.audio.samples->bytes;
+        auto args        = ffmpeg_args();
+        args.insert(args.end(), {"-f", "avi", "-i", "pipe:0", "-map", "0:v:0"});
+        if (audio)
+            args.insert(args.end(), {"-map", "0:a:0?"});
+        const auto crf = std::to_string(40 - options.quality * 22 / 100);
+        if (format == "mp4") {
+            args.insert(args.end(), {"-c:v", "libx264", "-crf", crf, "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-pix_fmt", "yuv420p"});
+            if (audio)
+                args.insert(args.end(), {"-c:a", "aac"});
+            args.insert(args.end(), {"-movflags", path ? "+faststart" : "+frag_keyframe+empty_moov+default_base_moof"});
+        } else if (format == "webm") {
+            args.insert(args.end(), {"-c:v", "libvpx-vp9", "-crf", crf, "-b:v", "0", "-pix_fmt", "yuv420p"});
+            if (audio)
+                args.insert(args.end(), {"-c:a", "libopus"});
+        } else {
+            throw UnsupportedMedia("unsupported video output format '" + format + "'");
+        }
+        if (!ffmpeg_available(true))
+            throw UnsupportedMedia("video output format '" + format + "' requires FFmpeg");
+        args.insert(args.end(), {"-f", format});
+        if (path)
+            args.insert(args.end(), {"-y", std::filesystem::absolute(*path)});
+        else
+            args.emplace_back("pipe:1");
+        auto raw_options  = options;
+        raw_options.jpeg  = false;
+        raw_options.pcm16 = false;
+        auto converted    = run_ffmpeg(args, encode_avi(frames, raw_options), media_decode_limit);
+        if (!converted.available)
+            throw UnsupportedMedia("video output format '" + format + "' requires FFmpeg");
+        return std::move(converted.bytes);
+    }
+}
diff --git a/src/dgl/ops/ffmpeg.h b/src/dgl/ops/ffmpeg.h
new file mode 100644
index 0000000..c1fb7c4
--- /dev/null
+++ b/src/dgl/ops/ffmpeg.h
@@ -0,0 +1,14 @@
+#ifndef __SD_DGL_OPS_FFMPEG_H__
+#define __SD_DGL_OPS_FFMPEG_H__
+
+#include "dgl/ops/media_input.h"
+#include "dgl/ops/video.h"
+
+namespace sd::dgl::ops {
+    AudioReadResult decode_audio(MediaInput& input);
+    VideoReadResult decode_video_with_fallback(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio);
+    std::vector<uint8_t> encode_audio(const AudioReadResult& audio, const std::string& format, bool pcm16);
+    std::vector<uint8_t> encode_video_with_ffmpeg(const sd_tensor_t& frames, const VideoSaveOptions& options, const std::string& format, const std::filesystem::path* path = nullptr);
+}
+
+#endif  // __SD_DGL_OPS_FFMPEG_H__
diff --git a/src/dgl/ops/ffmpeg_process.cpp b/src/dgl/ops/ffmpeg_process.cpp
new file mode 100644
index 0000000..2e1eec6
--- /dev/null
+++ b/src/dgl/ops/ffmpeg_process.cpp
@@ -0,0 +1,442 @@
+#include "dgl/ops/ffmpeg_process.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cstdlib>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <type_traits>
+
+#include "dgl/run_events.h"
+
+#ifdef _WIN32
+#define NOMINMAX
+#include <windows.h>
+#else
+#include <fcntl.h>
+#include <pthread.h>
+#include <signal.h>
+#include <spawn.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <cerrno>
+#ifdef __APPLE__
+#include <crt_externs.h>
+#else
+extern char** environ;
+#endif
+#endif
+
+namespace sd::dgl::ops {
+#ifdef _WIN32
+    using NativePipe                  = HANDLE;
+    constexpr NativePipe invalid_pipe = nullptr;
+    static void close_pipe(NativePipe pipe) {
+        CloseHandle(pipe);
+    }
+#else
+    using NativePipe                  = int;
+    constexpr NativePipe invalid_pipe = -1;
+    static void close_pipe(NativePipe pipe) {
+        close(pipe);
+    }
+#endif
+
+    class ProcessHandle {
+        NativePipe value_ = invalid_pipe;
+
+    public:
+        ProcessHandle()                                = default;
+        ProcessHandle(const ProcessHandle&)            = delete;
+        ProcessHandle& operator=(const ProcessHandle&) = delete;
+        ~ProcessHandle() { reset(); }
+        operator NativePipe() const { return value_; }
+        void reset(NativePipe value = invalid_pipe) {
+            if (value_ != invalid_pipe)
+                close_pipe(value_);
+            value_ = value;
+        }
+    };
+
+    struct ProcessPipe {
+        ProcessHandle reader, writer;
+
+        ProcessPipe() {
+#ifdef _WIN32
+            HANDLE read_end, write_end;
+            if (!CreatePipe(&read_end, &write_end, nullptr, 0))
+                throw std::runtime_error("cannot create FFmpeg pipe");
+            reader.reset(read_end);
+            writer.reset(write_end);
+#else
+            int ends[2];
+#ifdef __linux__
+            if (pipe2(ends, O_CLOEXEC))
+#else
+            if (pipe(ends))
+#endif
+                throw std::runtime_error("cannot create FFmpeg pipe");
+            reader.reset(ends[0]);
+            writer.reset(ends[1]);
+            for (auto* end : {&reader, &writer}) {
+                const int fd = fcntl(*end, F_DUPFD_CLOEXEC, 3);
+                if (fd < 0)
+                    throw std::runtime_error("cannot configure FFmpeg pipe");
+                end->reset(fd);
+            }
+#endif
+        }
+    };
+
+#ifdef _WIN32
+    static std::wstring environment_value(const wchar_t* key) {
+        const DWORD size = GetEnvironmentVariableW(key, nullptr, 0);
+        if (!size)
+            return {};
+        std::wstring value(size, L'\0');
+        const auto length = GetEnvironmentVariableW(key, value.data(), size);
+        if (length >= size)
+            throw std::runtime_error("environment changed while resolving FFmpeg");
+        value.resize(length);
+        return value;
+    }
+
+    static std::wstring command_argument(const std::wstring& value) {
+        std::wstring quoted = L"\"";
+        size_t slashes      = 0;
+        for (auto c : value) {
+            if (c == L'\\') {
+                ++slashes;
+            } else {
+                quoted.append(c == L'"' ? slashes * 2 + 1 : slashes, L'\\');
+                quoted.push_back(c);
+                slashes = 0;
+            }
+        }
+        quoted.append(slashes * 2, L'\\');
+        quoted.push_back(L'"');
+        return quoted;
+    }
+
+    class FFmpegProcess {
+        ProcessHandle process_;
+
+    public:
+        void start(const std::filesystem::path& executable, const std::vector<std::filesystem::path>& args, const ProcessPipe& in, const ProcessPipe& out, const ProcessPipe& err) {
+            const auto& program = executable.native();
+            auto command        = command_argument(program);
+            for (const auto& arg : args) {
+                command += L' ';
+                command += command_argument(arg.native());
+            }
+            const HANDLE current = GetCurrentProcess();
+            HANDLE originals[]   = {in.reader, out.writer, err.writer};
+            ProcessHandle child_pipes[3];
+            HANDLE inherited[3];
+            for (size_t i = 0; i < 3; ++i) {
+                if (!DuplicateHandle(current, originals[i], current, &inherited[i], 0, TRUE, DUPLICATE_SAME_ACCESS))
+                    throw std::runtime_error("cannot configure FFmpeg standard streams");
+                child_pipes[i].reset(inherited[i]);
+            }
+            STARTUPINFOEXW startup{};
+            startup.StartupInfo.cb         = sizeof(startup);
+            startup.StartupInfo.dwFlags    = STARTF_USESTDHANDLES;
+            startup.StartupInfo.hStdInput  = inherited[0];
+            startup.StartupInfo.hStdOutput = inherited[1];
+            startup.StartupInfo.hStdError  = inherited[2];
+            SIZE_T size                    = 0;
+            InitializeProcThreadAttributeList(nullptr, 1, 0, &size);
+            std::vector<unsigned char> storage(size);
+            startup.lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
+            if (!InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &size))
+                throw std::runtime_error("cannot initialize FFmpeg process attributes");
+            std::unique_ptr<std::remove_pointer_t<LPPROC_THREAD_ATTRIBUTE_LIST>, decltype(&DeleteProcThreadAttributeList)>
+                attributes(startup.lpAttributeList, DeleteProcThreadAttributeList);
+            if (!UpdateProcThreadAttribute(attributes.get(), 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, sizeof(inherited), nullptr, nullptr))
+                throw std::runtime_error("cannot restrict FFmpeg inherited handles");
+            PROCESS_INFORMATION info{};
+            if (!CreateProcessW(program.c_str(), command.data(), nullptr, nullptr, TRUE,
+                                EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, nullptr, nullptr, &startup.StartupInfo, &info)) {
+                throw std::runtime_error(std::string("cannot start FFmpeg") +
+                                         " (Windows error " + std::to_string(GetLastError()) + ")");
+            }
+            CloseHandle(info.hThread);
+            process_.reset(info.hProcess);
+        }
+
+        bool wait(int& exit_code) {
+            const auto status = WaitForSingleObject(process_, 20);
+            if (status == WAIT_TIMEOUT)
+                return false;
+            DWORD code;
+            if (status != WAIT_OBJECT_0 || !GetExitCodeProcess(process_, &code))
+                throw std::runtime_error("cannot wait for FFmpeg");
+            exit_code = int(code);
+            return true;
+        }
+
+        void stop() noexcept {
+            TerminateProcess(process_, 1);
+            WaitForSingleObject(process_, INFINITE);
+        }
+    };
+
+    static size_t pipe_read(NativePipe pipe, void* data, size_t count) {
+        DWORD read_count;
+        if (ReadFile(pipe, data, DWORD(count), &read_count, nullptr))
+            return read_count;
+        if (GetLastError() == ERROR_BROKEN_PIPE)
+            return 0;
+        throw std::runtime_error("cannot read FFmpeg pipe");
+    }
+
+    static size_t pipe_write(NativePipe pipe, const void* data, size_t count) {
+        DWORD written;
+        if (WriteFile(pipe, data, DWORD(count), &written, nullptr))
+            return written;
+        if (GetLastError() == ERROR_BROKEN_PIPE || GetLastError() == ERROR_NO_DATA)
+            return 0;
+        throw std::runtime_error("cannot write FFmpeg pipe");
+    }
+#else
+    class FFmpegProcess {
+        pid_t pid_ = -1;
+
+    public:
+        void start(const std::filesystem::path& executable, const std::vector<std::filesystem::path>& args, const ProcessPipe& in, const ProcessPipe& out, const ProcessPipe& err) {
+            const auto& program = executable.native();
+            std::vector<char*> argv{const_cast<char*>(program.c_str())};
+            for (const auto& arg : args)
+                argv.push_back(const_cast<char*>(arg.c_str()));
+            argv.push_back(nullptr);
+
+            posix_spawn_file_actions_t actions;
+            if (posix_spawn_file_actions_init(&actions))
+                throw std::runtime_error("cannot initialize FFmpeg process actions");
+            const auto status = posix_spawn_file_actions_adddup2(&actions, in.reader, STDIN_FILENO) |
+                                posix_spawn_file_actions_adddup2(&actions, out.writer, STDOUT_FILENO) |
+                                posix_spawn_file_actions_adddup2(&actions, err.writer, STDERR_FILENO);
+            if (status) {
+                posix_spawn_file_actions_destroy(&actions);
+                throw std::runtime_error("cannot configure FFmpeg standard streams");
+            }
+#ifdef __APPLE__
+            auto env         = *_NSGetEnviron();
+#else
+            auto env = environ;
+#endif
+            const auto error = posix_spawn(&pid_, program.c_str(), &actions, nullptr, argv.data(), env);
+            posix_spawn_file_actions_destroy(&actions);
+            if (error)
+                throw std::runtime_error("cannot start FFmpeg (OS error " + std::to_string(error) + ")");
+        }
+
+        bool wait(int& exit_code) {
+            int status;
+            const auto result = waitpid(pid_, &status, WNOHANG);
+            if (result == 0 || (result < 0 && errno == EINTR)) {
+                std::this_thread::sleep_for(std::chrono::milliseconds(20));
+                return false;
+            }
+            if (result < 0) {
+                if (errno == ECHILD)
+                    pid_ = -1;
+                throw std::runtime_error("cannot wait for FFmpeg");
+            }
+            pid_      = -1;
+            exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
+            return true;
+        }
+
+        void stop() noexcept {
+            if (pid_ <= 0)
+                return;
+            kill(pid_, SIGKILL);
+            while (waitpid(pid_, nullptr, 0) < 0 && errno == EINTR) {
+            }
+            pid_ = -1;
+        }
+    };
+
+    static size_t pipe_read(NativePipe pipe, void* data, size_t count) {
+        ssize_t actual;
+        do {
+            actual = read(pipe, data, count);
+        } while (actual < 0 && errno == EINTR);
+        if (actual < 0)
+            throw std::runtime_error("cannot read FFmpeg pipe");
+        return size_t(actual);
+    }
+
+    static size_t pipe_write(NativePipe pipe, const void* data, size_t count) {
+        ssize_t actual;
+        do {
+            actual = write(pipe, data, count);
+        } while (actual < 0 && errno == EINTR);
+        if (actual < 0 && errno == EPIPE)
+            return 0;
+        if (actual < 0)
+            throw std::runtime_error("cannot write FFmpeg pipe");
+        return size_t(actual);
+    }
+#endif
+
+    static std::filesystem::path find_ffmpeg(bool report_invalid_override) {
+        using Path         = std::filesystem::path;
+        auto is_executable = [](const Path& path) {
+            std::error_code error;
+            if (!std::filesystem::is_regular_file(path, error))
+                return false;
+#ifndef _WIN32
+            return access(path.c_str(), X_OK) == 0;
+#else
+            return true;
+#endif
+        };
+#ifdef _WIN32
+        const auto override_path = environment_value(L"SD_FFMPEG_PATH");
+        const auto paths         = environment_value(L"PATH");
+        constexpr auto separator = L';';
+        constexpr auto program   = L"ffmpeg.exe";
+#else
+        const char* configured          = std::getenv("SD_FFMPEG_PATH");
+        const std::string override_path = configured ? configured : "";
+        const char* path                = std::getenv("PATH");
+        const std::string paths         = path ? path : "/usr/bin:/bin";
+        constexpr auto separator        = ':';
+        constexpr auto program          = "ffmpeg";
+#endif
+        if (!override_path.empty()) {
+            const auto candidate = std::filesystem::absolute(Path(override_path));
+            if (is_executable(candidate))
+                return candidate;
+            if (report_invalid_override)
+                throw std::runtime_error("SD_FFMPEG_PATH does not name a usable FFmpeg executable");
+            return {};
+        }
+        for (size_t offset = 0; offset < paths.size();) {
+            const auto end = paths.find(separator, offset);
+            auto directory = paths.substr(offset, end - offset);
+            offset         = end == Path::string_type::npos ? paths.size() : end + 1;
+#ifdef _WIN32
+            if (directory.size() >= 2 && directory.front() == L'"' && directory.back() == L'"')
+                directory = directory.substr(1, directory.size() - 2);
+#endif
+            if (directory.empty())
+                continue;
+            const auto candidate = std::filesystem::absolute(Path(directory) / program);
+            if (is_executable(candidate))
+                return candidate;
+        }
+        return {};
+    }
+
+    bool ffmpeg_available(bool report_invalid_override) {
+        return !find_ffmpeg(report_invalid_override).empty();
+    }
+
+    FFmpegOutput run_ffmpeg(const std::vector<std::filesystem::path>& args, const std::vector<uint8_t>& input, size_t output_limit) {
+        const auto executable = find_ffmpeg(true);
+        if (executable.empty())
+            return {};
+#if !defined(_WIN32) && !defined(__linux__)
+        // Keep another conversion from spawning during pipe() and F_DUPFD_CLOEXEC.
+        static std::mutex pipe_spawn_mutex;
+        std::unique_lock<std::mutex> pipe_spawn_lock(pipe_spawn_mutex);
+#endif
+        ProcessPipe in, out, err;
+        FFmpegProcess process;
+        process.start(executable, args, in, out, err);
+#if !defined(_WIN32) && !defined(__linux__)
+        pipe_spawn_lock.unlock();
+#endif
+        in.reader.reset();
+        out.writer.reset();
+        err.writer.reset();
+
+        std::vector<uint8_t> output;
+        std::string diagnostic;
+        std::atomic<bool> io_failed{false};
+        std::atomic<bool> overflow{false};
+        std::thread writer, reader, errors;
+        std::exception_ptr failure;
+        int status = -1;
+        try {
+            writer = std::thread([&] {
+                try {
+#ifndef _WIN32
+                    sigset_t mask;
+                    sigemptyset(&mask);
+                    sigaddset(&mask, SIGPIPE);
+                    if (pthread_sigmask(SIG_BLOCK, &mask, nullptr))
+                        throw std::runtime_error("cannot block SIGPIPE for FFmpeg writer");
+#endif
+                    for (size_t offset = 0; offset < input.size();) {
+                        const size_t count = pipe_write(in.writer, input.data() + offset, std::min<size_t>(65536, input.size() - offset));
+                        if (!count)
+                            break;
+                        offset += count;
+                    }
+                } catch (...) {
+                    io_failed = true;
+                }
+                in.writer.reset();
+            });
+            reader              = std::thread([&] {
+                try {
+                    uint8_t buffer[65536];
+                    while (size_t count = pipe_read(out.reader, buffer, sizeof(buffer))) {
+                        if (count > output_limit - output.size()) {
+                            overflow = true;
+                            return;
+                        }
+                        output.insert(output.end(), buffer, buffer + count);
+                    }
+                } catch (...) {
+                    io_failed = true;
+                }
+            });
+            errors              = std::thread([&] {
+                try {
+                    constexpr size_t limit = 8192;
+                    char buffer[4096];
+                    while (size_t count = pipe_read(err.reader, buffer, sizeof(buffer)))
+                        diagnostic.append(buffer, std::min(count, limit - diagnostic.size()));
+                } catch (...) {
+                    io_failed = true;
+                }
+            });
+            const auto deadline = std::chrono::steady_clock::now() + std::chrono::minutes(2);
+            while (!process.wait(status)) {
+                check_run_cancelled();
+                if (io_failed || overflow)
+                    break;
+                if (std::chrono::steady_clock::now() > deadline)
+                    throw std::runtime_error("FFmpeg conversion timed out");
+            }
+        } catch (...) {
+            failure = std::current_exception();
+        }
+        if (failure || io_failed || overflow)
+            process.stop();
+        for (auto* thread : {&writer, &reader, &errors}) {
+            if (thread->joinable())
+                thread->join();
+        }
+        if (failure)
+            std::rethrow_exception(failure);
+        if (overflow)
+            throw std::runtime_error("FFmpeg output exceeds the media size limit");
+        if (io_failed)
+            throw std::runtime_error("FFmpeg pipe I/O failed");
+        if (status) {
+            const auto last = diagnostic.find_last_not_of(" \t\r\n");
+            diagnostic.resize(last == std::string::npos ? 0 : last + 1);
+            throw std::runtime_error("FFmpeg exited with status " + std::to_string(status) + (diagnostic.empty() ? "" : ": " + diagnostic));
+        }
+        return {true, std::move(output)};
+    }
+}
diff --git a/src/dgl/ops/ffmpeg_process.h b/src/dgl/ops/ffmpeg_process.h
new file mode 100644
index 0000000..97c8205
--- /dev/null
+++ b/src/dgl/ops/ffmpeg_process.h
@@ -0,0 +1,19 @@
+#ifndef __SD_DGL_OPS_FFMPEG_PROCESS_H__
+#define __SD_DGL_OPS_FFMPEG_PROCESS_H__
+
+#include <cstddef>
+#include <cstdint>
+#include <filesystem>
+#include <vector>
+
+namespace sd::dgl::ops {
+    struct FFmpegOutput {
+        bool available = false;
+        std::vector<uint8_t> bytes;
+    };
+
+    bool ffmpeg_available(bool report_invalid_override = false);
+    FFmpegOutput run_ffmpeg(const std::vector<std::filesystem::path>& args, const std::vector<uint8_t>& input, size_t output_limit);
+}
+
+#endif  // __SD_DGL_OPS_FFMPEG_PROCESS_H__
diff --git a/src/dgl/ops/image.cpp b/src/dgl/ops/image.cpp
index f7f334b..2526901 100644
--- a/src/dgl/ops/image.cpp
+++ b/src/dgl/ops/image.cpp
@@ -2,6 +2,8 @@
 #include "api/metadata.h"
 #include "core/file_access.h"
 #include "core/ggml_tensor_utils.h"
+#include "dgl/ops/media_encoding.h"
+#include "dgl/ops/media_input.h"
 #include "dgl/ops/tensor.h"

 #include <algorithm>
@@ -19,6 +21,12 @@
 #define STBIW_WINDOWS_UTF8
 #include "stb_image_write.h"

+#ifdef SD_USE_WEBP
+#include <webp/decode.h>
+#include <webp/encode.h>
+#include <webp/mux.h>
+#endif
+
 namespace sd::dgl::ops {

     static void validate_image_shape(int64_t width, int64_t height, int64_t channels) {
@@ -152,19 +160,56 @@ namespace sd::dgl::ops {
         return sd::Tensor<int64_t>({4, count}, std::move(boxes));
     }

-    std::shared_ptr<sd_tensor_t> read_image_tensor(const std::string& path, int requested_channels) {
-        require_file_access(path, SD_DGL_FILE_READ);
+    std::shared_ptr<sd_tensor_t> decode_image(const std::vector<uint8_t>& bytes, int requested_channels, bool strict_channels) {
+        if (bytes.empty() || bytes.size() > media_decode_limit)
+            throw std::runtime_error("invalid image input size");
+        if (bytes.size() >= 12 && !std::memcmp(bytes.data(), "RIFF", 4) && !std::memcmp(bytes.data() + 8, "WEBP", 4)) {
+#ifdef SD_USE_WEBP
+            WebPBitstreamFeatures features{};
+            if (WebPGetFeatures(bytes.data(), bytes.size(), &features) != VP8_STATUS_OK)
+                throw std::runtime_error("invalid WebP image");
+            const int channels        = features.has_alpha ? 4 : 3;
+            const int output_channels = requested_channels ? requested_channels : channels;
+            if (strict_channels && output_channels > channels)
+                throw std::runtime_error("image has fewer channels than requested");
+            auto image                 = allocate_image(features.width, features.height, output_channels);
+            const int decoded_channels = output_channels == 4 ? 4 : 3;
+            std::vector<uint8_t> rgb(output_channels == 1 ? size_t(features.width) * features.height * 3 : 0);
+            auto* destination = rgb.empty() ? static_cast<uint8_t*>(image->mutable_data()) : rgb.data();
+            const auto stride = features.width * decoded_channels;
+            auto decode       = decoded_channels == 4 ? WebPDecodeRGBAInto : WebPDecodeRGBInto;
+            if (!decode(bytes.data(), bytes.size(), destination, size_t(stride) * features.height, stride))
+                throw std::runtime_error("cannot decode WebP image");
+            auto* gray = static_cast<uint8_t*>(image->mutable_data());
+            for (size_t i = 0; i < rgb.size() / 3; ++i)
+                gray[i] = uint8_t((77 * rgb[3 * i] + 150 * rgb[3 * i + 1] + 29 * rgb[3 * i + 2]) >> 8);
+            return image;
+#else
+            throw UnsupportedMedia("WebP image input requires a build with SD_WEBP=ON");
+#endif
+        }
         int width, height, channels;
-        if (!stbi_info(path.c_str(), &width, &height, &channels))
-            throw std::runtime_error("cannot read image '" + path + "'");
+        const auto length = int(bytes.size());
+        if (!stbi_info_from_memory(bytes.data(), length, &width, &height, &channels))
+            throw std::runtime_error("cannot identify image input");
         const int output_channels = requested_channels ? requested_channels : (channels == 2 ? 4 : channels);
         validate_image_shape(width, height, output_channels);
-        std::unique_ptr<stbi_uc, decltype(&stbi_image_free)> pixels(stbi_load(path.c_str(), &width, &height, &channels, output_channels), stbi_image_free);
+        if (strict_channels && requested_channels > channels)
+            throw std::runtime_error("image has fewer channels than requested");
+        std::unique_ptr<stbi_uc, decltype(&stbi_image_free)> pixels(
+            stbi_load_from_memory(bytes.data(), length, &width, &height, &channels, output_channels), stbi_image_free);
         if (!pixels)
             throw std::runtime_error("image decode failed");
         return copy_image({uint32_t(width), uint32_t(height), uint32_t(output_channels), pixels.get()});
     }

+    std::shared_ptr<sd_tensor_t> read_image_tensor(const std::string& path, int requested_channels, bool strict_channels) {
+        MediaInput input(std::filesystem::u8path(path));
+        if (input.size() > media_decode_limit)
+            throw std::runtime_error("image input exceeds 256 MiB");
+        return decode_image(input.read(0, size_t(input.size())), requested_channels, strict_channels);
+    }
+
     std::vector<std::shared_ptr<sd_tensor_t>> read_image_directory(const std::filesystem::path& path, size_t max_images, int channels) {
         require_file_access(path.u8string(), SD_DGL_FILE_READ);
         std::vector<std::filesystem::path> paths;
@@ -224,7 +269,7 @@ namespace sd::dgl::ops {
         return result;
     }

-    std::vector<uint8_t> encode_image(const sd_tensor_t& input, const std::string& metadata) {
+    std::vector<uint8_t> encode_image(const sd_tensor_t& input, const std::string& metadata, const std::string& format, int quality) {
         const auto image = image_view(input);
         std::vector<uint8_t> bytes;
         auto append = [](void* context, void* data, int size) {
@@ -232,22 +277,64 @@ namespace sd::dgl::ops {
             const auto* first = static_cast<const uint8_t*>(data);
             output.insert(output.end(), first, first + size);
         };
-        if (!stbi_write_png_to_func(append, &bytes, image.width, image.height, image.channel, image.data, image.width * image.channel) ||
-            !sd::metadata::embed_png_metadata(bytes, metadata))
+        if (format == "webp") {
+#ifdef SD_USE_WEBP
+            std::vector<uint8_t> rgb;
+            if (image.channel == 1) {
+                rgb.resize(size_t(image.width) * image.height * 3);
+                for (size_t i = 0; i < rgb.size(); ++i)
+                    rgb[i] = image.data[i / 3];
+            }
+            uint8_t* raw       = nullptr;
+            const size_t count = image.channel == 4 ? WebPEncodeRGBA(image.data, image.width, image.height, image.width * 4, float(quality), &raw)
+                                                    : WebPEncodeRGB(rgb.empty() ? image.data : rgb.data(), image.width, image.height, image.width * 3, float(quality), &raw);
+            std::unique_ptr<uint8_t, decltype(&WebPFree)> encoded(raw, WebPFree);
+            if (!count)
+                throw std::runtime_error("cannot encode WebP image");
+            bytes.assign(raw, raw + count);
+            embed_webp_metadata(bytes, metadata);
+            return bytes;
+#else
+            throw UnsupportedMedia("WebP image output requires a build with SD_WEBP=ON");
+#endif
+        }
+        if (format != "png" && format != "jpeg")
+            throw UnsupportedMedia("unsupported image output format '" + format + "'");
+        const auto parameters = metadata.empty() ? std::string{} : sd::api::generation_metadata(metadata).value("infotext", "");
+        const bool ok         = format == "jpeg"
+                                    ? stbi_write_jpg_to_func(append, &bytes, image.width, image.height, image.channel, image.data, quality) &&
+                                  sd::metadata::embed_jpeg_metadata(bytes, metadata, parameters)
+                                    : stbi_write_png_to_func(append, &bytes, image.width, image.height, image.channel, image.data, image.width * image.channel) &&
+                                  sd::metadata::embed_png_metadata(bytes, metadata, parameters);
+        if (!ok)
             throw std::runtime_error("cannot encode image or generation metadata");
         return bytes;
     }

-    void save_image(const sd_tensor_t& input, const std::string& path, const std::string& metadata) {
-        if (path.size() < 4 || path.substr(path.size() - 4) != ".png")
-            throw std::runtime_error("image::save requires a .png path");
+    void embed_webp_metadata(std::vector<uint8_t>& bytes, const std::string& metadata) {
+#ifdef SD_USE_WEBP
+        if (metadata.empty())
+            return;
+        const WebPData source{bytes.data(), bytes.size()};
+        std::unique_ptr<WebPMux, decltype(&WebPMuxDelete)> mux(WebPMuxCreate(&source, 0), WebPMuxDelete);
+        const auto xmp = sd::metadata::generation_xmp(metadata, sd::api::generation_metadata(metadata).value("infotext", ""));
+        const WebPData chunk{reinterpret_cast<const uint8_t*>(xmp.data()), xmp.size()};
+        if (!mux || WebPMuxSetChunk(mux.get(), "XMP ", &chunk, 1) != WEBP_MUX_OK)
+            throw std::runtime_error("cannot set WebP generation metadata");
+        WebPData assembled{};
+        if (WebPMuxAssemble(mux.get(), &assembled) != WEBP_MUX_OK)
+            throw std::runtime_error("cannot assemble WebP output");
+        std::unique_ptr<WebPData, decltype(&WebPDataClear)> encoded(&assembled, WebPDataClear);
+        std::vector<uint8_t> result(assembled.bytes, assembled.bytes + assembled.size);
+        mux.reset();
+        bytes = std::move(result);
+#endif
+    }
+
+    void save_image(const sd_tensor_t& input, const std::string& path, const std::string& metadata, int quality) {
         require_file_access(path, SD_DGL_FILE_WRITE);
-        const auto bytes = encode_image(input, metadata);
-        std::ofstream file(std::filesystem::u8path(path), std::ios::binary | std::ios::trunc);
-        file.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()));
-        file.close();
-        if (!file)
-            throw std::runtime_error("cannot save image '" + path + "'");
+        const auto output = std::filesystem::u8path(path);
+        write_media_file(output, encode_image(input, metadata, media_path_format(output), quality));
     }

     void copy_video_frame(sd::Tensor<float>& video, const sd::Tensor<float>& frame, size_t index) {
diff --git a/src/dgl/ops/image.h b/src/dgl/ops/image.h
index 53bc6c5..599dc59 100644
--- a/src/dgl/ops/image.h
+++ b/src/dgl/ops/image.h
@@ -10,10 +10,12 @@ namespace sd::dgl::ops {
     std::shared_ptr<sd_tensor_t> allocate_image(int width, int height, int channels);
     std::shared_ptr<sd_tensor_t> copy_image(const sd::Image& image);
     sd::Image image_view(const sd_tensor_t& tensor);
-    std::shared_ptr<sd_tensor_t> read_image_tensor(const std::string& path, int requested_channels = 0);
+    std::shared_ptr<sd_tensor_t> read_image_tensor(const std::string& path, int requested_channels = 0, bool strict_channels = false);
+    std::shared_ptr<sd_tensor_t> decode_image(const std::vector<uint8_t>& bytes, int requested_channels = 0, bool strict_channels = false);
     std::vector<std::shared_ptr<sd_tensor_t>> read_image_directory(const std::filesystem::path& path, size_t max_images, int channels);
-    void save_image(const sd_tensor_t& input, const std::string& path, const std::string& metadata = {});
-    std::vector<uint8_t> encode_image(const sd_tensor_t& input, const std::string& metadata = {});
+    void save_image(const sd_tensor_t& input, const std::string& path, const std::string& metadata = {}, int quality = 90);
+    std::vector<uint8_t> encode_image(const sd_tensor_t& input, const std::string& metadata = {}, const std::string& format = "png", int quality = 90);
+    void embed_webp_metadata(std::vector<uint8_t>& bytes, const std::string& metadata);
     std::shared_ptr<sd_tensor_t> decode_video_jpeg(const std::vector<uint8_t>& bytes, int width, int height);
     std::vector<uint8_t> encode_video_jpeg(const sd::Image& image, int quality);
     void decode_base64(const std::string& text, uint8_t* bytes, size_t size);
diff --git a/src/dgl/ops/media_encoding.cpp b/src/dgl/ops/media_encoding.cpp
index a02e07e..dbfd0da 100644
--- a/src/dgl/ops/media_encoding.cpp
+++ b/src/dgl/ops/media_encoding.cpp
@@ -6,24 +6,77 @@
 #include <limits>
 #include <stdexcept>

+#include "core/file_access.h"
+#include "dgl/ops/ffmpeg.h"
+#include "dgl/ops/ffmpeg_process.h"
+
 namespace sd::dgl::ops {
-    void save_media(const std::string& path, const std::vector<uint8_t>& data, const std::string& mime_type) {
-        const char* expected = mime_type == "image/png" ? ".png" : mime_type == "video/webm"    ? ".webm"
-                                                               : mime_type == "video/x-msvideo" ? ".avi"
-                                                                                                : nullptr;
-        if (!expected)
-            throw std::runtime_error("media::save does not support MIME type '" + mime_type + "'");
-        const auto output = std::filesystem::u8path(path);
-        auto extension    = output.extension().u8string();
-        std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
-        if (extension != expected)
-            throw std::runtime_error("media::save path extension must be '" + std::string(expected) + "' for " + mime_type);
+    std::string media_path_format(const std::filesystem::path& path) {
+        auto format = path.extension().u8string();
+        if (!format.empty())
+            format.erase(0, 1);
+        std::transform(format.begin(), format.end(), format.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+        return format == "jpg" || format == "jpe" ? "jpeg" : format;
+    }
+
+    const char* media_mime_type(const std::string& format) {
+        if (format == "png")
+            return "image/png";
+        if (format == "jpeg")
+            return "image/jpeg";
+        if (format == "webp")
+            return "image/webp";
+        if (format == "avi")
+            return "video/x-msvideo";
+        if (format == "webm")
+            return "video/webm";
+        if (format == "mp4")
+            return "video/mp4";
+        if (format == "wav")
+            return "audio/wav";
+        if (format == "flac")
+            return "audio/flac";
+        if (format == "mp3")
+            return "audio/mpeg";
+        if (format == "m4a")
+            return "audio/mp4";
+        throw UnsupportedMedia("unsupported media format '" + format + "'");
+    }
+
+    std::vector<uint8_t> encode_video(const sd_tensor_t& frames, const VideoSaveOptions& options, const std::string& format) {
+        if (format == "avi")
+            return encode_avi(frames, options);
+        if (format == "webp")
+            return encode_animated_webp(frames, options);
+        if (format == "webm" && !options.vp9) {
+            try {
+                return encode_webm(frames, options);
+            } catch (const UnsupportedMedia&) {
+                if (!ffmpeg_available(true))
+                    throw;
+                return encode_video_with_ffmpeg(frames, options, format);
+            }
+        }
+        if (format == "mp4" || format == "webm")
+            return encode_video_with_ffmpeg(frames, options, format);
+        throw UnsupportedMedia("video output supports .avi, .webm, .webp and .mp4");
+    }
+
+    void write_media_file(const std::filesystem::path& path, const std::vector<uint8_t>& data) {
         if (data.empty() || data.size() > size_t(std::numeric_limits<std::streamsize>::max()))
-            throw std::runtime_error("media::save requires nonempty bytes that fit a file stream");
-        std::ofstream file(output, std::ios::binary | std::ios::trunc);
+            throw std::runtime_error("encoded media must contain nonempty bytes that fit a file stream");
+        std::ofstream file(path, std::ios::binary | std::ios::trunc);
         file.write(reinterpret_cast<const char*>(data.data()), std::streamsize(data.size()));
         file.close();
         if (!file)
-            throw std::runtime_error("cannot save media '" + path + "'");
+            throw std::runtime_error("cannot save media '" + path.u8string() + "'");
+    }
+
+    void save_media(const std::string& path, const std::vector<uint8_t>& data, const std::string& mime_type) {
+        require_file_access(path, SD_DGL_FILE_WRITE);
+        const auto output = std::filesystem::u8path(path);
+        if (media_mime_type(media_path_format(output)) != mime_type)
+            throw std::runtime_error("media::save path extension does not match MIME type '" + mime_type + "'");
+        write_media_file(output, data);
     }
 }
diff --git a/src/dgl/ops/media_encoding.h b/src/dgl/ops/media_encoding.h
index 4df6d7e..cd4a225 100644
--- a/src/dgl/ops/media_encoding.h
+++ b/src/dgl/ops/media_encoding.h
@@ -5,6 +5,11 @@

 namespace sd::dgl::ops {
     std::vector<uint8_t> encode_webm(const sd_tensor_t& frames, const VideoSaveOptions& options);
+    std::vector<uint8_t> encode_animated_webp(const sd_tensor_t& frames, const VideoSaveOptions& options);
+    std::vector<uint8_t> encode_video(const sd_tensor_t& frames, const VideoSaveOptions& options, const std::string& format);
+    std::string media_path_format(const std::filesystem::path& path);
+    const char* media_mime_type(const std::string& format);
+    void write_media_file(const std::filesystem::path& path, const std::vector<uint8_t>& data);
     void save_media(const std::string& path, const std::vector<uint8_t>& data, const std::string& mime_type);
 }

diff --git a/src/dgl/ops/media_input.cpp b/src/dgl/ops/media_input.cpp
new file mode 100644
index 0000000..01c01d4
--- /dev/null
+++ b/src/dgl/ops/media_input.cpp
@@ -0,0 +1,42 @@
+#include "dgl/ops/media_input.h"
+
+#include <cstring>
+
+#include "core/file_access.h"
+
+namespace sd::dgl::ops {
+    MediaInput::MediaInput(const std::filesystem::path& path)
+        : path_(path) {
+        require_file_access(path.u8string(), SD_DGL_FILE_READ);
+        if (path.native().find(std::filesystem::path::value_type{}) != std::filesystem::path::string_type::npos ||
+            !std::filesystem::is_regular_file(path))
+            throw std::runtime_error("media input must be a regular file");
+        file_.open(path, std::ios::binary | std::ios::ate);
+        const auto end = file_.tellg();
+        if (end < 0)
+            throw std::runtime_error("cannot open media input");
+        size_ = uint64_t(end);
+    }
+
+    void MediaInput::read(uint64_t offset, void* data, size_t size) {
+        if (offset > size_ || size > size_ - offset)
+            throw std::runtime_error("truncated media input");
+        if (!size)
+            return;
+        if (bytes_) {
+            std::memcpy(data, bytes_->data() + size_t(offset), size);
+        } else {
+            file_.seekg(std::streamoff(offset));
+            if (!file_.read(static_cast<char*>(data), std::streamsize(size)))
+                throw std::runtime_error("cannot read media input");
+        }
+    }
+
+    std::vector<uint8_t> MediaInput::read(uint64_t offset, size_t size) {
+        if (size > media_decode_limit)
+            throw std::runtime_error("media data exceeds 256 MiB");
+        std::vector<uint8_t> bytes(size);
+        read(offset, bytes.data(), size);
+        return bytes;
+    }
+}
diff --git a/src/dgl/ops/media_input.h b/src/dgl/ops/media_input.h
new file mode 100644
index 0000000..43d4247
--- /dev/null
+++ b/src/dgl/ops/media_input.h
@@ -0,0 +1,37 @@
+#ifndef __SD_DGL_OPS_MEDIA_INPUT_H__
+#define __SD_DGL_OPS_MEDIA_INPUT_H__
+
+#include <cstdint>
+#include <filesystem>
+#include <fstream>
+#include <stdexcept>
+#include <vector>
+
+namespace sd::dgl::ops {
+    constexpr size_t media_decode_limit = 256 * 1024 * 1024;
+
+    class UnsupportedMedia : public std::runtime_error {
+    public:
+        using std::runtime_error::runtime_error;
+    };
+
+    class MediaInput {
+        std::filesystem::path path_;
+        std::ifstream file_;
+        const std::vector<uint8_t>* bytes_ = nullptr;
+        uint64_t size_                     = 0;
+
+    public:
+        explicit MediaInput(const std::filesystem::path& path);
+        explicit MediaInput(const std::vector<uint8_t>& bytes)
+            : bytes_(&bytes), size_(bytes.size()) {}
+
+        uint64_t size() const { return size_; }
+        const auto& path() const { return path_; }
+        const auto* bytes() const { return bytes_; }
+        void read(uint64_t offset, void* data, size_t size);
+        std::vector<uint8_t> read(uint64_t offset, size_t size);
+    };
+}
+
+#endif  // __SD_DGL_OPS_MEDIA_INPUT_H__
diff --git a/src/dgl/ops/video.cpp b/src/dgl/ops/video.cpp
index 2e11f1b..2f1bf3b 100644
--- a/src/dgl/ops/video.cpp
+++ b/src/dgl/ops/video.cpp
@@ -10,10 +10,15 @@

 #include "api/metadata.h"
 #include "core/file_access.h"
+#include "core/temporary_output.h"
 #include "dgl/ops/audio.h"
+#include "dgl/ops/ffmpeg.h"
 #include "dgl/ops/image.h"
+#include "dgl/ops/media_encoding.h"
+#include "dgl/ops/media_input.h"
 #include "dgl/ops/video_webm.h"
 #include "dgl/ops/video_webp.h"
+#include "dgl/run_events.h"

 namespace sd::dgl::ops {

@@ -33,20 +38,25 @@ namespace sd::dgl::ops {
         return {uint32_t(shape[1]), uint32_t(shape[2]), 3, const_cast<uint8_t*>(data)};
     }

-    VideoReadResult load_video(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
-        std::ifstream file(path, std::ios::binary);
+    VideoReadResult decode_video(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
         uint8_t header[12]{};
-        if (!file || !file.read(reinterpret_cast<char*>(header), sizeof(header)))
-            throw std::runtime_error("cannot read video input header");
+        if (input.size() < sizeof(header))
+            throw UnsupportedMedia("cannot read video input header");
+        input.read(0, header, sizeof(header));
         if (!std::memcmp(header, "RIFF", 4)) {
             if (!std::memcmp(header + 8, "AVI ", 4))
-                return load_avi(path, max_frames, fps_num, fps_den, include_audio);
+                return decode_avi(input, max_frames, fps_num, fps_den, include_audio);
             if (!std::memcmp(header + 8, "WEBP", 4))
-                return load_webp(path, max_frames, fps_num, fps_den);
+                return decode_webp(input, max_frames, fps_num, fps_den);
         }
         if (header[0] == 0x1a && header[1] == 0x45 && header[2] == 0xdf && header[3] == 0xa3)
-            return load_webm(path, max_frames, fps_num, fps_den, include_audio);
-        throw std::runtime_error("unsupported video input; expected AVI, WebP or independent-frame VP8 WebM");
+            return decode_webm(input, max_frames, fps_num, fps_den, include_audio);
+        throw UnsupportedMedia("unsupported video input; expected AVI, WebP or independent-frame VP8 WebM");
+    }
+
+    VideoReadResult load_video(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
+        MediaInput input(path);
+        return decode_video_with_fallback(input, max_frames, fps_num, fps_den, include_audio);
     }

     static uint32_t fourcc(const char* text) {
@@ -64,39 +74,36 @@ namespace sd::dgl::ops {
     };

     class AVIReader {
-        std::ifstream file_;
-        uint64_t size_;
+        MediaInput& input_;
+        bool streaming_;
         size_t chunks_ = 0;

     public:
-        explicit AVIReader(const std::filesystem::path& path)
-            : file_(path, std::ios::binary | std::ios::ate) {
-            if (!file_ || file_.tellg() < 12)
-                throw std::runtime_error("cannot read AVI file");
-            size_ = uint64_t(file_.tellg());
-        }
+        AVIReader(MediaInput& input, bool streaming)
+            : input_(input), streaming_(streaming) {}

-        uint64_t size() const { return size_; }
+        uint64_t size() const { return input_.size(); }

-        std::vector<uint8_t> read(uint64_t offset, uint64_t size) {
-            if (offset > size_ || size > size_ - offset || size > 256 * 1024 * 1024)
-                throw std::runtime_error("invalid AVI data size");
-            std::vector<uint8_t> bytes(size_t(size), 0);
-            file_.seekg(std::streamoff(offset));
-            if (size && !file_.read(reinterpret_cast<char*>(bytes.data()), std::streamsize(size)))
-                throw std::runtime_error("truncated AVI file");
-            return bytes;
+        std::vector<uint8_t> read(uint64_t offset, size_t size) {
+            return input_.read(offset, size);
         }

         AVIChunk chunk(uint64_t offset, uint64_t end) {
             if (offset > end || end - offset < 8 || ++chunks_ > 1000000)
                 throw std::runtime_error("invalid AVI chunk structure or too many chunks");
-            auto bytes      = read(offset, 8);
-            uint64_t size   = read_u32(bytes.data() + 4);
+            uint8_t bytes[12]{};
+            input_.read(offset, bytes, 8);
+            const auto id = read_u32(bytes);
+            uint64_t size = read_u32(bytes + 4);
+            if (streaming_ && id == fourcc("LIST") && size == UINT32_MAX && end - offset >= 12) {
+                input_.read(offset + 8, bytes + 8, 4);
+                if (read_u32(bytes + 8) == fourcc("movi"))
+                    return {id, offset + 8, end - offset - 8, end};
+            }
             uint64_t padded = size + (size & 1);
             if (padded > end - offset - 8)
                 throw std::runtime_error("AVI chunk exceeds its container");
-            return {read_u32(bytes.data()), offset + 8, size, offset + 8 + padded};
+            return {id, offset + 8, size, offset + 8 + padded};
         }
     };

@@ -135,14 +142,17 @@ namespace sd::dgl::ops {
             if (format.size() < 16 || read_u32(header.data() + 28) != 0)
                 throw std::runtime_error("invalid AVI audio header or nonzero stream start");
             auto p          = format.data();
-            audio->encoding = read_u16(p);
+            audio->encoding = pcm_format_tag(p, format.size());
             audio->channels = read_u16(p + 2);
             audio->rate     = read_u32(p + 4);
             audio->block    = read_u16(p + 12);
             audio->bits     = read_u16(p + 14);
+            if (!((audio->encoding == 1 && (audio->bits == 8 || audio->bits == 16 || audio->bits == 24 || audio->bits == 32)) ||
+                  (audio->encoding == 3 && audio->bits == 32)))
+                throw UnsupportedMedia("AVI audio requires PCM or float32; use video::load(audio=false) to skip unsupported audio");
             if (audio->channels < 1 || audio->channels > 32 || audio->rate < 1000 || audio->rate > 384000 ||
-                !((audio->encoding == 1 && (audio->bits == 8 || audio->bits == 16 || audio->bits == 24 || audio->bits == 32)) || (audio->encoding == 3 && audio->bits == 32)) || audio->block != uint32_t(audio->channels * (audio->bits / 8)))
-                throw std::runtime_error("AVI audio requires PCM or float32; use video::load(audio=false) to skip unsupported audio");
+                audio->block != uint32_t(audio->channels * (audio->bits / 8)))
+                throw std::runtime_error("invalid AVI audio format");
             audio->index = index;
         }
         if (header.empty() || read_u32(header.data()) != fourcc("vids") || stream.index >= 0)
@@ -157,8 +167,10 @@ namespace sd::dgl::ops {
         uint32_t compression   = read_u32(p + 16);
         bool jpeg              = compression == fourcc("MJPG") || compression == fourcc("mjpg");
         if (width < 1 || width > 16384 || height < 1 || height > 16384 || width * height > 64 * 1024 * 1024 ||
-            p[12] != 1 || p[13] != 0 || p[14] != 24 || p[15] != 0 || (!jpeg && compression != 0))
-            throw std::runtime_error("AVI requires 24-bit RGB or MJPEG frames with supported dimensions");
+            p[12] != 1 || p[13] != 0)
+            throw std::runtime_error("invalid AVI video dimensions or planes");
+        if (p[14] != 24 || p[15] != 0 || (!jpeg && compression != 0))
+            throw UnsupportedMedia("AVI requires 24-bit RGB or MJPEG frames with supported dimensions");
         int64_t num = read_u32(header.data() + 24), den = read_u32(header.data() + 20);
         if (!num || !den)
             throw std::runtime_error("AVI has no usable frame rate");
@@ -166,7 +178,7 @@ namespace sd::dgl::ops {
         num /= divisor;
         den /= divisor;
         if (num > 1000000 || den > 1000000 || read_u32(header.data() + 28) != 0)
-            throw std::runtime_error("unsupported AVI frame rate or nonzero stream start");
+            throw UnsupportedMedia("unsupported AVI frame rate or nonzero stream start");
         stream = {index, int(width), int(height), num, den, jpeg, top_down};
     }

@@ -199,7 +211,7 @@ namespace sd::dgl::ops {
             auto chunk = reader.chunk(pos, end);
             if (chunk.id == raw || chunk.id == compressed) {
                 if (chunk.size == 0 && !audio)
-                    throw std::runtime_error("AVI dropped frames are unsupported");
+                    throw UnsupportedMedia("AVI dropped frames are unsupported");
                 if (chunk.size)
                     frames.push_back(chunk);
             } else if (chunk.id == fourcc("LIST")) {
@@ -213,16 +225,22 @@ namespace sd::dgl::ops {
         }
     }

-    VideoReadResult load_avi(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
-        if (!std::filesystem::is_regular_file(path))
-            throw std::runtime_error("video path is not a regular file");
-        AVIReader reader(path);
+    VideoReadResult decode_avi(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio, bool streaming) {
+        AVIReader reader(input, streaming);
         auto root = reader.read(0, 12);
         if (read_u32(root.data()) != fourcc("RIFF") || read_u32(root.data() + 8) != fourcc("AVI "))
             throw std::runtime_error("video input supports AVI (RGB or MJPEG) only");
         uint64_t end = uint64_t(read_u32(root.data() + 4)) + 8;
-        if (end != reader.size() || end < 12)
-            throw std::runtime_error("invalid AVI size; segmented OpenDML AVI is unsupported");
+        if (streaming && end == uint64_t(UINT32_MAX) + 8)
+            end = reader.size();
+        if (end != reader.size() || end < 12) {
+            if (end >= 12 && reader.size() > end && reader.size() - end >= 12) {
+                const auto next = reader.read(end, 12);
+                if (read_u32(next.data()) == fourcc("RIFF") && read_u32(next.data() + 8) == fourcc("AVIX"))
+                    throw UnsupportedMedia("invalid AVI size; segmented OpenDML AVI is unsupported");
+            }
+            throw std::runtime_error("invalid AVI size");
+        }
         AVIStream stream;
         AVIAudioStream audio;
         std::vector<AVIChunk> movies;
@@ -526,12 +544,17 @@ namespace sd::dgl::ops {
     }

     void save_video(const sd_tensor_t& frames, const std::filesystem::path& path, const VideoSaveOptions& options) {
-        auto extension = path.extension().u8string();
-        std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
-        if (extension != ".avi")
-            throw std::runtime_error("video output supports .avi (RGB or MJPEG) only");
         require_file_access(path.u8string(), SD_DGL_FILE_WRITE);
-        write_avi(frames, &path, options);
+        const auto format = media_path_format(path);
+        if (format == "avi")
+            write_avi(frames, &path, options);
+        else if (format == "mp4" && !active_file_access.callback) {
+            const TemporaryOutput temporary(path, ".dgl-mp4-");
+            encode_video_with_ffmpeg(frames, options, format, &temporary.path());
+            check_run_cancelled();
+            std::filesystem::rename(temporary.path(), path);
+        } else
+            write_media_file(path, encode_video(frames, options, format));
     }

     VideoReadResult load_frame_directory(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den) {
diff --git a/src/dgl/ops/video.h b/src/dgl/ops/video.h
index 18ff43d..fb8a755 100644
--- a/src/dgl/ops/video.h
+++ b/src/dgl/ops/video.h
@@ -6,6 +6,7 @@
 #include "dgl/tensor.h"

 namespace sd::dgl::ops {
+    class MediaInput;
     struct VideoReadResult {
         std::shared_ptr<sd_tensor_t> frames;
         int64_t fps_num = 24;
@@ -19,6 +20,7 @@ namespace sd::dgl::ops {
         AudioReadResult audio;
         bool trim_audio = false;
         bool jpeg       = true;
+        bool vp9        = false;
         int quality     = 90;
         bool pcm16      = false;
         std::string metadata;
@@ -28,7 +30,8 @@ namespace sd::dgl::ops {
     sd::Image video_frame_view(const sd_tensor_t& frames, size_t index);
     VideoReadResult load_frame_directory(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den);
     VideoReadResult load_video(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio);
-    VideoReadResult load_avi(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio);
+    VideoReadResult decode_video(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio);
+    VideoReadResult decode_avi(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio, bool streaming = false);
     void save_video(const sd_tensor_t& frames, const std::filesystem::path& path, const VideoSaveOptions& options);
     std::vector<uint8_t> encode_avi(const sd_tensor_t& frames, const VideoSaveOptions& options);
 }
diff --git a/src/dgl/ops/video_encoding.cpp b/src/dgl/ops/video_encoding.cpp
index 9bfe60a..73537f2 100644
--- a/src/dgl/ops/video_encoding.cpp
+++ b/src/dgl/ops/video_encoding.cpp
@@ -1,10 +1,21 @@
 #include "dgl/ops/media_encoding.h"

+#include <algorithm>
+#include <cmath>
 #include <cstring>
+#include <limits>
 #include <memory>
 #include <stdexcept>

+#include "dgl/ops/image.h"
+#include "dgl/ops/media_input.h"
 #include "dgl/ops/video_timing.h"
+#include "dgl/run_events.h"
+
+#ifdef SD_USE_WEBP
+#include <webp/decode.h>
+#include <webp/mux.h>
+#endif

 #ifdef SD_USE_WEBM
 #include <mkvmuxer/mkvmuxer.h>
@@ -65,14 +76,14 @@ namespace sd::dgl::ops {

     std::vector<uint8_t> encode_webm(const sd_tensor_t& frames, const VideoSaveOptions& options) {
 #ifndef SD_USE_WEBM
-        throw std::runtime_error("video::encode WebM requires a build with SD_WEBM=ON");
+        throw UnsupportedMedia("video::encode WebM requires a build with SD_WEBM=ON");
 #else
         using namespace media_encoding_detail;
+        if (options.audio.samples && options.audio.samples->bytes)
+            throw UnsupportedMedia("WebM audio encoding requires FFmpeg");
         validate_video_frames(frames);
         if (options.fps_num < 1 || options.fps_num > 1000000 || options.fps_den < 1 || options.fps_den > 1000000)
             throw std::runtime_error("WebM frame rate numerator and denominator must be in [1,1000000]");
-        if (options.audio.samples && options.audio.samples->bytes)
-            throw std::runtime_error("video::encode WebM does not support audio; use format=\"avi\" for PCM16 audio");
         MemoryWebMWriter writer;
         mkvmuxer::Segment segment;
         if (!segment.Init(&writer))
@@ -97,6 +108,7 @@ namespace sd::dgl::ops {
                 throw std::runtime_error("cannot write WebM generation metadata");
         }
         for (size_t frame = 0; frame < clock.count; ++frame) {
+            check_run_cancelled();
             auto packet = vp8_frame(video_frame_view(frames, frame), options.quality);
             if (!segment.AddFrame(packet.data(), packet.size(), track, uint64_t(clock.time_ns(frame)), true))
                 throw std::runtime_error("cannot mux WebM video frame");
@@ -108,4 +120,105 @@ namespace sd::dgl::ops {
         return writer.take_bytes();
 #endif
     }
+
+#ifdef SD_USE_WEBP
+    static std::vector<uint8_t> timed_webp(const WebPData& still, int width, int height, int duration) {
+        if (duration < 2)
+            throw std::runtime_error("cannot represent the animated WebP duration");
+        std::unique_ptr<WebPMux, decltype(&WebPMuxDelete)> mux(WebPMuxNew(), WebPMuxDelete);
+        WebPMuxAnimParams animation{};
+        if (!mux || WebPMuxSetCanvasSize(mux.get(), width, height) != WEBP_MUX_OK ||
+            WebPMuxSetAnimationParams(mux.get(), &animation) != WEBP_MUX_OK)
+            throw std::runtime_error("cannot initialize timed WebP");
+
+        // The muxer collapses a single full-canvas frame to a still image.
+        constexpr int max_frame_duration = (1 << 24) - 1;
+        WebPMuxFrameInfo frame{};
+        frame.bitstream    = still;
+        frame.id           = WEBP_CHUNK_ANMF;
+        frame.blend_method = WEBP_MUX_NO_BLEND;
+        frame.duration     = std::min(max_frame_duration, duration - 1);
+        do {
+            if (WebPMuxPushFrame(mux.get(), &frame, 0) != WEBP_MUX_OK)
+                throw std::runtime_error("cannot write a timed WebP frame");
+            duration -= frame.duration;
+            frame.duration = std::min(max_frame_duration, duration);
+        } while (duration > 0);
+
+        WebPData bytes{};
+        std::unique_ptr<WebPData, decltype(&WebPDataClear)> output(&bytes, WebPDataClear);
+        if (WebPMuxAssemble(mux.get(), &bytes) != WEBP_MUX_OK)
+            throw std::runtime_error("cannot assemble timed WebP");
+        return {bytes.bytes, bytes.bytes + bytes.size};
+    }
+#endif
+
+    std::vector<uint8_t> encode_animated_webp(const sd_tensor_t& frames, const VideoSaveOptions& options) {
+#ifdef SD_USE_WEBP
+        const auto& shape = frames.shape();
+        if (frames.type != SD_TENSOR_U8 || shape.size() != 4 || (shape[0] != 1 && shape[0] != 3 && shape[0] != 4) ||
+            shape[1] < 1 || shape[1] > WEBP_MAX_DIMENSION || shape[2] < 1 || shape[2] > WEBP_MAX_DIMENSION || shape[3] < 1 ||
+            options.fps_num < 1 || options.fps_den < 1)
+            throw std::runtime_error("animated WebP requires U8 [channels, width, height, frames] and a positive frame rate");
+        if (options.audio.samples && options.audio.samples->bytes)
+            throw UnsupportedMedia("animated WebP does not support audio");
+        const int channels = int(shape[0]), width = int(shape[1]), height = int(shape[2]);
+        const size_t stride = size_t(width) * channels, frame_size = stride * height;
+        const VideoSampling clock{{options.fps_num, options.fps_den}, size_t(shape[3])};
+        const auto timestamp = [&](size_t index) {
+            const auto time   = clock.time_ns(index);
+            const auto millis = time / 1000000 + (time % 1000000 >= 500000);
+            if (millis > std::numeric_limits<int>::max())
+                throw std::runtime_error("animated WebP duration exceeds limit");
+            return int(millis);
+        };
+        const int duration = timestamp(clock.count);
+        // With a sub-millisecond period, each rounded step is at most 1 ms.
+        if (size_t(duration) < clock.count)
+            throw std::runtime_error("animated WebP frame rate cannot be represented with millisecond timestamps");
+
+        WebPConfig config{};
+        if (!WebPConfigInit(&config))
+            throw std::runtime_error("cannot initialize WebP configuration");
+        config.quality      = float(options.quality);
+        config.thread_level = 1;
+        config.exact        = channels == 4;
+        std::unique_ptr<WebPAnimEncoder, decltype(&WebPAnimEncoderDelete)> encoder(WebPAnimEncoderNew(width, height, nullptr), WebPAnimEncoderDelete);
+        if (!encoder)
+            throw std::runtime_error("cannot create animated WebP encoder");
+        const auto* pixels = static_cast<const uint8_t*>(frames.data());
+        std::vector<uint8_t> rgb(channels == 1 ? frame_size * 3 : 0);
+        WebPPicture picture{};
+        if (!WebPPictureInit(&picture))
+            throw std::runtime_error("cannot initialize WebP frame");
+        std::unique_ptr<WebPPicture, decltype(&WebPPictureFree)> frame(&picture, WebPPictureFree);
+        picture.use_argb = 1;
+        picture.width    = width;
+        picture.height   = height;
+        for (size_t index = 0; index < clock.count; ++index) {
+            check_run_cancelled();
+            const auto* data = pixels + index * frame_size;
+            for (size_t i = 0; i < rgb.size(); ++i)
+                rgb[i] = data[i / 3];
+            const bool imported = channels == 4 ? WebPPictureImportRGBA(&picture, data, int(stride))
+                                                : WebPPictureImportRGB(&picture, rgb.empty() ? data : rgb.data(), width * 3);
+            if (!imported || !WebPAnimEncoderAdd(encoder.get(), &picture, timestamp(index), &config))
+                throw std::runtime_error("cannot encode animated WebP frame");
+        }
+        WebPData bytes{};
+        std::unique_ptr<WebPData, decltype(&WebPDataClear)> output(&bytes, WebPDataClear);
+        if (!WebPAnimEncoderAdd(encoder.get(), nullptr, duration, nullptr) ||
+            !WebPAnimEncoderAssemble(encoder.get(), &bytes))
+            throw std::runtime_error("cannot assemble animated WebP");
+        WebPBitstreamFeatures features{};
+        if (WebPGetFeatures(bytes.bytes, bytes.size, &features) != VP8_STATUS_OK)
+            throw std::runtime_error("invalid animated WebP output");
+        auto result = features.has_animation ? std::vector<uint8_t>(bytes.bytes, bytes.bytes + bytes.size)
+                                             : timed_webp(bytes, width, height, duration);
+        embed_webp_metadata(result, options.metadata);
+        return result;
+#else
+        throw UnsupportedMedia("animated WebP output requires a build with SD_WEBP=ON");
+#endif
+    }
 }
diff --git a/src/dgl/ops/video_webm.cpp b/src/dgl/ops/video_webm.cpp
index cf31446..22b1150 100644
--- a/src/dgl/ops/video_webm.cpp
+++ b/src/dgl/ops/video_webm.cpp
@@ -5,6 +5,7 @@
 #include <fstream>
 #include <limits>

+#include "dgl/ops/media_input.h"
 #include "dgl/ops/tensor.h"
 #include "dgl/ops/video_timing.h"

@@ -14,25 +15,19 @@

 namespace sd::dgl::ops {
     class WebMReader : public mkvparser::IMkvReader {
-        std::ifstream file_;
-        long long size_;
+        MediaInput& input_;

     public:
-        explicit WebMReader(const std::filesystem::path& path)
-            : file_(path, std::ios::binary | std::ios::ate) {
-            if (!file_ || file_.tellg() <= 0)
-                throw std::runtime_error("cannot read WebM input");
-            size_ = static_cast<long long>(file_.tellg());
-        }
+        explicit WebMReader(MediaInput& input)
+            : input_(input) {}
         int Read(long long position, long length, unsigned char* buffer) override {
-            if (position < 0 || length < 0 || position > size_ || length > size_ - position)
+            if (position < 0 || length < 0 || uint64_t(position) > input_.size() || uint64_t(length) > input_.size() - uint64_t(position))
                 return -1;
-            file_.clear();
-            file_.seekg(position);
-            return !length || file_.read(reinterpret_cast<char*>(buffer), length) ? 0 : -1;
+            input_.read(uint64_t(position), buffer, size_t(length));
+            return 0;
         }
         int Length(long long* total, long long* available) override {
-            *total = *available = size_;
+            *total = *available = static_cast<long long>(input_.size());
             return 0;
         }
         std::vector<uint8_t> packet(long long position, size_t length) {
@@ -50,8 +45,8 @@ namespace sd::dgl::ops {
         long size;
     };

-    VideoReadResult load_webm(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
-        WebMReader reader(path);
+    VideoReadResult decode_webm(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) {
+        WebMReader reader(input);
         mkvparser::EBMLHeader header;
         long long position = 0;
         if (header.Parse(&reader, position) || !header.m_docType ||
@@ -76,7 +71,7 @@ namespace sd::dgl::ops {
                 audio = static_cast<const mkvparser::AudioTrack*>(track);
         }
         if (!video || !video->GetCodecId() || std::strcmp(video->GetCodecId(), "V_VP8"))
-            throw std::runtime_error("WebM input supports independent VP8 keyframes only");
+            throw UnsupportedMedia("WebM input supports independent VP8 keyframes only");
         const auto width = video->GetWidth(), height = video->GetHeight();
         if (width < 1 || width > 16384 || height < 1 || height > 16384)
             throw std::runtime_error("invalid WebM video dimensions");
@@ -84,10 +79,11 @@ namespace sd::dgl::ops {
         int channels = 0, rate = 0;
         if (audio) {
             const auto sample_rate = audio->GetSamplingRate();
-            if (!audio->GetCodecId() || std::strcmp(audio->GetCodecId(), "A_PCM/INT/LIT") || audio->GetBitDepth() != 16 ||
-                audio->GetChannels() < 1 || audio->GetChannels() > 32 || !std::isfinite(sample_rate) ||
-                sample_rate < 1000 || sample_rate > 384000 || sample_rate != std::floor(sample_rate) || audio->GetCodecDelay())
-                throw std::runtime_error("WebM audio requires PCM16 without codec delay; use video::load(audio=false) to skip unsupported audio");
+            if (!audio->GetCodecId() || std::strcmp(audio->GetCodecId(), "A_PCM/INT/LIT") || audio->GetBitDepth() != 16 || audio->GetCodecDelay())
+                throw UnsupportedMedia("WebM audio requires PCM16 without codec delay; use video::load(audio=false) to skip unsupported audio");
+            if (audio->GetChannels() < 1 || audio->GetChannels() > 32 || !std::isfinite(sample_rate) ||
+                sample_rate < 1000 || sample_rate > 384000 || sample_rate != std::floor(sample_rate))
+                throw std::runtime_error("invalid WebM audio format");
             channels = int(audio->GetChannels());
             rate     = int(sample_rate);
         }
@@ -104,7 +100,7 @@ namespace sd::dgl::ops {
                 if (track == video->GetNumber() || (audio && track == audio->GetNumber())) {
                     const bool visual = track == video->GetNumber();
                     if (block->GetFrameCount() != 1 || (visual && (!block->IsKey() || block->IsInvisible())))
-                        throw std::runtime_error(visual ? "WebM input requires one independent VP8 keyframe per block" : "laced WebM audio is unsupported; use video::load(audio=false)");
+                        throw UnsupportedMedia(visual ? "WebM input requires one independent VP8 keyframe per block" : "laced WebM audio is unsupported; use video::load(audio=false)");
                     const auto& frame    = block->GetFrame(0);
                     const auto timestamp = block->GetTime(cluster);
                     if (frame.pos < 0 || frame.len <= 0 || timestamp < 0)
@@ -163,10 +159,12 @@ namespace sd::dgl::ops {
             }
             auto bytes       = reader.packet(frames[source].position, size_t(frames[source].size));
             int actual_width = 0, actual_height = 0;
-            if (bytes.size() < 10 || (bytes[0] & 1) || bytes[3] != 0x9d || bytes[4] != 0x01 || bytes[5] != 0x2a ||
+            if (!bytes.empty() && (bytes[0] & 1))
+                throw UnsupportedMedia("dependent VP8 frame in WebM input");
+            if (bytes.size() < 10 || bytes[3] != 0x9d || bytes[4] != 0x01 || bytes[5] != 0x2a ||
                 !WebPGetInfo(bytes.data(), bytes.size(), &actual_width, &actual_height) || actual_width != width || actual_height != height ||
                 !WebPDecodeRGBInto(bytes.data(), bytes.size(), destination, frame_bytes, int(width * 3)))
-                throw std::runtime_error("invalid or dependent VP8 frame in WebM input");
+                throw std::runtime_error("invalid VP8 frame in WebM input");
             previous = source;
         }
         if (audio && !packets.empty()) {
@@ -198,8 +196,8 @@ namespace sd::dgl::ops {
 }
 #else
 namespace sd::dgl::ops {
-    VideoReadResult load_webm(const std::filesystem::path&, size_t, int64_t, int64_t, bool) {
-        throw std::runtime_error("WebM video input requires a build with SD_WEBM=ON");
+    VideoReadResult decode_webm(MediaInput&, size_t, int64_t, int64_t, bool) {
+        throw UnsupportedMedia("WebM video input requires a build with SD_WEBM=ON");
     }
 }
 #endif
diff --git a/src/dgl/ops/video_webm.h b/src/dgl/ops/video_webm.h
index ed2863a..89bf51a 100644
--- a/src/dgl/ops/video_webm.h
+++ b/src/dgl/ops/video_webm.h
@@ -4,7 +4,7 @@
 #include "dgl/ops/video.h"

 namespace sd::dgl::ops {
-    VideoReadResult load_webm(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio);
+    VideoReadResult decode_webm(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio);
 }

 #endif  // __SD_DGL_OPS_VIDEO_WEBM_H__
diff --git a/src/dgl/ops/video_webp.cpp b/src/dgl/ops/video_webp.cpp
index aebbd77..89f2e45 100644
--- a/src/dgl/ops/video_webp.cpp
+++ b/src/dgl/ops/video_webp.cpp
@@ -4,6 +4,7 @@
 #include <fstream>
 #include <limits>

+#include "dgl/ops/media_input.h"
 #include "dgl/ops/tensor.h"
 #include "dgl/ops/video_timing.h"

@@ -11,17 +12,11 @@
 #include <webp/demux.h>

 namespace sd::dgl::ops {
-    VideoReadResult load_webp(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den) {
-        std::ifstream file(path, std::ios::binary | std::ios::ate);
-        if (!file || file.tellg() <= 0)
-            throw std::runtime_error("cannot read WebP input");
-        const auto length = uint64_t(file.tellg());
-        if (length > std::numeric_limits<size_t>::max() || length > uint64_t(std::numeric_limits<std::streamsize>::max()))
-            throw std::runtime_error("WebP input is too large");
-        std::vector<uint8_t> bytes(size_t(length), 0);
-        file.seekg(0);
-        if (!file.read(reinterpret_cast<char*>(bytes.data()), std::streamsize(bytes.size())))
-            throw std::runtime_error("truncated WebP input");
+    VideoReadResult decode_webp(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den) {
+        if (input.size() > media_decode_limit)
+            throw std::runtime_error("WebP input exceeds 256 MiB");
+        const auto file_bytes = input.bytes() ? std::vector<uint8_t>{} : input.read(0, size_t(input.size()));
+        const auto& bytes     = input.bytes() ? *input.bytes() : file_bytes;
         WebPBitstreamFeatures features{};
         if (WebPGetFeatures(bytes.data(), bytes.size(), &features) != VP8_STATUS_OK ||
             features.width < 1 || features.width > 16384 || features.height < 1 || features.height > 16384)
@@ -90,8 +85,8 @@ namespace sd::dgl::ops {
 }
 #else
 namespace sd::dgl::ops {
-    VideoReadResult load_webp(const std::filesystem::path&, size_t, int64_t, int64_t) {
-        throw std::runtime_error("WebP video input requires a build with SD_WEBP=ON");
+    VideoReadResult decode_webp(MediaInput&, size_t, int64_t, int64_t) {
+        throw UnsupportedMedia("WebP video input requires a build with SD_WEBP=ON");
     }
 }
 #endif
diff --git a/src/dgl/ops/video_webp.h b/src/dgl/ops/video_webp.h
index 5eb6d35..0a4ccd8 100644
--- a/src/dgl/ops/video_webp.h
+++ b/src/dgl/ops/video_webp.h
@@ -4,7 +4,7 @@
 #include "dgl/ops/video.h"

 namespace sd::dgl::ops {
-    VideoReadResult load_webp(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den);
+    VideoReadResult decode_webp(MediaInput& input, size_t max_frames, int64_t fps_num, int64_t fps_den);
 }

 #endif  // __SD_DGL_OPS_VIDEO_WEBP_H__
diff --git a/src/dgl/tensor_io.cpp b/src/dgl/tensor_io.cpp
index afe6f7b..c867bd9 100644
--- a/src/dgl/tensor_io.cpp
+++ b/src/dgl/tensor_io.cpp
@@ -1,10 +1,9 @@
 #include "tensor_io.h"

-#include <atomic>
-#include <chrono>
 #include <filesystem>

 #include "core/file_access.h"
+#include "core/temporary_output.h"
 #include "model_io/npy_io.h"

 namespace sd::dgl {
@@ -17,39 +16,12 @@ namespace sd::dgl {
         return tensor;
     }

-    class TemporaryNpyFile {
-        std::filesystem::path directory_;
-        std::filesystem::path path_;
-
-    public:
-        explicit TemporaryNpyFile(const std::filesystem::path& parent) {
-            static std::atomic<uint64_t> sequence{0};
-            const auto timestamp = std::chrono::steady_clock::now().time_since_epoch().count();
-            const auto prefix    = ".dgl-tensor-" + std::to_string(timestamp) + "-";
-            do {
-                directory_ = parent / (prefix + std::to_string(sequence.fetch_add(1, std::memory_order_relaxed)));
-                path_      = directory_ / "tensor.npy";
-            } while (!std::filesystem::create_directory(directory_));
-        }
-
-        TemporaryNpyFile(const TemporaryNpyFile&)            = delete;
-        TemporaryNpyFile& operator=(const TemporaryNpyFile&) = delete;
-
-        const std::filesystem::path& path() const { return path_; }
-
-        ~TemporaryNpyFile() {
-            std::error_code ignored;
-            std::filesystem::remove(path_, ignored);
-            std::filesystem::remove(directory_, ignored);
-        }
-    };
-
     void save_npy_atomic(const sd_tensor_t& tensor, const std::string& path) {
         if (path.empty())
             throw std::runtime_error("tensor output path is required");
         require_file_access(path, SD_DGL_FILE_WRITE);
         const auto destination = std::filesystem::u8path(path);
-        const TemporaryNpyFile temporary(destination.parent_path());
+        const TemporaryOutput temporary(destination, ".dgl-tensor-");
         npy::write(temporary.path(), tensor.type, tensor.shape(), tensor.data(), tensor.bytes);
         std::filesystem::rename(temporary.path(), destination);
     }