encoder_video_x264.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #include "encoder_video_x264.h"
  2. #include "headers_ffmpeg.h"
  3. #include "error_define.h"
  4. #include "log_helper.h"
  5. namespace am {
  6. encoder_video_x264::encoder_video_x264()
  7. {
  8. ffmpeg_register_all();
  9. _encoder = NULL;
  10. _encoder_ctx = NULL;
  11. _frame = NULL;
  12. _buff = NULL;
  13. _buff_size = 0;
  14. _y_size = 0;
  15. }
  16. encoder_video_x264::~encoder_video_x264()
  17. {
  18. stop();
  19. cleanup();
  20. }
  21. int encoder_video_x264::init(
  22. int pic_width, int pic_height, int frame_rate, int bit_rate, int qb, int key_pic_sec)
  23. {
  24. if (_inited == true)
  25. return AE_NO;
  26. int err = AE_NO;
  27. int ret = 0;
  28. AVDictionary *options = 0;
  29. // 使用ultrafast预设以获得最低延迟
  30. av_dict_set(&options, "preset", "ultrafast", 0);
  31. av_dict_set(&options, "tune", "zerolatency", 0);
  32. // 设置x264参数以匹配低延迟配置
  33. av_dict_set(&options, "x264-params", "keyint=30:min-keyint=30:no-scenecut=1", 0);
  34. av_dict_set(&options, "profile", "high", 0);
  35. av_dict_set(&options, "level", "4.1", 0);
  36. do {
  37. _encoder = avcodec_find_encoder(AV_CODEC_ID_H264);
  38. if (!_encoder) {
  39. err = AE_FFMPEG_FIND_ENCODER_FAILED;
  40. break;
  41. }
  42. _encoder_ctx = avcodec_alloc_context3(_encoder);
  43. if (!_encoder_ctx) {
  44. err = AE_FFMPEG_ALLOC_CONTEXT_FAILED;
  45. break;
  46. }
  47. _encoder_ctx->codec_id = AV_CODEC_ID_H264;
  48. _encoder_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
  49. _encoder_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
  50. _encoder_ctx->width = pic_width;
  51. _encoder_ctx->height = pic_height;
  52. _encoder_ctx->time_base.num = 1;
  53. _encoder_ctx->time_base.den = frame_rate;
  54. _encoder_ctx->framerate = {frame_rate, 1};
  55. _encoder_ctx->bit_rate = bit_rate;
  56. // 设置GOP大小为30帧,与用户ffmpeg命令一致
  57. _encoder_ctx->gop_size = 30;
  58. // 使用CRF 18以获得高质量和低延迟的平衡
  59. // 注意:FFmpeg的libx264编码器通过crf参数控制质量
  60. // 这里我们设置合理的qmin和qmax值
  61. _encoder_ctx->qmin = 10;
  62. _encoder_ctx->qmax = 25;
  63. // 设置CRF值(通过全局质量参数)
  64. _encoder_ctx->global_quality = 18 * FF_QP2LAMBDA;
  65. _encoder_ctx->max_b_frames = 0; //NO B Frame
  66. _encoder_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  67. ret = avcodec_open2(_encoder_ctx, _encoder, &options);
  68. if (ret != 0) {
  69. err = AE_FFMPEG_OPEN_CODEC_FAILED;
  70. break;
  71. }
  72. _frame = av_frame_alloc();
  73. _buff_size = av_image_get_buffer_size(_encoder_ctx->pix_fmt,
  74. _encoder_ctx->width,
  75. _encoder_ctx->height,
  76. 1);
  77. _buff = (uint8_t *) av_malloc(_buff_size);
  78. if (!_buff) {
  79. break;
  80. }
  81. av_image_fill_arrays(_frame->data,
  82. _frame->linesize,
  83. _buff,
  84. _encoder_ctx->pix_fmt,
  85. _encoder_ctx->width,
  86. _encoder_ctx->height,
  87. 1);
  88. _frame->format = _encoder_ctx->pix_fmt;
  89. _frame->width = _encoder_ctx->width;
  90. _frame->height = _encoder_ctx->height;
  91. _y_size = _encoder_ctx->width * _encoder_ctx->height;
  92. _time_base = _encoder_ctx->time_base;
  93. _inited = true;
  94. } while (0);
  95. if (err != AE_NO) {
  96. al_debug("%s,error:%d %lu", err2str(err), ret, GetLastError());
  97. cleanup();
  98. }
  99. if (options)
  100. av_dict_free(&options);
  101. return err;
  102. }
  103. int encoder_video_x264::get_extradata_size()
  104. {
  105. return _encoder_ctx->extradata_size;
  106. }
  107. const uint8_t *encoder_video_x264::get_extradata()
  108. {
  109. return (const uint8_t *) _encoder_ctx->extradata;
  110. }
  111. AVCodecID encoder_video_x264::get_codec_id()
  112. {
  113. if (_inited == false)
  114. return AV_CODEC_ID_NONE;
  115. return _encoder->id;
  116. }
  117. void encoder_video_x264::cleanup()
  118. {
  119. if (_frame)
  120. av_free(_frame);
  121. _frame = NULL;
  122. if (_buff)
  123. av_free(_buff);
  124. _buff = NULL;
  125. if (_encoder)
  126. avcodec_close(_encoder_ctx);
  127. _encoder = NULL;
  128. if (_encoder_ctx)
  129. avcodec_free_context(&_encoder_ctx);
  130. _encoder_ctx = NULL;
  131. }
  132. int encoder_video_x264::encode(AVFrame *frame, AVPacket *packet)
  133. {
  134. int ret = avcodec_send_frame(_encoder_ctx, frame);
  135. if (ret < 0) {
  136. return AE_FFMPEG_ENCODE_FRAME_FAILED;
  137. }
  138. while (ret >= 0) {
  139. av_init_packet(packet);
  140. ret = avcodec_receive_packet(_encoder_ctx, packet);
  141. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  142. break;
  143. }
  144. if (ret < 0) {
  145. return AE_FFMPEG_READ_PACKET_FAILED;
  146. }
  147. if (ret == 0 && _on_data)
  148. _on_data(packet);
  149. av_packet_unref(packet);
  150. }
  151. return AE_NO;
  152. }
  153. void encoder_video_x264::encode_loop()
  154. {
  155. AVPacket *packet = av_packet_alloc();
  156. AVFrame yuv_frame;
  157. int error = AE_NO;
  158. while (_running) {
  159. std::unique_lock<std::mutex> lock(_mutex);
  160. // 改为基于条件的等待,避免固定50ms超时带来的延迟抖动
  161. _cond_var.wait(lock, [this] { return _cond_notify || !_running; });
  162. if (!_running)
  163. break;
  164. while (_ring_buffer->get(_buff, _buff_size, yuv_frame)) {
  165. // Normalize incoming frame timestamps to encoder time_base (1/fps)
  166. // Source pts is in AV_TIME_BASE (microseconds) from capturer
  167. if (yuv_frame.pts != AV_NOPTS_VALUE) {
  168. _frame->pts = av_rescale_q(yuv_frame.pts, AVRational{1, AV_TIME_BASE}, _encoder_ctx->time_base);
  169. } else {
  170. _frame->pts = AV_NOPTS_VALUE;
  171. }
  172. // Keep pkt_dts consistent with pts for no-B-frames encoders
  173. _frame->pkt_dts = _frame->pts;
  174. if ((error = encode(_frame, packet)) != AE_NO) {
  175. if (_on_error)
  176. _on_error(error);
  177. al_fatal("encode 264 packet failed:%d", error);
  178. break;
  179. }
  180. }
  181. _cond_notify = false;
  182. }
  183. av_packet_free(&packet);
  184. }
  185. } // namespace am