encoder_video_x264.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. // 使用超低延迟录制配置
  30. av_dict_set(&options, "preset", UltraLowLatencyRecorderConfig::ULTRA_ENCODER_PRESET, 0);
  31. av_dict_set(&options, "tune", UltraLowLatencyRecorderConfig::ULTRA_ENCODER_TUNE, 0);
  32. av_dict_set(&options, "profile", UltraLowLatencyRecorderConfig::ULTRA_ENCODER_PROFILE, 0);
  33. // 超低延迟x264参数优化
  34. char x264_params[512];
  35. snprintf(x264_params, sizeof(x264_params),
  36. "keyint=%d:min-keyint=%d:no-scenecut=1:rc-lookahead=0:bframes=%d:ref=%d:me=dia:subme=1:trellis=0:8x8dct=0:fast-pskip=1:aq-mode=0:weightb=0:weightp=0:mixed-refs=0:no-chroma-me=1:no-8x8dct=1:partitions=none",
  37. UltraLowLatencyRecorderConfig::ULTRA_VIDEO_GOP_SIZE,
  38. UltraLowLatencyRecorderConfig::ULTRA_VIDEO_GOP_SIZE,
  39. UltraLowLatencyRecorderConfig::ULTRA_VIDEO_BFRAMES,
  40. UltraLowLatencyRecorderConfig::ULTRA_VIDEO_REFS);
  41. av_dict_set(&options, "x264-params", x264_params, 0);
  42. // 质量控制
  43. char crf_str[16];
  44. snprintf(crf_str, sizeof(crf_str), "%d", UltraLowLatencyRecorderConfig::ULTRA_CRF_VALUE);
  45. av_dict_set(&options, "crf", crf_str, 0);
  46. do {
  47. _encoder = avcodec_find_encoder(AV_CODEC_ID_H264);
  48. if (!_encoder) {
  49. err = AE_FFMPEG_FIND_ENCODER_FAILED;
  50. break;
  51. }
  52. _encoder_ctx = avcodec_alloc_context3(_encoder);
  53. if (!_encoder_ctx) {
  54. err = AE_FFMPEG_ALLOC_CONTEXT_FAILED;
  55. break;
  56. }
  57. _encoder_ctx->codec_id = AV_CODEC_ID_H264;
  58. _encoder_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
  59. _encoder_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
  60. _encoder_ctx->width = pic_width;
  61. _encoder_ctx->height = pic_height;
  62. _encoder_ctx->time_base.num = 1;
  63. _encoder_ctx->time_base.den = frame_rate;
  64. _encoder_ctx->framerate = {frame_rate, 1};
  65. _encoder_ctx->bit_rate = UltraLowLatencyRecorderConfig::ULTRA_VIDEO_BITRATE;
  66. // 使用超低延迟GOP设置
  67. _encoder_ctx->gop_size = UltraLowLatencyRecorderConfig::ULTRA_VIDEO_GOP_SIZE;
  68. // 超低延迟量化参数
  69. _encoder_ctx->qmin = 18; // 提高最小质量
  70. _encoder_ctx->qmax = 32; // 控制最大量化
  71. // 设置CRF值
  72. _encoder_ctx->global_quality = UltraLowLatencyRecorderConfig::ULTRA_CRF_VALUE * FF_QP2LAMBDA;
  73. _encoder_ctx->max_b_frames = UltraLowLatencyRecorderConfig::ULTRA_VIDEO_BFRAMES; // 禁用B帧
  74. // 超低延迟设置
  75. _encoder_ctx->delay = 0;
  76. _encoder_ctx->thread_count = UltraLowLatencyRecorderConfig::ULTRA_ENCODER_THREAD_COUNT;
  77. _encoder_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  78. ret = avcodec_open2(_encoder_ctx, _encoder, &options);
  79. if (ret != 0) {
  80. err = AE_FFMPEG_OPEN_CODEC_FAILED;
  81. break;
  82. }
  83. _frame = av_frame_alloc();
  84. _buff_size = av_image_get_buffer_size(_encoder_ctx->pix_fmt,
  85. _encoder_ctx->width,
  86. _encoder_ctx->height,
  87. 1);
  88. _buff = (uint8_t *) av_malloc(_buff_size);
  89. if (!_buff) {
  90. break;
  91. }
  92. av_image_fill_arrays(_frame->data,
  93. _frame->linesize,
  94. _buff,
  95. _encoder_ctx->pix_fmt,
  96. _encoder_ctx->width,
  97. _encoder_ctx->height,
  98. 1);
  99. _frame->format = _encoder_ctx->pix_fmt;
  100. _frame->width = _encoder_ctx->width;
  101. _frame->height = _encoder_ctx->height;
  102. _y_size = _encoder_ctx->width * _encoder_ctx->height;
  103. _time_base = _encoder_ctx->time_base;
  104. _inited = true;
  105. } while (0);
  106. if (err != AE_NO) {
  107. al_debug("%s,error:%d %lu", err2str(err), ret, GetLastError());
  108. cleanup();
  109. }
  110. if (options)
  111. av_dict_free(&options);
  112. return err;
  113. }
  114. int encoder_video_x264::get_extradata_size()
  115. {
  116. return _encoder_ctx->extradata_size;
  117. }
  118. const uint8_t *encoder_video_x264::get_extradata()
  119. {
  120. return (const uint8_t *) _encoder_ctx->extradata;
  121. }
  122. AVCodecID encoder_video_x264::get_codec_id()
  123. {
  124. if (_inited == false)
  125. return AV_CODEC_ID_NONE;
  126. return _encoder->id;
  127. }
  128. void encoder_video_x264::cleanup()
  129. {
  130. if (_frame)
  131. av_free(_frame);
  132. _frame = NULL;
  133. if (_buff)
  134. av_free(_buff);
  135. _buff = NULL;
  136. if (_encoder)
  137. avcodec_close(_encoder_ctx);
  138. _encoder = NULL;
  139. if (_encoder_ctx)
  140. avcodec_free_context(&_encoder_ctx);
  141. _encoder_ctx = NULL;
  142. }
  143. int encoder_video_x264::encode(AVFrame *frame, AVPacket *packet)
  144. {
  145. int ret = avcodec_send_frame(_encoder_ctx, frame);
  146. if (ret < 0) {
  147. return AE_FFMPEG_ENCODE_FRAME_FAILED;
  148. }
  149. while (ret >= 0) {
  150. av_init_packet(packet);
  151. ret = avcodec_receive_packet(_encoder_ctx, packet);
  152. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  153. break;
  154. }
  155. if (ret < 0) {
  156. return AE_FFMPEG_READ_PACKET_FAILED;
  157. }
  158. if (ret == 0 && _on_data)
  159. _on_data(packet);
  160. av_packet_unref(packet);
  161. }
  162. return AE_NO;
  163. }
  164. void encoder_video_x264::encode_loop()
  165. {
  166. AVPacket *packet = av_packet_alloc();
  167. AVFrame yuv_frame;
  168. int error = AE_NO;
  169. while (_running) {
  170. std::unique_lock<std::mutex> lock(_mutex);
  171. // 恢复最激进的低延迟处理
  172. if (!_cond_notify && _ring_buffer->get_pending_frames() == 0) {
  173. // 使用最短等待时间
  174. _cond_var.wait_for(lock, std::chrono::milliseconds(1), [this] { return _cond_notify || !_running; });
  175. }
  176. if (!_running)
  177. break;
  178. // 立即处理所有可用帧,不限制批处理大小
  179. while (_ring_buffer->get(_buff, _buff_size, yuv_frame)) {
  180. // Normalize incoming frame timestamps to encoder time_base (1/fps)
  181. // Source pts is in AV_TIME_BASE (microseconds) from capturer
  182. if (yuv_frame.pts != AV_NOPTS_VALUE) {
  183. _frame->pts = av_rescale_q(yuv_frame.pts, AVRational{1, AV_TIME_BASE}, _encoder_ctx->time_base);
  184. } else {
  185. _frame->pts = AV_NOPTS_VALUE;
  186. }
  187. // Keep pkt_dts consistent with pts for no-B-frames encoders
  188. _frame->pkt_dts = _frame->pts;
  189. if ((error = encode(_frame, packet)) != AE_NO) {
  190. if (_on_error)
  191. _on_error(error);
  192. al_fatal("encode 264 packet failed:%d", error);
  193. break;
  194. }
  195. }
  196. _cond_notify = false;
  197. }
  198. av_packet_free(&packet);
  199. }
  200. } // namespace am