使用FFmpeg将yuv420p编码为h264

代码对一些数据没做判断,仅仅是做个备忘!请谨慎参考!

#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <stdio.h>

void encode_to_h264(AVCodecContext *codec_ctx, AVFrame *frame, AVPacket *pkt,
                    FILE *file_out) {
  int ret;
  ret = avcodec_send_frame(codec_ctx, frame);
  while (!ret) {
    ret = avcodec_receive_packet(codec_ctx, pkt);
    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
      printf("AVERROR(EAGAIN) or AVERROR_EOF\n");
      return;
    } else if (ret < 0) {
      printf("error 8\n");
      exit(1);
    }
    printf("ENCODE SUCCESS\n");
    fwrite(pkt->data, 1, pkt->size, file_out);
    av_packet_unref(pkt);
  }
}

int main(int argc, char **argv) {
  AVCodecContext *codec_ctx;
  AVCodec *codec;
  FILE *file_in;
  FILE *file_out;
  uint8_t *in_buf;
  size_t in_size;
  char *in_yuv;
  char *out_h264;
  AVFrame *frame;
  AVPacket *pkt;
  int ret;
  if (argc != 3) {
    printf("error 0\n");
    exit(1);
  }
  in_yuv = argv[1];
  out_h264 = argv[2];
  file_in = fopen(in_yuv, "rb");
  file_out = fopen(out_h264, "wb");
  codec = avcodec_find_encoder(AV_CODEC_ID_H264);
  if (!codec) {
    printf("error 1\n");
    exit(1);
  }
  codec_ctx = avcodec_alloc_context3(codec);
  if (!codec_ctx) {
    printf("error 2\n");
    exit(1);
  }
  codec_ctx->width = 320;
  codec_ctx->height = 240;
  codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
  codec_ctx->gop_size = 12;
  codec_ctx->max_b_frames = 2;
  codec_ctx->framerate = (AVRational){25, 1};
  codec_ctx->time_base = (AVRational){1, 25};
  codec_ctx->bit_rate = 516 * 1024;
  ret = avcodec_open2(codec_ctx, codec, NULL);
  if (ret) {
    printf("error 5\n");
    exit(1);
  }
  in_size = av_image_get_buffer_size(codec_ctx->pix_fmt, codec_ctx->width,
                                     codec_ctx->height, 1);
  in_buf = av_malloc(in_size);
  frame = av_frame_alloc();
  frame->width = codec_ctx->width;
  frame->height = codec_ctx->height;
  frame->format = codec_ctx->pix_fmt;
  ret = av_frame_get_buffer(frame, 0);
  if (ret) {
    printf("error 3\n");
    exit(1);
  }
  pkt = av_packet_alloc();
  av_init_packet(pkt);
  int pts = 0;
  while (fread(in_buf, 1, in_size, file_in) == in_size) {
    ret = av_image_fill_arrays(frame->data, frame->linesize, in_buf,
                               codec_ctx->pix_fmt, codec_ctx->width,
                               codec_ctx->height, 1);
    if (ret < 0) {
      printf("error 4\n");
      exit(1);
    }
    frame->width = codec_ctx->width;
    frame->height = codec_ctx->height;
    frame->format = codec_ctx->pix_fmt;
    frame->pts = pts++;
    encode_to_h264(codec_ctx, frame, pkt, file_out);
    av_frame_unref(frame);
  }
  encode_to_h264(codec_ctx, NULL, pkt, file_out);
end:
  fclose(file_in);
  fclose(file_out);
  av_frame_free(&frame);
  av_packet_free(&pkt);
  avcodec_free_context(&codec_ctx);
  av_freep(&in_buf);
  printf("Finished!\n");
  return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是将Mat YUV编码H264流的C++代码示例,使用FFmpeg库: ```c++ #include <iostream> #include <fstream> #include <opencv2/opencv.hpp> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> int main(int argc, char* argv[]) { // Check input arguments if (argc < 4) { std::cerr << "Usage: " << argv[0] << " input_file width height output_file" << std::endl; return 1; } // Initialize FFmpeg av_register_all(); // Open input file const char* input_file = argv[1]; int width = std::stoi(argv[2]); int height = std::stoi(argv[3]); cv::Mat yuv_image(height * 3 / 2, width, CV_8UC1); std::ifstream input_stream(input_file, std::ios::binary); if (!input_stream.is_open()) { std::cerr << "Failed to open input file" << std::endl; return 1; } // Open output file const char* output_file = argv[4]; AVFormatContext* format_context = nullptr; if (avformat_alloc_output_context2(&format_context, nullptr, nullptr, output_file) < 0) { std::cerr << "Failed to allocate output context" << std::endl; return 1; } // Open output stream AVOutputFormat* output_format = format_context->oformat; AVStream* stream = avformat_new_stream(format_context, nullptr); if (!stream) { std::cerr << "Failed to create output stream" << std::endl; return 1; } stream->id = format_context->nb_streams - 1; AVCodecContext* codec_context = stream->codec; codec_context->codec_id = output_format->video_codec; codec_context->codec_type = AVMEDIA_TYPE_VIDEO; codec_context->width = width; codec_context->height = height; codec_context->pix_fmt = AV_PIX_FMT_YUV420P; codec_context->time_base = { 1, 25 }; if (format_context->oformat->flags & AVFMT_GLOBALHEADER) { codec_context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } AVCodec* codec = avcodec_find_encoder(codec_context->codec_id); if (!codec) { std::cerr << "Failed to find encoder" << std::endl; return 1; } if (avcodec_open2(codec_context, codec, nullptr) < 0) { std::cerr << "Failed to open codec" << std::endl; return 1; } av_dump_format(format_context, 0, output_file, 1); if (!(output_format->flags & AVFMT_NOFILE)) { if (avio_open(&format_context->pb, output_file, AVIO_FLAG_WRITE) < 0) { std::cerr << "Failed to open output file" << std::endl; return 1; } } if (avformat_write_header(format_context, nullptr) < 0) { std::cerr << "Failed to write header" << std::endl; return 1; } // Initialize video converter struct SwsContext* converter = sws_getContext(width, height, AV_PIX_FMT_GRAY8, width, height, AV_PIX_FMT_YUV420P, 0, nullptr, nullptr, nullptr); if (!converter) { std::cerr << "Failed to create video converter" << std::endl; return 1; } // Encode frames AVFrame* frame = av_frame_alloc(); frame->width = width; frame->height = height; frame->format = codec_context->pix_fmt; if (av_frame_get_buffer(frame, 0) < 0) { std::cerr << "Failed to allocate frame buffer" << std::endl; return 1; } AVPacket packet = { 0 }; int frame_count = 0; while (input_stream.read(reinterpret_cast<char*>(yuv_image.data), yuv_image.total())) { // Convert YUV image to AVFrame sws_scale(converter, &yuv_image.data, &yuv_image.step, 0, height, frame->data, frame->linesize); // Encode frame frame->pts = frame_count++; int result = avcodec_send_frame(codec_context, frame); if (result < 0) { std::cerr << "Failed to send frame" << std::endl; return 1; } while (result >= 0) { result = avcodec_receive_packet(codec_context, &packet); if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) { break; } if (result < 0) { std::cerr << "Failed to receive packet" << std::endl; return 1; } av_packet_rescale_ts(&packet, codec_context->time_base, stream->time_base); packet.stream_index = stream->index; if (av_interleaved_write_frame(format_context, &packet) < 0) { std::cerr << "Failed to write packet" << std::endl; return 1; } av_packet_unref(&packet); } } // Flush encoder int result = avcodec_send_frame(codec_context, nullptr); if (result < 0) { std::cerr << "Failed to send frame" << std::endl; return 1; } while (result >= 0) { result = avcodec_receive_packet(codec_context, &packet); if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) { break; } if (result < 0) { std::cerr << "Failed to receive packet" << std::endl; return 1; } av_packet_rescale_ts(&packet, codec_context->time_base, stream->time_base); packet.stream_index = stream->index; if (av_interleaved_write_frame(format_context, &packet) < 0) { std::cerr << "Failed to write packet" << std::endl; return 1; } av_packet_unref(&packet); } // Close output file av_write_trailer(format_context); if (format_context && !(output_format->flags & AVFMT_NOFILE)) { avio_close(format_context->pb); } avcodec_close(codec_context); avformat_free_context(format_context); av_frame_free(&frame); sws_freeContext(converter); input_stream.close(); return 0; } ``` 请注意,此示例假设输入文件为YUV 4:2:0格式的二进制文件,其中Y,U和V平面以交替方式存储。如果您的输入格式不同,请根据需要进行修改。此外,此示例假设您已安装OpenCV和FFmpeg库。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值