C++ – h264 encode video stream ffmpeg c++

cffmpegvideo streaming

I'm trying to develop A live streaming app that capture video from web cam encode it to H264 video stream and use rtsp to send it to device,
I've looked up some examples and found this:
FFMPEG to send RTSP encoded stream C++

I've been using it as a reference to my program.

However I'm keep getting AVCodec type "MPEG", I've been trying to change filename extension and tried different approaches with avformat_alloc_output_context2

This is the relevant code:

const char *filename = "rtsp://127.0.0.1:7003/live.sdp";
AVOutputFormat *fmt;
AVFormatContext *oc;
AVStream *video_st;
AVCodec *video_codec;
video_st = NULL;

av_register_all();
avformat_network_init();
// format context:
avformat_alloc_output_context2(&oc,NULL,"rtsp",filename);

After calling avformat_alloc_output_context2 oc->oformat->video_codec is generated as MPEG codec.
I've tried changing filename extension to:

const char *filename = "rtsp://127.0.0.1:7003/live.264";
const char *filename = "rtsp://127.0.0.1:7003/live.h264";

and a bunch of other extensions.

How can I generate a H264 stream?

Best Answer

According to the documentation, you need to pass an output format to avformat_alloc_output_context2.

To quote (content in square brackets mine):

[the second parameter is the] format to use for allocating the context, if NULL format_name and filename are used instead

This parameter is a pointer to type AVOutputFormat.

Alternatively, you could continue to pass NULL and infer the output by using H264 as the format name.

Either way, I think you'll need to separate the encoding process from the streaming protocol.

This separation of concerns is useful, as if you find you want to use a different protocol to get the stream, the encoding code does not need to know about it.

Related Topic