G.711 A-law Decoder (Run)

This article explains how you can use Transcoder.Run to decode a G.711 A-law WAV file to uncompressed PCM WAV.

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

Source Audio

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

Code

This code takes a G.711 A-law WAV file and decodes it to uncompressed LPCM WAV file.

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 decodeResult = Decode(opt);

    Library.Shutdown();

    return decodeResult ? (int)ExitCodes.Success : (int)ExitCodes.DecodingError;
}

Configure Output Socket

The output socket defines where and how the decoded audio data will be written. In this case, we’re configuring it to output a WAV file with 16-bit LPCM (Linear Pulse Code Modulation) format. The G.711 A-law decoder outputs audio at the same sample rate as the input (typically 8000 Hz) with mono channel configuration. The AudioStreamInfo object specifies these audio format parameters - converting from 8-bit logarithmic samples to 16-bit linear samples.

static MediaSocket CreateOutputSocket(Options opt)
{
    MediaSocket socket = new MediaSocket();
    socket.File = opt.OutputFile;
    socket.StreamType = StreamType.Wave;

    MediaPin pin = new MediaPin();
    socket.Pins.Add(pin);

    AudioStreamInfo asi = new AudioStreamInfo();
    pin.StreamInfo = asi;

    asi.StreamType = StreamType.LPCM;
    // PCM output with 16-bit samples
    asi.SampleRate = 8000;
    asi.Channels = 1;
    asi.BitsPerSample = 16;

    return socket;
}

Configure Transcoder and Decode

This is the main decoding function that ties everything together. First, we create an input socket that points to the G.711 A-law WAV file we want to decode. Then we create the output socket using our helper method. The transcoder is the core component that performs the actual decoding - it takes the compressed G.711 A-law data from the input and converts it to uncompressed LPCM data for the output.

The AllowDemoMode = true setting 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.

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

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

    // create input socket
    MediaSocket inSocket = new MediaSocket();
    inSocket.File = opt.InputFile;

    // create output socket
    MediaSocket outSocket = CreateOutputSocket(opt);

    // create Transcoder
    using (Transcoder transcoder = new Transcoder())
    {
        transcoder.AllowDemoMode = true;
        transcoder.Inputs.Add(inSocket);
        transcoder.Outputs.Add(outSocket);

        bool res = transcoder.Open();
        PrintError("Transcoder open", transcoder.Error);
        if (!res)
            return false;

        res = transcoder.Run();
        PrintError("Transcoder run", transcoder.Error);
        if (!res)
            return false;

        transcoder.Close();
    }

    return true;
}

Complete C# Code

Here’s the complete working example that demonstrates G.711 A-law decoding 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 decoding operation, and properly shuts down the library before exiting.

using System;
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 decodeResult = Decode(opt);

            Library.Shutdown();

            return decodeResult ? (int)ExitCodes.Success : (int)ExitCodes.DecodingError;
        }

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

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

            // create input socket
            MediaSocket inSocket = new MediaSocket();
            inSocket.File = opt.InputFile;

            // create output socket
            MediaSocket outSocket = CreateOutputSocket(opt);

            // create Transcoder
            using (Transcoder transcoder = new Transcoder())
            {
                transcoder.AllowDemoMode = true;
                transcoder.Inputs.Add(inSocket);
                transcoder.Outputs.Add(outSocket);

                bool res = transcoder.Open();
                PrintError("Transcoder open", transcoder.Error);
                if (!res)
                    return false;

                res = transcoder.Run();
                PrintError("Transcoder run", transcoder.Error);
                if (!res)
                    return false;

                transcoder.Close();
            }

            return true;
        }

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

        static MediaSocket CreateOutputSocket(Options opt)
        {
            MediaSocket socket = new MediaSocket();
            socket.File = opt.OutputFile;
            socket.StreamType = StreamType.Wave;

            MediaPin pin = new MediaPin();
            socket.Pins.Add(pin);

            AudioStreamInfo asi = new AudioStreamInfo();
            pin.StreamInfo = asi;

            asi.StreamType = StreamType.LPCM;
            // PCM output with 16-bit samples
            asi.SampleRate = 8000;
            asi.Channels = 1;
            asi.BitsPerSample = 16;

            return socket;
        }

        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,
            DecodingError = 2,
        }
    }
}

How to Run

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

Command Line

dec_g711_alaw_file --input <g711 alaw wav file> --output <wav file>

Examples

List options:

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

  -i, --input     input G.711 A-law WAV file

  -o, --output    output PCM WAV file

  --help          Display this help screen.

  --version       Display version information.

The following example decodes input file ./assets/aud/express-dictate_8000_s8_1ch_alaw.wav into output file ./output/dec_g711_alaw_file/express-dictate_8000_s16_1ch_pcm.wav:

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

./bin/net10.0/dec_g711_alaw_file \
    --input ./assets/aud/express-dictate_8000_s8_1ch_alaw.wav \
    --output ./output/dec_g711_alaw_file/express-dictate_8000_s16_1ch_pcm.wav
# Windows
mkdir -Force -Path ./output/dec_g711_alaw_file

./bin/net10.0/dec_g711_alaw_file `
    --input ./assets/aud/express-dictate_8000_s8_1ch_alaw.wav `
    --output ./output/dec_g711_alaw_file/express-dictate_8000_s16_1ch_pcm.wav