AVC / H.264 Annex B Encoder (Run)

This article explains how you can use TTranscoder::run to encode a raw YUV video file to AVC / H.264 Annex B elementary stream format.

The code snippets in this article are from the enc_avc_file macOS sample.

Source Video

For source we use the foreman_qcif.yuv file from the AVBlocks Assets repository. After downloading and unzipping you will find foreman_qcif.yuv in the vid subdirectory.

Code

This code takes a raw YUV video file and encodes it to compressed H.264 Annex B format.

Initialize AVBlocks

The first step in any AVBlocks application is to initialize the library. This must be done before using any other AVBlocks functionality. The TLibrary constructor initializes the library and loads the necessary codecs. The TLibrary destructor shuts the library down and releases any allocated memory, so the library is terminated when the TLibrary object goes out of scope at the end of main.

int main(int argc, char* argv[])
{
    Options opt;
    switch(prepareOptions(opt, argc, argv))
    {
        case Command: return 0;
        case Error:   return 1;
        case Parsed:  break;
    }

    TLibrary library;
    return encode(opt) ? 0 : 1;
}

Configure Input Socket

The input socket defines the source raw YUV video data. We need to specify the video parameters including frame dimensions, frame rate, color format, and scan type. These parameters must match the actual properties of the input YUV file. In this example, we’re reading QCIF resolution (176x144) YUV 4:2:0 progressive video at 30 frames per second.

TMediaSocket()
    .file(opt.yuv_file)
    .streamType(StreamType::UncompressedVideo)
    .addPin(
        TMediaPin()
            .streamInfo(TVideoStreamInfo()
                .streamType(StreamType::UncompressedVideo)
                .frameWidth(opt.frame_size.width_)
                .frameHeight(opt.frame_size.height_)
                .colorFormat(opt.yuv_color.Id)
                .frameRate(opt.fps)
                .scanType(ScanType::Progressive)
            )
    )

Configure Output Socket

The output socket defines where and how the encoded H.264 video data will be written. We configure it to output an H.264 Annex B elementary stream file. The socket represents the output destination, while the pin represents the specific video stream within that destination. By setting StreamSubType::AVC_Annex_B, we ensure the output uses the Annex B format with start codes, which is suitable for elementary streams and broadcasting applications.

TMediaSocket()
    .file(opt.h264_file)
    .streamType(StreamType::H264)
    .addPin(
        TMediaPin()
            .streamInfo(TVideoStreamInfo()
                .streamType(StreamType::H264)
                .streamSubType(StreamSubType::AVC_Annex_B)
            )
    )

Configure Transcoder and Encode

This is the main encoding function that ties everything together. First, we create an input socket that points to the YUV file we want to encode. Then we create the output socket. The transcoder is the core component that performs the actual encoding - it takes the uncompressed YUV data from the input and converts it to compressed H.264 data for the output.

The allowDemoMode(true) call allows the transcoder to work even without a valid license (useful for testing, but not recommended for production). We then add our input and output sockets to the transcoder, open it to prepare for processing, run the actual transcoding operation, and finally close it to clean up.

bool encode(const Options& opt)
{
    try {
        deleteFile(opt.h264_file.c_str());

        TTranscoder()
            .allowDemoMode(true)
            .addInput(
                TMediaSocket()
                    .file(opt.yuv_file)
                    .streamType(StreamType::UncompressedVideo)
                    .addPin(
                        TMediaPin()
                            .streamInfo(TVideoStreamInfo()
                                .streamType(StreamType::UncompressedVideo)
                                .frameWidth(opt.frame_size.width_)
                                .frameHeight(opt.frame_size.height_)
                                .colorFormat(opt.yuv_color.Id)
                                .frameRate(opt.fps)
                                .scanType(ScanType::Progressive)
                            )
                    )
            )
            .addOutput(
                TMediaSocket()
                    .file(opt.h264_file)
                    .streamType(StreamType::H264)
                    .addPin(
                        TMediaPin()
                            .streamInfo(TVideoStreamInfo()
                                .streamType(StreamType::H264)
                                .streamSubType(StreamSubType::AVC_Annex_B)
                            )
                    )
            )
            .open()
            .run()
            .close();

        std::println("Output: {}", opt.h264_file);
        return true;

    } catch (const TAVBlocksException& ex) {
        std::println(stderr, "AVBlocks error: {}", ex.what());
        return false;
    } catch (const std::exception& ex) {
        std::println(stderr, "Error: {}", ex.what());
        return false;
    }
}

Complete C++ Code

Here’s the complete working example that demonstrates H.264 encoding using AVBlocks. This code combines all the previous snippets into a functional program that can be compiled and run. The main function handles command-line argument parsing, initializes AVBlocks, performs the encoding operation, and properly shuts down the library before exiting.

#include <primo/avblocks/avb++.h>

#include <print>

#include "options.h"
#include "util.h"

using namespace primo::codecs;
using namespace primo::avblocks::modern;

bool encode(const Options& opt)
{
    try {
        deleteFile(opt.h264_file.c_str());

        TTranscoder()
            .allowDemoMode(true)
            .addInput(
                TMediaSocket()
                    .file(opt.yuv_file)
                    .streamType(StreamType::UncompressedVideo)
                    .addPin(
                        TMediaPin()
                            .streamInfo(TVideoStreamInfo()
                                .streamType(StreamType::UncompressedVideo)
                                .frameWidth(opt.frame_size.width_)
                                .frameHeight(opt.frame_size.height_)
                                .colorFormat(opt.yuv_color.Id)
                                .frameRate(opt.fps)
                                .scanType(ScanType::Progressive)
                            )
                    )
            )
            .addOutput(
                TMediaSocket()
                    .file(opt.h264_file)
                    .streamType(StreamType::H264)
                    .addPin(
                        TMediaPin()
                            .streamInfo(TVideoStreamInfo()
                                .streamType(StreamType::H264)
                                .streamSubType(StreamSubType::AVC_Annex_B)
                            )
                    )
            )
            .open()
            .run()
            .close();

        std::println("Output: {}", opt.h264_file);
        return true;

    } catch (const TAVBlocksException& ex) {
        std::println(stderr, "AVBlocks error: {}", ex.what());
        return false;
    } catch (const std::exception& ex) {
        std::println(stderr, "Error: {}", ex.what());
        return false;
    }
}

int main(int argc, char* argv[])
{
    Options opt;
    switch(prepareOptions(opt, argc, argv))
    {
        case Command: return 0;
        case Error:   return 1;
        case Parsed:  break;
    }

    TLibrary library;
    return encode(opt) ? 0 : 1;
}

How to Run

See the build instructions for macOS and the enc_avc_file example for details.

Command Line

./enc_avc_file --frame <width>x<height> --rate <fps> --color <COLOR> --input <file.yuv> --output <file.h264> [--colors] [--help]

Examples

List options:

./bin/x64/enc_avc_file --help
enc_avc_file --frame <width>x<height> --rate <fps> --color <COLOR> --input <file.yuv> --output <file.h264> [--colors]
  -h,    --help
  -i,    --input    input YUV file
  -o,    --output   output H264 file
  -r,    --rate     input frame rate
  -f,    --frame    input frame sizes <width>x<height>
  -c,    --color    input color format. Use --colors to list all supported color
                    formats
         --colors   list COLOR constants

The following example encodes input file ./assets/vid/foreman_qcif.yuv into output file foreman_qcif.h264:

mkdir -p ./output/enc_avc_file

./bin/x64/enc_avc_file \
  --input ./assets/vid/foreman_qcif.yuv \
  --output ./output/enc_avc_file/foreman_qcif.h264 \
  --frame 176x144 \
  --rate 30 \
  --color yuv420