FFmpegH264Provider

FFmpegH264Provider can help you quickly create an H264 Stream. It supports setting the cache size and the cache duration in milliseconds. You can use it for live broadcasts or video recordings. FFmpegH264Provider is dependent on FFmpegVideoSource and FFmpegH264Encoder. It gets YUV data through FFmpegVideoSource and then sends YUV data to FFmpegH264Encoder. H264 data generated by FFmpegH264Encoder will be cached in the queue of FFmpegH264Provider. All of its APIs are thread-safe.

API Instructions

namespace com { namespace sunplus { namespace media { class FFmpegH264Provider { public: FFmpegH264Provider(std::shared_ptr<FFmpegVideoSource> yuvSource, int maxCacheSize = 150, int maxCacheTimeMs = 0); ~FFmpegH264Provider(); public: int prepare(VideoStreamParam_t param); void destroy(); AVCodecContext* getAVCodecContext(); int getFrame(AVPacket*& packet); int getAllFrames(std::queue<AVPacket*>& frameQueue); }; }}}

Constructors

When creating FFmpegH264Provider you can set the cache size or duration.

  • if maxCacheSize > 0 && maxCacheTimeMs > 0, maxCacheTimeMs is valid.

  • if maxCacheSize <=0 && maxCacheTimeMs <=0, will not limit the cache size and the cache duration. It is recommended to use this only when recording, to prevent dropped frames.

/** * @param yuvSource provide yuv data. * * @param maxCacheSize >0 is valid. * * @param maxCacheTimeMs >0 is valid. * */ FFmpegH264Provider(std::shared_ptr<FFmpegVideoSource> yuvSource, int maxCacheSize = 150, int maxCacheTimeMs = 0);

prepare

Set encoding parameters. Create FFmpegH264Encoder and initialize it. Create FFmpegVideoProvider to get yuv frame. Initialize the queue for cache the h264 frame. You can only getFrame/getAllFrames after preparing.

/** * Set encoding parameters and initialize all required resources. * * @param param set parameters of the encoder. * */ int prepare(VideoStreamParam_t param);

destroy

Release all resources allocated by the prepare method and close the encoder. Empty the cached h264 frame and release the related resources. After destroying, the getFrame/getAllFrames returns a failure.

getAVCodecContext

Get AVCodecContext to get the info of the encoder, such as width, height, spspps, etc.

getFrame

Get cached h264 frame from the queue. After successfully obtaining the packet, it must be freed with av_packet_unref()+av_packet_free() when it is no longer needed.

getAllFrames

Get all cached h264 frames from the queue. The packet must be freed with av_packet_unref()+av_packet_free() when it is no longer needed.

Sample Code

This is a sample of how to create the FFmpegH264Provider and get the h264 frame through it.

You can also refer to the Sample of FFmpegAVMuxer.

the flow of encode h264:

create yuv source --> create h264 provider --> provider prepare --> create the thread of get the h264 frame

Test Result

FFmpegH264ProviderTestResult.png

Â