H.264 Codec for ESP32-S3
Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Public Attributes | List of all members
H264Encoder< Alloc > Class Template Reference

Template class for capturing frames from ESP32 camera and encoding to H.264. More...

#include <H264Encoder.h>

Classes

struct  Config
 Configuration structure for camera, WiFi, and encoder settings. More...
 

Public Member Functions

Config defaultConfig ()
 Create a default configuration with reasonable defaults.
 
Config defaultConfig (const char *camera)
 Create a default configuration based on camera preset name.
 
 H264Encoder ()
 Default constructor.
 
 ~H264Encoder ()
 Destructor.
 
bool begin (Config cfg)
 Initialize WiFi, camera and H.264 encoder.
 
bool captureFrame (uint8_t *dst, size_t dst_len)
 Capture a single frame and write raw I420 data to buffer.
 
bool encodeYUV422 (const uint8_t *raw_data, size_t raw_len, Print &out)
 Encode raw YUV422 frame data to H.264 and write to Print stream.
 
bool encodeRGB565 (const uint8_t *raw_data, size_t raw_len, Print &out)
 Encode raw RGB565 frame data to H.264 and write to Print stream.
 
bool encode (const uint8_t *raw_data, size_t raw_len, Print &out)
 Encode raw I420 frame data to H.264 and write to Print stream.
 
bool captureH264 (Print &out)
 Capture frame, encode to H.264, and stream with frame rate control.
 
void end ()
 Cleanup and release camera resources.
 
sensor_t * getSensor ()
 

Static Public Attributes

static constexpr const char * TAG = "H264Encoder"
 Logging tag for ESP32 log system.
 

Detailed Description

template<typename Alloc = H264_DEFAULT_ALLOCATOR>
class esp_h264::H264Encoder< Alloc >

Template class for capturing frames from ESP32 camera and encoding to H.264.

H264Encoder is a lightweight, header-only class that wraps camera initialization, pixel format conversions (RGB565/YUV422 → I420), H.264 encoder lifecycle, and streaming to any Arduino Print implementation.

The class is templated on an allocator type to allow customization of memory allocation strategy (e.g., PSRAM vs regular heap).

Template Parameters
AllocMemory allocator type for internal buffers (defaults to PSRAMAllocatorH264)
Note
This class intentionally keeps implementation in the header for easy integration into Arduino sketches without separate .cpp files
The pixel format conversions are straightforward and not highly optimized
Requires ESP32 with camera module and sufficient memory for frame buffers

Example usage:

#include "H264Encoder.h"
#include "UDPPrint.h"
H264EncoderPSRAM streamer; // Uses PSRAM allocation (simpler than
void setup() {
auto cfg = streamer.defaultConfig();
cfg.ssid = "MyWiFi";
cfg.password = "MyPassword";
cfg.width = 640;
cfg.height = 480;
cfg.fps = 15;
udpOut.begin("192.168.1.100", 5000);
if (!streamer.begin(cfg)) {
Serial.println("Failed to start camera streamer");
}
}
void loop() {
streamer.captureH264(udpOut); // Captures, encodes, and streams
udpOut.flush();
}
Header-only helper to capture frames from ESP32 camera and encode to H.264.
header-only Arduino Print implementation that sends data over
Template class for capturing frames from ESP32 camera and encoding to H.264.
Definition: H264Encoder.h:75
bool captureH264(Print &out)
Capture frame, encode to H.264, and stream with frame rate control.
Definition: H264Encoder.h:451
bool begin(Config cfg)
Initialize WiFi, camera and H.264 encoder.
Definition: H264Encoder.h:209
Config defaultConfig()
Create a default configuration with reasonable defaults.
Definition: H264Encoder.h:133
A Print implementation that buffers and sends data over UDP.
Definition: UDPPrint.h:35
int width
Frame width in pixels.
Definition: H264Encoder.h:88

Constructor & Destructor Documentation

◆ H264Encoder()

H264Encoder ( )
inline

Default constructor.

Creates an uninitialized H264Encoder. Call begin() to initialize WiFi, camera, and encoder resources.

◆ ~H264Encoder()

~H264Encoder ( )
inline

Destructor.

Automatically releases camera, encoder, and buffer resources by calling end().

Note
Safe to destroy without calling end() explicitly

Member Function Documentation

◆ begin()

bool begin ( Config  cfg)
inline

Initialize WiFi, camera and H.264 encoder.

Configures and initializes all subsystems needed for camera streaming:

  1. WiFi connection (if credentials provided)
  2. Camera module with specified pins and resolution
  3. H.264 software encoder with specified bitrate and GOP
  4. Internal frame buffers using the configured allocator
Parameters
cfgConfiguration structure (passed by value to allow temporary objects)
Returns
true if all initialization succeeded, false on any failure
Note
If WiFi credentials are nullptr, WiFi initialization is skipped
Camera is configured for RGB565 pixel format internally
Frame buffers are allocated using the template allocator (Alloc)
On failure, any partially initialized resources are cleaned up

◆ captureFrame()

bool captureFrame ( uint8_t *  dst,
size_t  dst_len 
)
inline

Capture a single frame and write raw I420 data to buffer.

Captures one frame from the camera, converts it from the native format (RGB565 or YUV422) to I420 (YUV420 planar), and writes the raw pixel data to the provided buffer.

Parameters
dstDestination buffer for I420 pixel data
dst_lenSize of destination buffer in bytes
Returns
true if frame capture and conversion succeeded, false otherwise
Note
Buffer must be at least width × height × 1.5 bytes for I420 data
This is a lower-level method; most users should use captureH264() instead
Caller is responsible for ensuring buffer is large enough

◆ captureH264()

bool captureH264 ( Print &  out)
inline

Capture frame, encode to H.264, and stream with frame rate control.

High-level method that performs the complete streaming pipeline:

  1. Captures one frame from the camera
  2. Converts pixel format to I420 if needed
  3. Encodes frame using H.264 software encoder
  4. Writes encoded data to the provided Print stream
  5. Enforces configured frame rate by delaying remaining time

This method measures processing time and only delays for the remainder of the target frame interval, ensuring consistent frame rate regardless of processing time variations.

Parameters
outPrint stream to receive encoded H.264 NAL units
Returns
true if capture, encoding, and streaming succeeded, false otherwise
Note
Frame rate is controlled by Config::fps setting
Processing time is subtracted from frame interval delay
This is the main method most applications should use
On failure, no delay is applied (to avoid blocking on errors)

◆ defaultConfig() [1/2]

Config defaultConfig ( )
inline

Create a default configuration with reasonable defaults.

Returns a Config structure populated with default values suitable for ESP32-S3-EYE development boards. WiFi credentials are set to nullptr, requiring manual configuration or external WiFi management.

Returns
Config Default configuration structure
Note
WiFi SSID and password are nullptr - set them manually or manage WiFi externally
Pin assignments match the ESP32-S3-EYE development board layout

◆ defaultConfig() [2/2]

Config defaultConfig ( const char *  camera)
inline

Create a default configuration based on camera preset name.

Searches for a predefined camera preset that contains the specified name and returns a Config structure with the corresponding pin mappings and default settings. If no matching preset is found, returns the generic default configuration.

Parameters
cameraName of the camera preset
Returns
Config Configuration structure for the specified camera preset

◆ encode()

bool encode ( const uint8_t *  raw_data,
size_t  raw_len,
Print &  out 
)
inline

Encode raw I420 frame data to H.264 and write to Print stream.

Takes raw I420 pixel data, encodes it using the H.264 software encoder, and writes the resulting NAL units to the provided Print stream. Handles partial writes with retry logic.

Parameters
raw_dataPointer to I420 pixel data buffer
raw_lenSize of I420 data in bytes
outPrint stream to receive encoded H.264 data
Returns
true if encoding and writing succeeded, false otherwise
Note
Input data must be valid I420 format with correct dimensions
Implements retry logic for partial Print::write() operations
This is a lower-level method; most users should use captureH264() instead

◆ encodeRGB565()

bool encodeRGB565 ( const uint8_t *  raw_data,
size_t  raw_len,
Print &  out 
)
inline

Encode raw RGB565 frame data to H.264 and write to Print stream.

Converts RGB565 data to I420, encodes it, and writes to the Print stream.

Parameters
raw_dataPointer to RGB565 pixel data buffer
raw_lenSize of RGB565 data in bytes
outPrint stream to receive encoded H.264 data
Returns
true if encoding and writing succeeded, false otherwise

◆ encodeYUV422()

bool encodeYUV422 ( const uint8_t *  raw_data,
size_t  raw_len,
Print &  out 
)
inline

Encode raw YUV422 frame data to H.264 and write to Print stream.

Converts YUV422 data to I420, encodes it, and writes to the Print stream.

Parameters
raw_dataPointer to YUV422 pixel data buffer
raw_lenSize of YUV422 data in bytes
outPrint stream to receive encoded H.264 data
Returns
true if encoding and writing succeeded, false otherwise

◆ end()

void end ( )
inline

Cleanup and release camera resources.

Deinitializes the ESP32 camera driver and releases all allocated resources. Should be called when streaming is complete or when switching camera configurations.

After calling end(), the camera becomes available for other applications or for reconfiguration with different settings.

Note
Safe to call multiple times
Required before calling begin() with different Config
Automatically called by destructor

◆ getSensor()

sensor_t * getSensor ( )
inline

Member Data Documentation

◆ TAG

constexpr const char* TAG = "H264Encoder"
staticconstexpr

Logging tag for ESP32 log system.


The documentation for this class was generated from the following file: