Opus Encoder (Run)

This article explains how you can use TTranscoder::run to encode a WAV file to Opus audio stored in an OGG container.

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

Source Audio

For source we use the equinox-48KHz.wav file from the AVBlocks Assets repository. After downloading and unzipping you will find equinox-48KHz.wav in the aud subdirectory.

Code

This code takes a WAV file and encodes it to Opus audio in an OGG container.

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 Output Socket

The output socket defines where and how the encoded audio data will be written. In this case, we’re configuring it to output an Opus stream in an OGG container. The socket represents the output destination, while the pin represents the specific audio stream within that destination. The TAudioStreamInfo object specifies the audio format parameters - you can customize the bitrate, sampling rate, or number of channels with its bitrate, sampleRate and channels methods.

TMediaSocket()
    .file(opt.outputFile)
    .streamType(StreamType::OGG)
    .addPin(
        TMediaPin()
            .streamInfo(TAudioStreamInfo()
                .streamType(StreamType::Opus)
            )
    )

Configure Transcoder and Encode

This is the main encoding function that ties everything together. First, we create an input socket that points to the WAV 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 LPCM data from the input and converts it to compressed Opus 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.outputFile.c_str());

        TTranscoder()
            .allowDemoMode(true)
            .addInput(
                TMediaSocket()
                    .file(opt.inputFile)
            )
            .addOutput(
                TMediaSocket()
                    .file(opt.outputFile)
                    .streamType(StreamType::OGG)
                    .addPin(
                        TMediaPin()
                            .streamInfo(TAudioStreamInfo()
                                .streamType(StreamType::Opus)
                            )
                    )
            )
            .open()
            .run()
            .close();

        std::println("Output: {}", opt.outputFile);
        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 Opus 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.outputFile.c_str());

        TTranscoder()
            .allowDemoMode(true)
            .addInput(
                TMediaSocket()
                    .file(opt.inputFile)
            )
            .addOutput(
                TMediaSocket()
                    .file(opt.outputFile)
                    .streamType(StreamType::OGG)
                    .addPin(
                        TMediaPin()
                            .streamInfo(TAudioStreamInfo()
                                .streamType(StreamType::Opus)
                            )
                    )
            )
            .open()
            .run()
            .close();

        std::println("Output: {}", opt.outputFile);
        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_opus_file example for details.

Command Line

./enc_opus_file --input <wav file> --output <opus file>

Examples

List options:

./bin/x64/enc_opus_file --help
Usage: enc_opus_file --input <wav file> --output <opus file>
  -h,    --help
  -i,    --input    input WAV file
  -o,    --output   output Opus file

The following example encodes input file ./assets/aud/equinox-48KHz.wav into output file equinox-48KHz.opus:

mkdir -p ./output/enc_opus_file

./bin/x64/enc_opus_file \
    --input ./assets/aud/equinox-48KHz.wav \
    --output ./output/enc_opus_file/equinox-48KHz.opus