MP3 Encoder (Push)

This article explains how you can use Transcoder.Push to encode an MP3 audio stream from raw audio frames.

The code snippets in this article are from the enc_mp3_push sample.

Source Audio

As audio input we use the equinox-48KHz.wav file from the AVBlocks Assets archive. After downloading and unzipping you will find equinox-48KHz.wav in the aud subdirectory.

Code

This code shows how you can encode raw uncompressed audio frames into an MP3 stream. Two Transcoder objects are used, one to read the raw LPCM frames from a file, and another to encode the raw frames to MP3 stream. The encoding is done via the Transcoder.Push method.

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 Library.Initialize() method sets up the internal state and loads necessary codecs. Always remember to call Library.Shutdown() at the end of your program to properly clean up resources and release any allocated memory.

static int Main(string[] args)
{
    var opt = new Options();

    if (!opt.Prepare(args))
        return opt.Error ? (int)ExitCodes.OptionsError : (int)ExitCodes.Success;

    Library.Initialize();

    // Set license information. Without this AVBlocks runs in Demo mode.
    // Library.SetLicense("<license-string>");

    bool encodeResult = Encode(opt);

    Library.Shutdown();

    return encodeResult ? (int)ExitCodes.Success : (int)ExitCodes.EncodingError;
}

Configure Input Socket

The input socket defines the format of the raw LPCM audio frames that will be fed to the MP3 encoder. This socket describes uncompressed 16-bit stereo audio at 48 kHz sample rate. The socket represents the input source, while the pin represents the specific audio stream within that source. The AudioStreamInfo object specifies the audio format parameters that the encoder expects to receive.

static MediaSocket CreateInputSocket()
{
    MediaSocket socket = new MediaSocket();
    socket.StreamType = StreamType.LPCM;

    MediaPin pin = new MediaPin();
    AudioStreamInfo asi = new AudioStreamInfo();
    asi.StreamType = StreamType.LPCM;
    asi.Channels = 2;
    asi.SampleRate = 48000;
    asi.BitsPerSample = 16;

    pin.StreamInfo = asi;
    socket.Pins.Add(pin);

    return socket;
}

Configure Output Socket

The output socket defines where and how the encoded MP3 data will be written. This method sets up the MP3 encoding parameters including the output file location, audio format, and encoding options. You can customize the bitrate, sample rate, and number of channels by uncommenting the relevant lines. The socket represents the output destination, while the pin represents the specific MP3 stream within that destination.

static MediaSocket CreateOutputSocket(string outputFile)
{
    MediaSocket socket = new MediaSocket();
    socket.StreamType = StreamType.MpegAudio;
    socket.StreamSubType = StreamSubType.MpegAudioLayer3;
    socket.File = outputFile;

    MediaPin pin = new MediaPin();
    AudioStreamInfo asi = new AudioStreamInfo();
    asi.StreamType = StreamType.MpegAudio;
    asi.StreamSubType = StreamSubType.MpegAudioLayer3;

    // The default bitrate is 128000. You can set it to 192000, 256000, etc.
    // asi.Bitrate = 192000;

    // Optionally set the sampling rate and the number of the channels, e.g. 44.1 Khz, Mono
    // asi.SampleRate = 44100;
    // asi.Channels = 1;

    pin.StreamInfo = asi;
    socket.Pins.Add(pin);

    return socket;
}

Configure WAV Reader

This method creates a transcoder that reads WAV files and outputs raw LPCM audio frames. In a real-world scenario, you might have a different audio source like an audio capture device or streaming input. The WAV reader transcoder converts the compressed or container-wrapped audio in the WAV file into raw PCM samples that can be fed to the MP3 encoder. The AllowDemoMode = true setting allows the transcoder to work without a valid license for testing purposes.

static Transcoder CreateWavReader(string inputFile)
{
    Transcoder wavReader = new Transcoder();
    wavReader.AllowDemoMode = true;

    MediaSocket wavInputSocket = new MediaSocket();
    wavInputSocket.File = inputFile;
    wavReader.Inputs.Add(wavInputSocket);

    MediaSocket pcmOutputSocket = new MediaSocket();
    pcmOutputSocket.StreamType = StreamType.LPCM;
    MediaPin pcmPin = new MediaPin();
    AudioStreamInfo pcmAsi = new AudioStreamInfo();
    pcmAsi.StreamType = StreamType.LPCM;
    pcmAsi.Channels = 2;
    pcmAsi.SampleRate = 48000;
    pcmAsi.BitsPerSample = 16;
    pcmPin.StreamInfo = pcmAsi;
    pcmOutputSocket.Pins.Add(pcmPin);
    wavReader.Outputs.Add(pcmOutputSocket);

    return wavReader;
}

Configure Transcoder and Encode

This is the main encoding function that coordinates the entire MP3 encoding process. It creates both the WAV reader (to provide raw audio frames) and the MP3 encoder (to compress those frames). The function demonstrates the push-based encoding workflow where raw PCM samples are pulled from the WAV reader and pushed to the MP3 encoder. The encoding loop continues until all audio data has been processed, with proper error handling and end-of-stream detection.

static bool Encode(Options opt)
{
    // transcoder will fail if output exists (by design)
    DeleteFile(opt.OutputFile);

    // Create output directory if needed
    string outputDir = Path.GetDirectoryName(opt.OutputFile);
    if (!string.IsNullOrEmpty(outputDir))
        Directory.CreateDirectory(outputDir);

    // Create WAV reader transcoder
    using (Transcoder wavReader = CreateWavReader(opt.InputFile))
    {
        if (!wavReader.Open())
        {
            PrintError("WAV Reader open", wavReader.Error);
            return false;
        }

        // Create encoder transcoder
        using (Transcoder encoder = new Transcoder())
        {
            encoder.AllowDemoMode = true;
            encoder.Inputs.Add(CreateInputSocket());
            encoder.Outputs.Add(CreateOutputSocket(opt.OutputFile));

            if (!encoder.Open())
            {
                PrintError("Encoder open", encoder.Error);
                wavReader.Close();
                return false;
            }

            // Push encoding loop
            int wavOutputIndex = 0;
            MediaSample pcmSample = new MediaSample();

            bool wavEos = false;
            while (!wavEos)
            {
                // Get PCM sample from WAV reader
                if (wavReader.Pull(out wavOutputIndex, pcmSample))
                {
                    // Push PCM sample to encoder
                    if (!encoder.Push(0, pcmSample))
                    {
                        PrintError("Encoder push", encoder.Error);
                        wavReader.Close();
                        encoder.Close();
                        return false;
                    }
                }
                else
                {
                    // No more PCM data from WAV reader
                    ErrorInfo error = wavReader.Error;
                    if (error.Facility == ErrorFacility.Codec &&
                        error.Code == (int)CodecError.EOS)
                    {
                        // Push null to signal EOS to encoder
                        encoder.Push(0, null);
                        wavEos = true;
                    }
                    else
                    {
                        PrintError("WAV Reader pull", error);
                        wavReader.Close();
                        encoder.Close();
                        return false;
                    }
                }
            }

            wavReader.Close();
            encoder.Close();
        }
    }

    return true;
}

Complete C# Code

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

using System;
using System.IO;
using PrimoSoftware.AVBlocks;

namespace CliSample
{
    class Program
    {
        static int Main(string[] args)
        {
            var opt = new Options();

            if (!opt.Prepare(args))
                return opt.Error ? (int)ExitCodes.OptionsError : (int)ExitCodes.Success;

            Library.Initialize();

            // Set license information. Without this AVBlocks runs in Demo mode.
            // Library.SetLicense("<license-string>");

            bool encodeResult = Encode(opt);

            Library.Shutdown();

            return encodeResult ? (int)ExitCodes.Success : (int)ExitCodes.EncodingError;
        }

        static MediaSocket CreateInputSocket()
        {
            MediaSocket socket = new MediaSocket();
            socket.StreamType = StreamType.LPCM;

            MediaPin pin = new MediaPin();
            AudioStreamInfo asi = new AudioStreamInfo();
            asi.StreamType = StreamType.LPCM;
            asi.Channels = 2;
            asi.SampleRate = 48000;
            asi.BitsPerSample = 16;

            pin.StreamInfo = asi;
            socket.Pins.Add(pin);

            return socket;
        }

        static MediaSocket CreateOutputSocket(string outputFile)
        {
            MediaSocket socket = new MediaSocket();
            socket.StreamType = StreamType.MpegAudio;
            socket.StreamSubType = StreamSubType.MpegAudioLayer3;
            socket.File = outputFile;

            MediaPin pin = new MediaPin();
            AudioStreamInfo asi = new AudioStreamInfo();
            asi.StreamType = StreamType.MpegAudio;
            asi.StreamSubType = StreamSubType.MpegAudioLayer3;

            // The default bitrate is 128000. You can set it to 192000, 256000, etc.
            // asi.Bitrate = 192000;

            // Optionally set the sampling rate and the number of the channels, e.g. 44.1 Khz, Mono
            // asi.SampleRate = 44100;
            // asi.Channels = 1;

            pin.StreamInfo = asi;
            socket.Pins.Add(pin);

            return socket;
        }

        static Transcoder CreateWavReader(string inputFile)
        {
            Transcoder wavReader = new Transcoder();
            wavReader.AllowDemoMode = true;

            MediaSocket wavInputSocket = new MediaSocket();
            wavInputSocket.File = inputFile;
            wavReader.Inputs.Add(wavInputSocket);

            MediaSocket pcmOutputSocket = new MediaSocket();
            pcmOutputSocket.StreamType = StreamType.LPCM;
            MediaPin pcmPin = new MediaPin();
            AudioStreamInfo pcmAsi = new AudioStreamInfo();
            pcmAsi.StreamType = StreamType.LPCM;
            pcmAsi.Channels = 2;
            pcmAsi.SampleRate = 48000;
            pcmAsi.BitsPerSample = 16;
            pcmPin.StreamInfo = pcmAsi;
            pcmOutputSocket.Pins.Add(pcmPin);
            wavReader.Outputs.Add(pcmOutputSocket);

            return wavReader;
        }

        static bool Encode(Options opt)
        {
            // transcoder will fail if output exists (by design)
            DeleteFile(opt.OutputFile);

            // Create output directory if needed
            string outputDir = Path.GetDirectoryName(opt.OutputFile);
            if (!string.IsNullOrEmpty(outputDir))
                Directory.CreateDirectory(outputDir);

            // Create WAV reader transcoder
            using (Transcoder wavReader = CreateWavReader(opt.InputFile))
            {
                if (!wavReader.Open())
                {
                    PrintError("WAV Reader open", wavReader.Error);
                    return false;
                }

                // Create encoder transcoder
                using (Transcoder encoder = new Transcoder())
                {
                    encoder.AllowDemoMode = true;
                    encoder.Inputs.Add(CreateInputSocket());
                    encoder.Outputs.Add(CreateOutputSocket(opt.OutputFile));

                    if (!encoder.Open())
                    {
                        PrintError("Encoder open", encoder.Error);
                        wavReader.Close();
                        return false;
                    }

                    // Push encoding loop
                    int wavOutputIndex = 0;
                    MediaSample pcmSample = new MediaSample();

                    bool wavEos = false;
                    while (!wavEos)
                    {
                        // Get PCM sample from WAV reader
                        if (wavReader.Pull(out wavOutputIndex, pcmSample))
                        {
                            // Push PCM sample to encoder
                            if (!encoder.Push(0, pcmSample))
                            {
                                PrintError("Encoder push", encoder.Error);
                                wavReader.Close();
                                encoder.Close();
                                return false;
                            }
                        }
                        else
                        {
                            // No more PCM data from WAV reader
                            ErrorInfo error = wavReader.Error;
                            if (error.Facility == ErrorFacility.Codec &&
                                error.Code == (int)CodecError.EOS)
                            {
                                // Push null to signal EOS to encoder
                                encoder.Push(0, null);
                                wavEos = true;
                            }
                            else
                            {
                                PrintError("WAV Reader pull", error);
                                wavReader.Close();
                                encoder.Close();
                                return false;
                            }
                        }
                    }

                    wavReader.Close();
                    encoder.Close();
                }
            }

            return true;
        }

        static void DeleteFile(string filename)
        {
            try
            {
                if (File.Exists(filename))
                    File.Delete(filename);
            }
            catch { }
        }

        static void PrintError(string action, ErrorInfo e)
        {
            if (action != null)
            {
                Console.Write("{0}: ", action);
            }

            if (ErrorFacility.Success == e.Facility)
            {
                Console.WriteLine("Success");
                return;
            }
            else
            {
                Console.WriteLine("{0}, facility:{1} code:{2} hint:{3}", e.Message ?? "", e.Facility, e.Code, e.Hint ?? "");
            }
        }

        enum ExitCodes : int
        {
            Success = 0,
            OptionsError = 1,
            EncodingError = 2,
        }
    }
}

How to Run

See the build instructions for Windows, macOS, and Linux, and the enc_mp3_push sample for details.

Command Line

enc_mp3_push --input <wav file> --output <mp3 file>

Examples

List options:

./bin/net10.0/enc_mp3_push --help
enc_mp3_push 1.0.0.0
Copyright (C) 2023 Primo Software

  -i, --input     input WAV file

  -o, --output    output MP3 file

  --help          Display this help screen.

  --version       Display version information.

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

# Linux and macOS
mkdir -p ./output/enc_mp3_push

./bin/net10.0/enc_mp3_push \
    --input ./assets/aud/equinox-48KHz.wav \
    --output ./output/enc_mp3_push/equinox-48KHz.mp3
# Windows
mkdir -Force -Path ./output/enc_mp3_push

./bin/net10.0/enc_mp3_push `
    --input ./assets/aud/equinox-48KHz.wav `
    --output ./output/enc_mp3_push/equinox-48KHz.mp3