Skip to content

libvips (C) ​

A demand-driven, horizontally threaded image-processing library in C over GObject: partial images form a lazy graph, and sinks pull pixels through it in regions. Streaming pipelines avoid full intermediates, but memory also depends on image width, codec behaviour and operations that require the whole image.

FieldValue
LanguageC (gnu11), with C++ for the Highway SIMD kernels and the cplusplus/ binding
LicenseLGPL-2.1-or-later (LICENSE, README.md)
Repositorylibvips/libvips
Revision readb8242162f09585ce5b4029cdb7fe95de186dde1a (meson.build version 8.19.0, "Merge branch '8.18'")
Documentationlibvips.org/API/current; the doc/ tree, in particular how-it-works.md
CategoryGeneric libraries
TierA
Last reviewedNovember 15, 2026

NOTE

libvips supplies the survey's run-time pull pipeline: C callbacks fill rectangles, with per-operation geometry hints. Halide instead separates algorithm and schedule before compilation. Behaviour marked verified below was independently rerun on November 15, 2026 against the pinned 8.19.0 source, built with nixpkgs packaging and dependencies. Memory figures describe that build and machine, not portable bounds.


Overview ​

What it solves ​

Image-server and slide-scanner pipelines can exceed RAM if every intermediate is materialised. libvips keeps regions instead (how-it-works.md):

"Compared to most image processing libraries, libvips needs little RAM and runs quickly, especially on machines with more than one CPU. libvips achieves this improvement by only keeping the pixels currently being processed in RAM and by having an efficient, threaded image IO system."

It supports about 300 operations, ten numeric band formats from 8-bit integer to 128-bit complex, arbitrary band counts within dimension limits, many codecs and ImageMagick as a fallback (README.md).

Design philosophy ​

  1. An image can be a function. A partial image stores "a function which can make any rectangular area of pixels on demand" (how-it-works.md).
  2. Non-mutating operations can be cached. Operations normally create new images; mutating draw operations emit invalidate to flush downstream caches (how-it-works.md, how-it-works.md).
  3. Sequence setup separates state from computation. "Start and stop functions are mutually exclusive and a state is never used by more than one generate." (how-it-works.md). This does not prohibit allocation or locking inside generate callbacks.

Images are "uninterpreted arrays": callers must supply the appropriate colour interpretation for each operation (image.c).


How it works ​

VipsImage: a descriptor that may have no pixels ​

struct _VipsImage holds int width, height and bands, VipsBandFormat, VipsCoding, an advisory VipsInterpretation, resolution and GValue metadata (image.h). VipsImageType distinguishes owned memory, caller-owned memory, file windows, mapped files, output files and partial images (image.h). A partial image stores start_fn, generate_fn, stop_fn, two client pointers, the start/stop mutex and a demand hint (image.h). Start returns per-sequence state; generate receives that state and an output region; stop frees it (image.h).

VipsRegion: a strided window with an origin ​

A region holds its image, a VipsRect valid in that image's coordinates, a data pointer and bpl (bytes per line) (region.h). Its backing may be a buffer, borrowed image/region memory or a file window (private.h). VIPS_REGION_ADDR offsets from valid.left and valid.top using line stride and pixel size; only -DDEBUG adds bounds checks and abort() (region.h). extract_area remaps coordinates and aliases input memory (extract.c). Bands remain interleaved (stride; layouts).

vips_region_prepare(reg, r) makes the intersection with the image addressable (region.c). Partial images fill a buffer unless already done; memory/mapped images borrow existing bytes (region.c). Worker-local VipsBufferCache entries can reuse finished buffers. Buffers "can move between caches and between threads, but not between images" (private.h); non-libvips threads do not receive this cache (buffer.c).

Writing an operation ​

The negative example's build validates inputs, creates the output, declares VIPS_DEMAND_STYLE_THINSTRIP with vips_image_pipelinev, then attaches callbacks with vips_image_generate (extending.md). Its generate callback prepares the input rectangle and fills out->valid; vips_start_one and vips_stop_one create and free an input region per sequence. gboolean *stop supports early termination (extending.md). Area operations enlarge the input rectangle; transforms remap it; vips_region_region aliases existing pixels (extending.md). vips_image_generate checks that the demand hint was set, stores callbacks for PARTIAL, and evaluates memory/file outputs immediately with vips_sink_memory or vips_sink_disc (generate.c).

Sequences and the start/stop lock ​

vips__region_start takes image->sslock, calls start_fn and stores the result in region->seq; vips__region_stop takes the same lock to call stop_fn (region.c). This serialises start and stop callbacks on the same image; it does not lock generate calls or shared state passed through a and b. Each sequence is used by only one generate at a time. Regions are bound to their creating thread; using-threads.md warns that "to reduce locking, [class@Region] keeps a lot of state in per-thread storage", and moving one needs vips__region_no_ownership() and vips__region_take_ownership().

Demand hints ​

The preference enum orders SMALLTILE, FATSTRIP, THINSTRIP, ANY (image.h; image.c). vips__demand_hint_array folds the numeric minimum over the operation and its inputs, then records invalidation links (generate.c):

c
set_hint = hint;
for (i = 0, len = 0; in[i]; i++, len++)
    set_hint = (VipsDemandStyle)
        VIPS_MIN((int) set_hint, (int) in[i]->dhint);
image->dhint = set_hint;

vips_get_tile_size maps SMALLTILE to 128 by 128; FATSTRIP and ANY to full-width, 16-line strips; THINSTRIP uses one line only above width 10000. Buffer height derives from concurrency and rounds to tile height, independently of image dimensions (thread.c; private.h).

Verified and independently rerun on pinned 8.19.0, concurrency 32: 1000 by 1000, three-band black reports any, invert thinstrip, gaussblur (sigma 1.5, default integer precision) and rotate (45 degrees) smalltile. The latter two use 128 by 128 tiles and n_lines=640. At the pinned revision the blur chain is gaussblur → convsep → two conv calls → convi, which requests SMALLTILE (gaussblur.c; convsep.c; conv.c; convi.c). The documented FATSTRIP example for conv therefore differs from its integer path. Hints do not constrain request sizes (extending.md).

Sinks and the threadpool ​

"In a demand-driven system, something has to do the demanding" (how-it-works.md). The sinks are vips_sink_disc (stream to a file), vips_sink_memory, vips_sink (loop over an image for statistics), vips_sink_tile and vips_sink_screen (libvips-generate.md). All run on vips_threadpool_run (threadpool.c), which takes four callbacks: start (per-thread state, a VipsThreadState subclass holding a region), allocate (pick the next work unit, run under allocate_lock, "always single-threaded"), work (fill the tile, many at once) and progress. The pool starts at 1 + max_workers / 2 workers and adapts to instrumented mutex and condition waits, including loader/cache waits (n_waiting > 3 shrinks, < 2 grows; threadpool.c, wait accounting).

The disc sink double-buffers (sinkdisc.c): Write holds buf, being filled by workers tile by tile, and buf_back, held by a background thread that writes complete scanlines through the format library when the last tile of the buffer lands (how-it-works.md). The display sink, vips_sink_screen, renders in the background into a tile cache, returns immediately from vips_region_prepare with "whatever is currently in cache", exposes a one-band mask of valid pixels, and calls a notify_fn from a worker when new tiles land. With a NULL callback it runs synchronously instead (sinkscreen.c).

Verifier measurement on pinned 8.19.0 (x86_64, 32 hardware threads, getrusage peak RSS in fresh children): a 40000 by 40000 three-band uchar virtual image (4.8 GB uncompressed; black, linear1 with scale 1, offset 128 and uchar=TRUE, gaussblur sigma 1.5) streamed to JPEG peaked at 50.4 MiB with VIPS_CONCURRENCY=1, 53.7 MiB with 4 and 215.0–216.8 MiB in two runs with 32; pre-write peaks were about 18 MiB. A 40000 by 10000 run at concurrency 1 peaked at 50.2 MiB. This supports streaming with a working set insensitive to height for this pipeline, not a bound independent of dimensions: the disc sink buffers full-width strips. RSS varies; these are measurements, not memory bounds.

Operations, introspection and the cache ​

Operations subclass VipsOperation (operation.h). VIPS_ARG_* declarations record names, priorities, descriptions, flags, offsets and numeric limits for the CLI and bindings (extending.md; how-it-works.md). C varargs calls have "almost no compile-time type checking"; wrappers add typed required arguments (extending.md).

vips_cache_operation_buildp reuses matching operations. Its hash covers type and assigned, hashable construction inputs, excluding VIPS_ARGUMENT_NON_HASHABLE (cache.c, cache.c). Defaults are 100 operations, 100 tracked open files and 100 MiB tracked memory (cache.c). Flags include NOCACHE, REVALIDATE, SEQUENTIAL, DEPRECATED, UNTRUSTED, BLOCKED (operation.h).

Loaders, savers and sources ​

VipsForeignLoad subclasses declare sniffers, flags, header and optional load methods (foreign.h). With a separate load, the framework defers that method to first pixel demand (foreign.c) and selects backing through vips_foreign_load_temp (foreign.c):

ConditionBacking
memory forcedvips_image_new_memory()
loader flags VIPS_FOREIGN_PARTIAL (tiled TIFF, OpenEXR, …)vips_image_new(): lazy, random access
VIPS_FOREIGN_SEQUENTIAL and access is not RANDOMvips_image_new(): lazy, top to bottom
decoded size above vips_get_disc_threshold()vips_image_new_temp_file("%s.v")
otherwisememory buffer

vips_foreign_load_iscompat rejects differences in size, bands, format or coding between header and load (foreign.c). Verifier measurement on pinned 8.19.0, concurrency 1: opening a black 12000 by 12000 one-band PNG sequentially peaked at 18.4 MiB; vips_avg raised it to 24.4 MiB for 144 MB decoded pixels. These are pipeline measurements, not fixed requirements.

Sequential mode adds a small line cache (open strategies, sequential access). vips_sequential locks requests and reads skipped lines into cache (sequential.c); sequential loaders in this mode are nocache (foreign.c). Savers declare accepted colour/band models and metadata retention through VipsForeignSaveable and VipsForeignKeep (foreign.h). VipsSource/VipsTarget abstract byte I/O; unseekable input is buffered for header replay (source.c), with pipe-to-memory reads capped at 1 GiB by default (source.c).


Analysis ​

1. Pixel and memory model ​

Width, height and bands are positive ints, with interleaved bands and one of ten native C band formats per image (how-it-works.md; image.c). There is no planar, subsampled or fourth-axis storage; multipage images use a tall strip. One-bit TIFF samples expand to uchar (tiff2vips.c). LABQ packs Lab into four bytes; RAD stores Radiance RGBE (image.c).

Regions have line stride but no independent band or element stride. VIPS_DEFAULT_MAX_COORD supplies a configurable 100-million limit (image.h); vips_image_sanity checks dimensions, multiplication overflow and scanline bytes below INT_MAX (image.c). Byte sizes use size_t/guint64. Evaluation tiles need not match storage tiles in tiled TIFF/OpenEXR (tiling).

2. Genericity mechanism ​

Operation dispatch is GObject classes, properties, argument introspection and nickname. Element dispatch is usually a BandFmt switch with per-type C macros. add also keeps a ten-entry promotion table whose comment requires it to match the switch (add.c, add.c). Format/coding checks happen in build (extending.md). Unlike Boost.GIL, this does not encode pixel types or colour interpretation in the language's type system; compare generic image programming.

3. Colour and metadata ​

VipsInterpretation carries an advisory colour tag (image.h); there are no independent transfer-function, primaries or alpha-mode fields. "RGB and sRGB are treated in the same way" (image.c). Alpha is a trailing band; 2-by-2 region shrinking scales pixels by alpha to avoid fringing (region.h).

Little CMS 2 handles ICC. vips_icc_build shares a transform with cmsFLAGS_NOCACHE to disable its one-pixel cache for thread safety (icc_transform.c). The profile is an icc-profile-data blob; libvips's PCS is Lab D65 or XYZ (icc_transform.c). CICP travels as metadata; CICP2scRGB applies a transfer LUT and primaries matrix to tagged RGB (CICP2scRGB.c). Its matrix-coefficient and full-range fields are unused, so this is not general YCbCr matrix/range conversion (CICP2scRGB.c). UltraHDR uses libultrahdr as SDR plus gain-map metadata or full HDR scRGB (uhdr.md). EXIF, XMP, IPTC, Photoshop and orientation metadata travel separately (header.h). See ICC, CICP, gain maps and the colour papers.

4. I/O and codec architecture ​

Pulling rectangles is incremental where the wrapped codec permits it: sequential JPEG/PNG can stream, tiled TIFF/OpenEXR allow random access, and other paths decode the whole image to memory or a temporary .v file (open strategies, sequential access). vips_region_prepare blocks its calling thread; libvips adds no suspend/resume protocol (region.c). VipsSource wraps file, memory or custom read/seek callbacks; unseekable replay buffering ends after the header phase (source.c).

The .v spill format has a 64-byte header, contiguous pixels and an XML metadata extension; rolling mapped windows let it exceed RAM (how-it-works.md). Spilling supplies random access at the cost of full decoding and temporary storage. See pull decoding and incremental decoding.

5. Hostile input and safety ​

  • Trust policy. UNTRUSTED marks operations not hardened for hostile input (operation.c). vips_block_untrusted_set(TRUE) sets BLOCKED on them (init.c); VIPS_BLOCK_UNTRUSTED applies this at init (init.c). Subtree blocking can disable VipsForeignLoad then re-enable JPEG (operation.c). Blocked operations fail (operation.c); blocked loaders are excluded before sniffing (foreign.c). A pinned-tree search finds 26 loader/saver files setting UNTRUSTED; foreign.c only prints it. The security policy excludes reports against these loaders (SECURITY.md).
  • Strictness. VipsFailOn orders NONE, TRUNCATED, ERROR, WARNING; each includes earlier levels (foreign.h). Default NONE permits decoder recovery but does not guarantee truncated inputs load.
  • Limits. Loader-specific limits include PNG text-chunk handling and failure at 100 JPEG warnings (vipspng.c; jpeg2vips.c). unlimited defaults to vips_unlimited_get(); fuzz builds remove that argument and make vips_unlimited_set a no-op (jpegload.c; init.c).
  • Geometry. Sanity checks reject invalid dimensions/enums; header/load checks reject inconsistent dimensions, coding and format (image.c; foreign.c). Pixel access remains unchecked without DEBUG.

Verified and independently rerun on pinned 8.19.0: VIPS_BLOCK_UNTRUSTED=1 prevents loading a 64 by 64 PPM (unknown format), while PNG loads; PPM loads without it. vips -l lists 68 untrusted classes in this build, dependent on enabled codecs. See hostile input and the safety papers.

6. Allocation and ownership ​

GObjects are reference counted; regions retain their image and release attached buffers (region.c). Region buffers use vips_tracked_aligned_alloc (buffer.c); codec allocations need not be tracked. Each worker's per-image cache reserves up to two spare buffers (buffer.c). Allocation reuse is a design goal, not a guarantee for every callback (how-it-works.md).

vips_region_region aliases memory, as in the loader's copy (foreign.c). VIPS_IMAGE_SETBUF_FOREIGN leaves caller memory unfreed (image.h). Errors return -1/NULL with messages in a process-wide buffer; a thread cannot reliably associate its error return with one message (using-threads.md).

7. CPU parallelism and SIMD ​

Workers run private pipeline state on their tiles. The documentation claims "four lock operations per output tile, regardless of the pipeline length or complexity" (how-it-works.md); sequential loaders add their own locking. Concurrency defaults to hardware threads, clipped to 1..1024; Apple Silicon prefers performance cores when discoverable. API, CLI and VIPS_CONCURRENCY override it (thread.c). Threadpool pre-creation is supported for wasm (threadpool.c).

SIMD uses Highway dynamic dispatch; vector helpers select Orc when Highway is absent (vector.cpp). Kernel files re-include themselves through foreach_target.h, use ScalableTag and export HWY_DYNAMIC_DISPATCH wrappers (shrinkv_hwy.cpp, shrinkv_hwy.cpp). The shrink kernel has scalar tails and SVE/RVV demotion workarounds (shrinkv_hwy.cpp). Its vector path is selected in build for uchar when vips_vector_isenabled(); other formats use the C loop (shrinkv.c). Six kernel files cover convi, morph, reduceh, reducev, shrinkh and shrinkv. vips_vector_get_supported_targets excludes HWY_EMU128 and HWY_SCALAR; VIPS_VECTOR disables selected targets for testing (vector.cpp). composite.cpp separately uses GCC vector arithmetic for RGBA uchar, ushort and float (composite.cpp). The documented SIMD speedup of three or four is not measured here (how-it-works.md).

8. GPU offload and interop ​

Not applicable: there is no GPU code path at this revision. A search of libvips/, doc/ and the build files for OpenCL, CUDA, Vulkan or GPU finds one comment in nohalo.cpp referring to a paper title. The evaluation model assumes host memory: a generate function fills a host buffer synchronously, one tile at a time, and nothing in the tree addresses batching tiles for a device or measures a break-even. The display sink's tile cache and notify_fn are the nearest thing to an interop seam: an application uploads tiles as they become ready.

9. Temporal, animation and containers ​

Animation and multipage are "tall, thin strips of frames, like a strip of movie film" (multipage-and-animated-images.md): page-height, n-pages, loop and a delay array in milliseconds are metadata; n=-1 loads all frames and page selects one. GIF, WebP and JPEG XL animate; APNG needs APNG-capable libpng (PNG support); TIFF, PDF, HEIC, AVIF and .v are multipage. Ordinary pixel operations see the strip; vertical filtering must handle frame boundaries explicitly. One strip requires equal page sizes; unequal PDF/TIFF pages load individually. There is no standard per-frame timestamp, public disposal state or video-frame abstraction (multipage documentation; video.h).

10. Testing and conformance ​

Two layers (test/README.md): shell scripts under meson test (threading, sequential access, stall, timeouts for GIF and WebP savers, CLI) and a pytest suite over pyvips with 94 sample files under test/test-suite/images. The arithmetic oracle is pixel-against-scalar: run_cmp reads one pixel, applies the Python function to the number and to the image, and compares with pytest.approx(..., abs=0.0001) (helpers.py), across all ten formats (test_arithmetic.py). Codec tests save, reload and assert a maximum absolute difference, 0 for lossless formats and a per-test bound for lossy ones (save_load_file and friends, test_foreign.py); there is no external conformance corpus pinned in the tree.

Fuzzing runs on OSS-Fuzz (README.md badge, oss_fuzz_build.sh). generic_buffer_fuzzer.cc opens arbitrary bytes with vips_image_new_from_buffer, rejects width/height above 100 or bands above 4, then saves at concurrency 1 to the format selected by SAVE_SUFFIX. Separate targets select JPEG, PNG, TIFF and other savers (generic_buffer_fuzzer.cc, fuzz/meson.build); further targets cover thumbnail, sharpen, smartcrop, mosaic and a JPEG save. Fuzz builds compile out unlimited and the system operation (init.c).


Lessons for Sparkles ​

  • Q3 — Type the sequence contract. Worker-owned state can replace void *seq, with optional start/stop hooks. Shared callback data and region thread affinity still need explicit rules (thread rules; baseline G7).
  • Q1 — Use regions as a view model. Pointer, stride and owning-image rectangle support crops and aliases. A checked @safe view needs more than one preparation check to justify inner-loop access (baseline G2; mir; Halide).
  • Q3 — Demand hints are a coarse schedule. D could fold an enum over stage types without an IR; default integer gaussblur shows one stage changing sink geometry (scheduling; DSL synthesis).
  • Q6, Q7 — Budget concurrency and buffering together. The 4.8 GB pipeline peaked at 50.4 MiB on one thread and 215.0–216.8 MiB on 32. Full-width buffers couple memory to width and concurrency (event-horizon baseline).
  • Q4 — Separate header and pixel phases, then re-check geometry. Two D operations can return Expected; resumability still needs storage or re-decoding for arbitrary access (incremental decoding; baseline G1/G7; wired).
  • Q4, Q8 — Filter probes by codec trust. Codec UDAs or enums can feed a probe registry. Subtree blocking and ordered fail levels separate deployment trust from strictness (baseline G1/G11).
  • Q8 — Keep limits active in fuzz builds. Removing unlimited tests the production limits. Arbitrary bytes, size rejection and re-encoding supply a first harness (baseline G11; safety synthesis).
  • Q2 — Derive dynamic and typed interfaces together. Argument UDAs could feed sparkles:core-cli and typed calls; element templates can replace the hand-kept format switch/promotion table (generic programming; SIMD baseline).
  • Q3, Q7 — Expose SIMD selection for testing. Highway's scalable kernels extend the per-@target pattern; capability probes and target masks are useful controls. Its six kernels do not cover all libvips SIMD (compositor; SIMD baseline).
  • Q5 — Blobs do not replace typed colour contracts. Interpretation, ICC, CICP and gain maps support conversion without an alpha-mode type. lcms sharing requires cache discipline (baseline G3/G4/G5; color).
  • Q6 — Display sinks can expose tiles and validity. A completion could carry vips_sink_screen-style tile notifications to a viewer (image consumers; Vulkan).
  • Q9 — Scheduling suggests a package seam. libvips integrates engine and codecs with global state; it does not demonstrate an independent engine package. Global state alone does not exclude wasm (threadpool; baseline question 6).

Strengths ​

  • Streaming avoids full intermediates for suitable pipelines; a 4.8 GB image streamed in 50.4 MiB on one thread in the verifier run, with width-dependent buffers.
  • Region chaining needs no compiler: links are function calls, and small intermediates can fit in cache (how-it-works.md).
  • Sequence-local state reduces shared mutable state; loaders can still add locks.
  • Operation cache and invalidation follow from side-effect freedom; run-time introspection yields a uniform CLI and dynamic bindings.
  • Explicit hostile-input policy: untrusted tagging, subtree blocking, fail levels, DoS limits that fuzz builds cannot disable, OSS-Fuzz coverage.
  • Highway kernels cover x86, Arm (including SVE) and RISC-V from one source.
  • Breadth: ten numeric formats including complex, many bands, about 300 operations and a wide set of formats.

Weaknesses ​

  • No type safety for pixels or colour: an RGB image passed to Lab2XYZ "you'll just get nonsense" (image.c); format/promotion invariants are kept by comments.
  • int coordinates; unchecked pixel addressing in release builds; a global error buffer that cannot be matched to the failing call; implicit region thread affinity.
  • Demand hints are coarse and can be dominated by one stage; documentation and code disagree on conv.
  • Random access to a sequential codec requires full decode to memory or a temporary file; sequential pipelines can instead stream.
  • Interleaved bands only; no planar, subsampled or N-D storage; animation as a strip with no timestamps.
  • Highway acceleration covers six kernels for uchar; it is not the only SIMD path.
  • No GPU path; deep GLib/GObject dependency rules out freestanding builds.

Key design decisions and trade-offs ​

DecisionRationaleTrade-off
Partial images: a function from rectangle to pixelsStreaming can avoid full intermediates; separate header/load methods defer decodingWhole-image algorithms (FFT, flood fill) need wio_input; memory images also permit direct access
Start/generate/stop with a per-image start/stop lockSerial setup/teardown and private sequence state reduce lockingShared callback data needs its own discipline; regions need explicit thread handover
Demand hint, folded by minimumA schedule with one parameter, chosen at run time, no compilerOne SMALLTILE stage can dominate sink geometry
Double-buffered disc sink, full-width stripsWriters that need scanlines get them while workers fill the next bufferBuffer memory scales with image width times threads
Side-effect-free operations with a hash-keyed cacheReuse across calls and threads; cheap repeated thumbnailsStale results for replaced files (revalidate needed); mutation needs an invalidate signal
GObject classes and run-time argument introspectionOne declaration feeds the CLI, vips_call and dynamic bindingsLittle compile-time checking; varargs wrappers per operation
Band format as a run-time tag with per-format macro loopsTen formats from one source file per operationHand-kept promotion tables; Highway kernels specialise uchar
Untrusted flag plus block list, filtered at sniffingApplications choose a hardened subset without rebuildingSafety is a deployment setting; the default leaves untrusted loaders enabled
Spill non-random-access decodes to memory or a temp .v fileAny codec can feed a random-access pipelineDisc traffic and latency for large JPEG/PNG used out of order
Highway dynamic dispatch, scalar fallbackOne source per kernel across x86, Arm and RISC-VC++ in a C library; only a few kernels vectorised

Sources ​