Configure libdav1d Max Decoding Threads

This article explains how to configure the maximum number of decoding threads in the libdav1d AV1 decoder. You will learn about the distinct threading models used by libdav1d, the specific settings structure parameters required to limit CPU usage, and how to apply these configurations in your C/C++ application.

Understanding libdav1d Threading Parameters

The libdav1d library utilizes two complementary threading models to decode AV1 video streams efficiently: frame threading and tile threading.

The total maximum number of threads spawned by libdav1d is generally the product of these two values (n_frame_threads * n_tile_threads).

Configuring Threads in Code

To set the maximum decoding threads, you must populate the Dav1dSettings structure before initializing the decoder context.

Step-by-Step Implementation

  1. Initialize default settings: Always use dav1d_default_settings() to populate the settings structure with safe, standard defaults.
  2. Assign thread counts: Modify the n_frame_threads and n_tile_threads members to your desired limits.
  3. Initialize the context: Pass the settings structure to dav1d_open().

Code Example

#include <stdio.h>
#include <dav1d/dav1d.h>

int main() {
    Dav1dContext *context = NULL;
    Dav1dSettings settings;

    // 1. Initialize settings with default values
    dav1d_default_settings(&settings);

    // 2. Configure the maximum decoding threads
    // Limit to 4 frame threads and 2 tile threads (Max 8 threads total)
    settings.n_frame_threads = 4;
    settings.n_tile_threads = 2;

    // 3. Open the decoder context with the configured settings
    int result = dav1d_open(&context, &settings);
    if (result < 0) {
        fprintf(stderr, "Failed to open libdav1d context: %d\n", result);
        return 1;
    }

    printf("libdav1d successfully configured with %d frame threads and %d tile threads.\n",
           settings.n_frame_threads, settings.n_tile_threads);

    // Clean up
    dav1d_close(&context);
    return 0;
}

Best Practices for Thread Allocation