AVC / H.264 Annex B Decoder (Run)¶
This article explains how you can use Transcoder.Run to decode an AVC / H.264 elementary stream to a raw YUV video file.
The code snippets in this article are from the dec_avc_file sample.
Source Video¶
For source we use the foreman_qcif.h264 file from the AVBlocks Assets repository. After downloading and unzipping you will find foreman_qcif.h264 in the vid subdirectory.
Code¶
This code takes a compressed H.264 elementary stream file and decodes it to raw YUV video 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 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. To run AVBlocks in demo mode, comment the next line out
// Library.SetLicense("<license-string>");
bool decAvcFileResult = Decode(opt);
Library.Shutdown();
return decAvcFileResult ? (int)ExitCodes.Success : (int)ExitCodes.DecodingError;
}
Configure Output Socket¶
The output socket defines where and how the decoded raw YUV video data will be written. We configure it to output an uncompressed YUV 4:2:0 video file. The socket represents the output destination, while the pin represents the specific video stream within that destination. By setting ColorFormat.YUV420, we ensure the output uses the standard YUV 4:2:0 planar format, which is the most common format for raw video and provides a good balance between quality and file size.
static MediaSocket CreateOutputSocket(Options opt)
{
MediaSocket socket = new MediaSocket();
socket.File = opt.OutputFile;
socket.StreamType = StreamType.UncompressedVideo;
MediaPin pin = new MediaPin();
socket.Pins.Add(pin);
VideoStreamInfo vsi = new VideoStreamInfo();
pin.StreamInfo = vsi;
vsi.StreamType = StreamType.UncompressedVideo;
vsi.ColorFormat = ColorFormat.YUV420;
return socket;
}
Configure Transcoder and Decode¶
This is the main decoding function that ties everything together. First, we create a MediaInfo object and open it against the H.264 file to detect the input stream format, then build the matching input socket with MediaSocket.FromMediaInfo. This is more convenient than manually specifying parameters, as MediaInfo reads the stream headers and extracts all necessary information about the encoded video, including resolution, frame rate, and codec settings. 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 H.264 data from the input and converts it to uncompressed YUV 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);
var mediaInfo = new PrimoSoftware.AVBlocks.MediaInfo();
mediaInfo.Inputs[0].File = opt.InputFile;
if (!mediaInfo.Open())
{
PrintError("MediaInfo.Open()", mediaInfo.Error);
return false;
}
MediaSocket inSocket = MediaSocket.FromMediaInfo(mediaInfo);
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();
PrintError("Transcoder close", transcoder.Error);
if (!res)
return false;
}
return true;
}
Complete C# Code¶
Here’s the complete working example that demonstrates H.264 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. To run AVBlocks in demo mode, comment the next line out
// Library.SetLicense("<license-string>");
bool decAvcFileResult = Decode(opt);
Library.Shutdown();
return decAvcFileResult ? (int)ExitCodes.Success : (int)ExitCodes.DecodingError;
}
static bool Decode(Options opt)
{
// transcoder will fail if output exists (by design)
DeleteFile(opt.OutputFile);
var mediaInfo = new PrimoSoftware.AVBlocks.MediaInfo();
mediaInfo.Inputs[0].File = opt.InputFile;
if (!mediaInfo.Open())
{
PrintError("MediaInfo.Open()", mediaInfo.Error);
return false;
}
MediaSocket inSocket = MediaSocket.FromMediaInfo(mediaInfo);
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();
PrintError("Transcoder close", transcoder.Error);
if (!res)
return false;
}
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.UncompressedVideo;
MediaPin pin = new MediaPin();
socket.Pins.Add(pin);
VideoStreamInfo vsi = new VideoStreamInfo();
pin.StreamInfo = vsi;
vsi.StreamType = StreamType.UncompressedVideo;
vsi.ColorFormat = ColorFormat.YUV420;
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_avc_file sample for details.
Command Line¶
dec_avc_file --input <file.h264> --output <file.yuv>
Examples¶
List options:
./bin/net10.0/dec_avc_file --help
dec_avc_file 1.0.0.0
Copyright (C) 2023 Primo Software
-i, --input input AVC / H.264 file
-o, --output output YUV file
--help Display this help screen.
The following example decodes input file ./assets/vid/foreman_qcif.h264 into output file foreman_qcif.yuv:
# Linux and macOS
mkdir -p ./output/dec_avc_file
./bin/net10.0/dec_avc_file \
--input ./assets/vid/foreman_qcif.h264 \
--output ./output/dec_avc_file/foreman_qcif.yuv
# Windows
mkdir -Force -Path ./output/dec_avc_file
./bin/net10.0/dec_avc_file `
--input ./assets/vid/foreman_qcif.h264 `
--output ./output/dec_avc_file/foreman_qcif.yuv