通过FFmpeg进行h264的编码流程:
1.通过名字(h264编码器名字是libx264)查找编码器:avcodec_find_encoder_by_name()
。
2.设置编码器的参数(比如码率、分辨率、帧率、时间基等)。
3.打开编码器avcodec_open2()
。
4.对帧数据进行编码avcodec_send_frame()/avcodec_receive_packet()
,编码完后写入文件。(在实际使用中帧数据来源于解码后的元数据或来源于摄像头,本文示例的帧数据时人工添加了模拟数据。)
/*h264编码*/
#include
#include
#include
#include
#include
#include
// 对每一帧进行编码
static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt,
FILE *outfile)
{
int ret;
/* send the frame to the encoder */
if (frame)
printf("Send frame %3"PRId64"\n", frame->pts);
ret = avcodec_send_frame(enc_ctx, frame);
if (ret < 0) {
fprintf(stderr, "Error sending a frame for encoding\n");
exit(1);
}
while (ret >= 0) {
ret = avcodec_receive_packet(enc_ctx, pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
return;
else if (ret < 0) {
fprintf(stderr, "Error during encoding\n");
exit(1);
}
printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size);
fwrite(pkt->data, 1, pkt->size, outfile);
av_packet_unref(pkt);
}
}
int main(int argc, char **argv)
{
const char *filename, *codec_name; // 输出文件路径和编码器名字,由运行程序时传入参数(要编码的内容是从摄像头获取的)
const AVCodec *codec; // 编码器
AVCodecContext *c= NULL; // 编码上下文环境
// got_output用于标记一帧是否压缩成功
int i, ret, x, y, got_output;
FILE *f;
AVFrame *frame; // 原始帧(未压缩的数据)
AVPacket pkt;
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
if (argc <= 2) {
fprintf(stderr, "Usage: %s