You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1046 lines
34KB

  1. /*
  2. * Rate control for video encoders
  3. *
  4. * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * Libav is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * Rate control for video encoders.
  25. */
  26. #include "libavutil/attributes.h"
  27. #include "libavutil/internal.h"
  28. #include "avcodec.h"
  29. #include "internal.h"
  30. #include "ratecontrol.h"
  31. #include "mpegutils.h"
  32. #include "mpegvideo.h"
  33. #include "libavutil/eval.h"
  34. #undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
  35. #include <assert.h>
  36. #ifndef M_E
  37. #define M_E 2.718281828
  38. #endif
  39. static int init_pass2(MpegEncContext *s);
  40. static double get_qscale(MpegEncContext *s, RateControlEntry *rce,
  41. double rate_factor, int frame_num);
  42. void ff_write_pass1_stats(MpegEncContext *s)
  43. {
  44. snprintf(s->avctx->stats_out, 256,
  45. "in:%d out:%d type:%d q:%d itex:%d ptex:%d mv:%d misc:%d "
  46. "fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d;\n",
  47. s->current_picture_ptr->f->display_picture_number,
  48. s->current_picture_ptr->f->coded_picture_number,
  49. s->pict_type,
  50. s->current_picture.f->quality,
  51. s->i_tex_bits,
  52. s->p_tex_bits,
  53. s->mv_bits,
  54. s->misc_bits,
  55. s->f_code,
  56. s->b_code,
  57. s->current_picture.mc_mb_var_sum,
  58. s->current_picture.mb_var_sum,
  59. s->i_count, s->skip_count,
  60. s->header_bits);
  61. }
  62. static inline double qp2bits(RateControlEntry *rce, double qp)
  63. {
  64. if (qp <= 0.0) {
  65. av_log(NULL, AV_LOG_ERROR, "qp<=0.0\n");
  66. }
  67. return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / qp;
  68. }
  69. static inline double bits2qp(RateControlEntry *rce, double bits)
  70. {
  71. if (bits < 0.9) {
  72. av_log(NULL, AV_LOG_ERROR, "bits<0.9\n");
  73. }
  74. return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / bits;
  75. }
  76. av_cold int ff_rate_control_init(MpegEncContext *s)
  77. {
  78. RateControlContext *rcc = &s->rc_context;
  79. int i, res;
  80. static const char * const const_names[] = {
  81. "PI",
  82. "E",
  83. "iTex",
  84. "pTex",
  85. "tex",
  86. "mv",
  87. "fCode",
  88. "iCount",
  89. "mcVar",
  90. "var",
  91. "isI",
  92. "isP",
  93. "isB",
  94. "avgQP",
  95. "qComp",
  96. "avgIITex",
  97. "avgPITex",
  98. "avgPPTex",
  99. "avgBPTex",
  100. "avgTex",
  101. NULL
  102. };
  103. static double (* const func1[])(void *, double) = {
  104. (void *)bits2qp,
  105. (void *)qp2bits,
  106. NULL
  107. };
  108. static const char * const func1_names[] = {
  109. "bits2qp",
  110. "qp2bits",
  111. NULL
  112. };
  113. emms_c();
  114. res = av_expr_parse(&rcc->rc_eq_eval,
  115. s->rc_eq ? s->rc_eq : "tex^qComp",
  116. const_names, func1_names, func1,
  117. NULL, NULL, 0, s->avctx);
  118. if (res < 0) {
  119. av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->rc_eq);
  120. return res;
  121. }
  122. #if FF_API_RC_STRATEGY
  123. FF_DISABLE_DEPRECATION_WARNINGS
  124. if (!s->rc_strategy)
  125. s->rc_strategy = s->avctx->rc_strategy;
  126. FF_ENABLE_DEPRECATION_WARNINGS
  127. #endif
  128. for (i = 0; i < 5; i++) {
  129. rcc->pred[i].coeff = FF_QP2LAMBDA * 7.0;
  130. rcc->pred[i].count = 1.0;
  131. rcc->pred[i].decay = 0.4;
  132. rcc->i_cplx_sum [i] =
  133. rcc->p_cplx_sum [i] =
  134. rcc->mv_bits_sum[i] =
  135. rcc->qscale_sum [i] =
  136. rcc->frame_count[i] = 1; // 1 is better because of 1/0 and such
  137. rcc->last_qscale_for[i] = FF_QP2LAMBDA * 5;
  138. }
  139. rcc->buffer_index = s->avctx->rc_initial_buffer_occupancy;
  140. if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  141. int i;
  142. char *p;
  143. /* find number of pics */
  144. p = s->avctx->stats_in;
  145. for (i = -1; p; i++)
  146. p = strchr(p + 1, ';');
  147. i += s->max_b_frames;
  148. if (i <= 0 || i >= INT_MAX / sizeof(RateControlEntry))
  149. return -1;
  150. rcc->entry = av_mallocz(i * sizeof(RateControlEntry));
  151. rcc->num_entries = i;
  152. if (!rcc->entry)
  153. return AVERROR(ENOMEM);
  154. /* init all to skipped P-frames
  155. * (with B-frames we might have a not encoded frame at the end FIXME) */
  156. for (i = 0; i < rcc->num_entries; i++) {
  157. RateControlEntry *rce = &rcc->entry[i];
  158. rce->pict_type = rce->new_pict_type = AV_PICTURE_TYPE_P;
  159. rce->qscale = rce->new_qscale = FF_QP2LAMBDA * 2;
  160. rce->misc_bits = s->mb_num + 10;
  161. rce->mb_var_sum = s->mb_num * 100;
  162. }
  163. /* read stats */
  164. p = s->avctx->stats_in;
  165. for (i = 0; i < rcc->num_entries - s->max_b_frames; i++) {
  166. RateControlEntry *rce;
  167. int picture_number;
  168. int e;
  169. char *next;
  170. next = strchr(p, ';');
  171. if (next) {
  172. (*next) = 0; // sscanf is unbelievably slow on looong strings // FIXME copy / do not write
  173. next++;
  174. }
  175. e = sscanf(p, " in:%d ", &picture_number);
  176. assert(picture_number >= 0);
  177. assert(picture_number < rcc->num_entries);
  178. rce = &rcc->entry[picture_number];
  179. e += sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d",
  180. &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits,
  181. &rce->mv_bits, &rce->misc_bits,
  182. &rce->f_code, &rce->b_code,
  183. &rce->mc_mb_var_sum, &rce->mb_var_sum,
  184. &rce->i_count, &rce->skip_count, &rce->header_bits);
  185. if (e != 14) {
  186. av_log(s->avctx, AV_LOG_ERROR,
  187. "statistics are damaged at line %d, parser out=%d\n",
  188. i, e);
  189. return -1;
  190. }
  191. p = next;
  192. }
  193. if (init_pass2(s) < 0) {
  194. ff_rate_control_uninit(s);
  195. return -1;
  196. }
  197. // FIXME maybe move to end
  198. if ((s->avctx->flags & AV_CODEC_FLAG_PASS2) && s->rc_strategy == 1) {
  199. #if CONFIG_LIBXVID
  200. return ff_xvid_rate_control_init(s);
  201. #else
  202. av_log(s->avctx, AV_LOG_ERROR,
  203. "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
  204. return -1;
  205. #endif
  206. }
  207. }
  208. if (!(s->avctx->flags & AV_CODEC_FLAG_PASS2)) {
  209. rcc->short_term_qsum = 0.001;
  210. rcc->short_term_qcount = 0.001;
  211. rcc->pass1_rc_eq_output_sum = 0.001;
  212. rcc->pass1_wanted_bits = 0.001;
  213. if (s->avctx->qblur > 1.0) {
  214. av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
  215. return -1;
  216. }
  217. /* init stuff with the user specified complexity */
  218. if (s->rc_initial_cplx) {
  219. for (i = 0; i < 60 * 30; i++) {
  220. double bits = s->rc_initial_cplx * (i / 10000.0 + 1.0) * s->mb_num;
  221. RateControlEntry rce;
  222. if (i % ((s->gop_size + 3) / 4) == 0)
  223. rce.pict_type = AV_PICTURE_TYPE_I;
  224. else if (i % (s->max_b_frames + 1))
  225. rce.pict_type = AV_PICTURE_TYPE_B;
  226. else
  227. rce.pict_type = AV_PICTURE_TYPE_P;
  228. rce.new_pict_type = rce.pict_type;
  229. rce.mc_mb_var_sum = bits * s->mb_num / 100000;
  230. rce.mb_var_sum = s->mb_num;
  231. rce.qscale = FF_QP2LAMBDA * 2;
  232. rce.f_code = 2;
  233. rce.b_code = 1;
  234. rce.misc_bits = 1;
  235. if (s->pict_type == AV_PICTURE_TYPE_I) {
  236. rce.i_count = s->mb_num;
  237. rce.i_tex_bits = bits;
  238. rce.p_tex_bits = 0;
  239. rce.mv_bits = 0;
  240. } else {
  241. rce.i_count = 0; // FIXME we do know this approx
  242. rce.i_tex_bits = 0;
  243. rce.p_tex_bits = bits * 0.9;
  244. rce.mv_bits = bits * 0.1;
  245. }
  246. rcc->i_cplx_sum[rce.pict_type] += rce.i_tex_bits * rce.qscale;
  247. rcc->p_cplx_sum[rce.pict_type] += rce.p_tex_bits * rce.qscale;
  248. rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;
  249. rcc->frame_count[rce.pict_type]++;
  250. get_qscale(s, &rce, rcc->pass1_wanted_bits / rcc->pass1_rc_eq_output_sum, i);
  251. // FIXME misbehaves a little for variable fps
  252. rcc->pass1_wanted_bits += s->bit_rate / (1 / av_q2d(s->avctx->time_base));
  253. }
  254. }
  255. }
  256. return 0;
  257. }
  258. av_cold void ff_rate_control_uninit(MpegEncContext *s)
  259. {
  260. RateControlContext *rcc = &s->rc_context;
  261. emms_c();
  262. av_expr_free(rcc->rc_eq_eval);
  263. av_freep(&rcc->entry);
  264. #if CONFIG_LIBXVID
  265. if ((s->avctx->flags & AV_CODEC_FLAG_PASS2) && s->rc_strategy == 1)
  266. ff_xvid_rate_control_uninit(s);
  267. #endif
  268. }
  269. int ff_vbv_update(MpegEncContext *s, int frame_size)
  270. {
  271. RateControlContext *rcc = &s->rc_context;
  272. const double fps = 1 / av_q2d(s->avctx->time_base);
  273. const int buffer_size = s->avctx->rc_buffer_size;
  274. const double min_rate = s->avctx->rc_min_rate / fps;
  275. const double max_rate = s->avctx->rc_max_rate / fps;
  276. ff_dlog(s, "%d %f %d %f %f\n",
  277. buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
  278. if (buffer_size) {
  279. int left;
  280. rcc->buffer_index -= frame_size;
  281. if (rcc->buffer_index < 0) {
  282. av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
  283. rcc->buffer_index = 0;
  284. }
  285. left = buffer_size - rcc->buffer_index - 1;
  286. rcc->buffer_index += av_clip(left, min_rate, max_rate);
  287. if (rcc->buffer_index > buffer_size) {
  288. int stuffing = ceil((rcc->buffer_index - buffer_size) / 8);
  289. if (stuffing < 4 && s->codec_id == AV_CODEC_ID_MPEG4)
  290. stuffing = 4;
  291. rcc->buffer_index -= 8 * stuffing;
  292. if (s->avctx->debug & FF_DEBUG_RC)
  293. av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
  294. return stuffing;
  295. }
  296. }
  297. return 0;
  298. }
  299. /**
  300. * Modify the bitrate curve from pass1 for one frame.
  301. */
  302. static double get_qscale(MpegEncContext *s, RateControlEntry *rce,
  303. double rate_factor, int frame_num)
  304. {
  305. RateControlContext *rcc = &s->rc_context;
  306. AVCodecContext *a = s->avctx;
  307. const int pict_type = rce->new_pict_type;
  308. const double mb_num = s->mb_num;
  309. double q, bits;
  310. int i;
  311. double const_values[] = {
  312. M_PI,
  313. M_E,
  314. rce->i_tex_bits * rce->qscale,
  315. rce->p_tex_bits * rce->qscale,
  316. (rce->i_tex_bits + rce->p_tex_bits) * (double)rce->qscale,
  317. rce->mv_bits / mb_num,
  318. rce->pict_type == AV_PICTURE_TYPE_B ? (rce->f_code + rce->b_code) * 0.5 : rce->f_code,
  319. rce->i_count / mb_num,
  320. rce->mc_mb_var_sum / mb_num,
  321. rce->mb_var_sum / mb_num,
  322. rce->pict_type == AV_PICTURE_TYPE_I,
  323. rce->pict_type == AV_PICTURE_TYPE_P,
  324. rce->pict_type == AV_PICTURE_TYPE_B,
  325. rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
  326. a->qcompress,
  327. rcc->i_cplx_sum[AV_PICTURE_TYPE_I] / (double)rcc->frame_count[AV_PICTURE_TYPE_I],
  328. rcc->i_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
  329. rcc->p_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
  330. rcc->p_cplx_sum[AV_PICTURE_TYPE_B] / (double)rcc->frame_count[AV_PICTURE_TYPE_B],
  331. (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
  332. 0
  333. };
  334. bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
  335. if (isnan(bits)) {
  336. av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->rc_eq);
  337. return -1;
  338. }
  339. rcc->pass1_rc_eq_output_sum += bits;
  340. bits *= rate_factor;
  341. if (bits < 0.0)
  342. bits = 0.0;
  343. bits += 1.0; // avoid 1/0 issues
  344. /* user override */
  345. for (i = 0; i < s->avctx->rc_override_count; i++) {
  346. RcOverride *rco = s->avctx->rc_override;
  347. if (rco[i].start_frame > frame_num)
  348. continue;
  349. if (rco[i].end_frame < frame_num)
  350. continue;
  351. if (rco[i].qscale)
  352. bits = qp2bits(rce, rco[i].qscale); // FIXME move at end to really force it?
  353. else
  354. bits *= rco[i].quality_factor;
  355. }
  356. q = bits2qp(rce, bits);
  357. /* I/B difference */
  358. if (pict_type == AV_PICTURE_TYPE_I && s->avctx->i_quant_factor < 0.0)
  359. q = -q * s->avctx->i_quant_factor + s->avctx->i_quant_offset;
  360. else if (pict_type == AV_PICTURE_TYPE_B && s->avctx->b_quant_factor < 0.0)
  361. q = -q * s->avctx->b_quant_factor + s->avctx->b_quant_offset;
  362. if (q < 1)
  363. q = 1;
  364. return q;
  365. }
  366. static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q)
  367. {
  368. RateControlContext *rcc = &s->rc_context;
  369. AVCodecContext *a = s->avctx;
  370. const int pict_type = rce->new_pict_type;
  371. const double last_p_q = rcc->last_qscale_for[AV_PICTURE_TYPE_P];
  372. const double last_non_b_q = rcc->last_qscale_for[rcc->last_non_b_pict_type];
  373. if (pict_type == AV_PICTURE_TYPE_I &&
  374. (a->i_quant_factor > 0.0 || rcc->last_non_b_pict_type == AV_PICTURE_TYPE_P))
  375. q = last_p_q * FFABS(a->i_quant_factor) + a->i_quant_offset;
  376. else if (pict_type == AV_PICTURE_TYPE_B &&
  377. a->b_quant_factor > 0.0)
  378. q = last_non_b_q * a->b_quant_factor + a->b_quant_offset;
  379. if (q < 1)
  380. q = 1;
  381. /* last qscale / qdiff stuff */
  382. if (rcc->last_non_b_pict_type == pict_type || pict_type != AV_PICTURE_TYPE_I) {
  383. double last_q = rcc->last_qscale_for[pict_type];
  384. const int maxdiff = FF_QP2LAMBDA * a->max_qdiff;
  385. if (q > last_q + maxdiff)
  386. q = last_q + maxdiff;
  387. else if (q < last_q - maxdiff)
  388. q = last_q - maxdiff;
  389. }
  390. rcc->last_qscale_for[pict_type] = q; // Note we cannot do that after blurring
  391. if (pict_type != AV_PICTURE_TYPE_B)
  392. rcc->last_non_b_pict_type = pict_type;
  393. return q;
  394. }
  395. /**
  396. * Get the qmin & qmax for pict_type.
  397. */
  398. static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type)
  399. {
  400. int qmin = s->lmin;
  401. int qmax = s->lmax;
  402. assert(qmin <= qmax);
  403. switch (pict_type) {
  404. case AV_PICTURE_TYPE_B:
  405. qmin = (int)(qmin * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset + 0.5);
  406. qmax = (int)(qmax * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset + 0.5);
  407. break;
  408. case AV_PICTURE_TYPE_I:
  409. qmin = (int)(qmin * FFABS(s->avctx->i_quant_factor) + s->avctx->i_quant_offset + 0.5);
  410. qmax = (int)(qmax * FFABS(s->avctx->i_quant_factor) + s->avctx->i_quant_offset + 0.5);
  411. break;
  412. }
  413. qmin = av_clip(qmin, 1, FF_LAMBDA_MAX);
  414. qmax = av_clip(qmax, 1, FF_LAMBDA_MAX);
  415. if (qmax < qmin)
  416. qmax = qmin;
  417. *qmin_ret = qmin;
  418. *qmax_ret = qmax;
  419. }
  420. static double modify_qscale(MpegEncContext *s, RateControlEntry *rce,
  421. double q, int frame_num)
  422. {
  423. RateControlContext *rcc = &s->rc_context;
  424. const double buffer_size = s->avctx->rc_buffer_size;
  425. const double fps = 1 / av_q2d(s->avctx->time_base);
  426. const double min_rate = s->avctx->rc_min_rate / fps;
  427. const double max_rate = s->avctx->rc_max_rate / fps;
  428. const int pict_type = rce->new_pict_type;
  429. int qmin, qmax;
  430. get_qminmax(&qmin, &qmax, s, pict_type);
  431. /* modulation */
  432. if (s->rc_qmod_freq &&
  433. frame_num % s->rc_qmod_freq == 0 &&
  434. pict_type == AV_PICTURE_TYPE_P)
  435. q *= s->rc_qmod_amp;
  436. /* buffer overflow/underflow protection */
  437. if (buffer_size) {
  438. double expected_size = rcc->buffer_index;
  439. double q_limit;
  440. if (min_rate) {
  441. double d = 2 * (buffer_size - expected_size) / buffer_size;
  442. if (d > 1.0)
  443. d = 1.0;
  444. else if (d < 0.0001)
  445. d = 0.0001;
  446. q *= pow(d, 1.0 / s->rc_buffer_aggressivity);
  447. q_limit = bits2qp(rce,
  448. FFMAX((min_rate - buffer_size + rcc->buffer_index) *
  449. s->avctx->rc_min_vbv_overflow_use, 1));
  450. if (q > q_limit) {
  451. if (s->avctx->debug & FF_DEBUG_RC)
  452. av_log(s->avctx, AV_LOG_DEBUG,
  453. "limiting QP %f -> %f\n", q, q_limit);
  454. q = q_limit;
  455. }
  456. }
  457. if (max_rate) {
  458. double d = 2 * expected_size / buffer_size;
  459. if (d > 1.0)
  460. d = 1.0;
  461. else if (d < 0.0001)
  462. d = 0.0001;
  463. q /= pow(d, 1.0 / s->rc_buffer_aggressivity);
  464. q_limit = bits2qp(rce,
  465. FFMAX(rcc->buffer_index *
  466. s->avctx->rc_max_available_vbv_use,
  467. 1));
  468. if (q < q_limit) {
  469. if (s->avctx->debug & FF_DEBUG_RC)
  470. av_log(s->avctx, AV_LOG_DEBUG,
  471. "limiting QP %f -> %f\n", q, q_limit);
  472. q = q_limit;
  473. }
  474. }
  475. }
  476. ff_dlog(s, "q:%f max:%f min:%f size:%f index:%f agr:%f\n",
  477. q, max_rate, min_rate, buffer_size, rcc->buffer_index,
  478. s->rc_buffer_aggressivity);
  479. if (s->rc_qsquish == 0.0 || qmin == qmax) {
  480. if (q < qmin)
  481. q = qmin;
  482. else if (q > qmax)
  483. q = qmax;
  484. } else {
  485. double min2 = log(qmin);
  486. double max2 = log(qmax);
  487. q = log(q);
  488. q = (q - min2) / (max2 - min2) - 0.5;
  489. q *= -4.0;
  490. q = 1.0 / (1.0 + exp(q));
  491. q = q * (max2 - min2) + min2;
  492. q = exp(q);
  493. }
  494. return q;
  495. }
  496. // ----------------------------------
  497. // 1 Pass Code
  498. static double predict_size(Predictor *p, double q, double var)
  499. {
  500. return p->coeff * var / (q * p->count);
  501. }
  502. static void update_predictor(Predictor *p, double q, double var, double size)
  503. {
  504. double new_coeff = size * q / (var + 1);
  505. if (var < 10)
  506. return;
  507. p->count *= p->decay;
  508. p->coeff *= p->decay;
  509. p->count++;
  510. p->coeff += new_coeff;
  511. }
  512. static void adaptive_quantization(MpegEncContext *s, double q)
  513. {
  514. int i;
  515. const float lumi_masking = s->avctx->lumi_masking / (128.0 * 128.0);
  516. const float dark_masking = s->avctx->dark_masking / (128.0 * 128.0);
  517. const float temp_cplx_masking = s->avctx->temporal_cplx_masking;
  518. const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
  519. const float p_masking = s->avctx->p_masking;
  520. const float border_masking = s->border_masking;
  521. float bits_sum = 0.0;
  522. float cplx_sum = 0.0;
  523. float *cplx_tab = s->cplx_tab;
  524. float *bits_tab = s->bits_tab;
  525. const int qmin = s->avctx->mb_lmin;
  526. const int qmax = s->avctx->mb_lmax;
  527. Picture *const pic = &s->current_picture;
  528. const int mb_width = s->mb_width;
  529. const int mb_height = s->mb_height;
  530. for (i = 0; i < s->mb_num; i++) {
  531. const int mb_xy = s->mb_index2xy[i];
  532. float temp_cplx = sqrt(pic->mc_mb_var[mb_xy]); // FIXME merge in pow()
  533. float spat_cplx = sqrt(pic->mb_var[mb_xy]);
  534. const int lumi = pic->mb_mean[mb_xy];
  535. float bits, cplx, factor;
  536. int mb_x = mb_xy % s->mb_stride;
  537. int mb_y = mb_xy / s->mb_stride;
  538. int mb_distance;
  539. float mb_factor = 0.0;
  540. if (spat_cplx < 4)
  541. spat_cplx = 4; // FIXME fine-tune
  542. if (temp_cplx < 4)
  543. temp_cplx = 4; // FIXME fine-tune
  544. if ((s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_INTRA)) { // FIXME hq mode
  545. cplx = spat_cplx;
  546. factor = 1.0 + p_masking;
  547. } else {
  548. cplx = temp_cplx;
  549. factor = pow(temp_cplx, -temp_cplx_masking);
  550. }
  551. factor *= pow(spat_cplx, -spatial_cplx_masking);
  552. if (lumi > 127)
  553. factor *= (1.0 - (lumi - 128) * (lumi - 128) * lumi_masking);
  554. else
  555. factor *= (1.0 - (lumi - 128) * (lumi - 128) * dark_masking);
  556. if (mb_x < mb_width / 5) {
  557. mb_distance = mb_width / 5 - mb_x;
  558. mb_factor = (float)mb_distance / (float)(mb_width / 5);
  559. } else if (mb_x > 4 * mb_width / 5) {
  560. mb_distance = mb_x - 4 * mb_width / 5;
  561. mb_factor = (float)mb_distance / (float)(mb_width / 5);
  562. }
  563. if (mb_y < mb_height / 5) {
  564. mb_distance = mb_height / 5 - mb_y;
  565. mb_factor = FFMAX(mb_factor,
  566. (float)mb_distance / (float)(mb_height / 5));
  567. } else if (mb_y > 4 * mb_height / 5) {
  568. mb_distance = mb_y - 4 * mb_height / 5;
  569. mb_factor = FFMAX(mb_factor,
  570. (float)mb_distance / (float)(mb_height / 5));
  571. }
  572. factor *= 1.0 - border_masking * mb_factor;
  573. if (factor < 0.00001)
  574. factor = 0.00001;
  575. bits = cplx * factor;
  576. cplx_sum += cplx;
  577. bits_sum += bits;
  578. cplx_tab[i] = cplx;
  579. bits_tab[i] = bits;
  580. }
  581. /* handle qmin/qmax clipping */
  582. if (s->mpv_flags & FF_MPV_FLAG_NAQ) {
  583. float factor = bits_sum / cplx_sum;
  584. for (i = 0; i < s->mb_num; i++) {
  585. float newq = q * cplx_tab[i] / bits_tab[i];
  586. newq *= factor;
  587. if (newq > qmax) {
  588. bits_sum -= bits_tab[i];
  589. cplx_sum -= cplx_tab[i] * q / qmax;
  590. } else if (newq < qmin) {
  591. bits_sum -= bits_tab[i];
  592. cplx_sum -= cplx_tab[i] * q / qmin;
  593. }
  594. }
  595. if (bits_sum < 0.001)
  596. bits_sum = 0.001;
  597. if (cplx_sum < 0.001)
  598. cplx_sum = 0.001;
  599. }
  600. for (i = 0; i < s->mb_num; i++) {
  601. const int mb_xy = s->mb_index2xy[i];
  602. float newq = q * cplx_tab[i] / bits_tab[i];
  603. int intq;
  604. if (s->mpv_flags & FF_MPV_FLAG_NAQ) {
  605. newq *= bits_sum / cplx_sum;
  606. }
  607. intq = (int)(newq + 0.5);
  608. if (intq > qmax)
  609. intq = qmax;
  610. else if (intq < qmin)
  611. intq = qmin;
  612. s->lambda_table[mb_xy] = intq;
  613. }
  614. }
  615. void ff_get_2pass_fcode(MpegEncContext *s)
  616. {
  617. RateControlContext *rcc = &s->rc_context;
  618. RateControlEntry *rce = &rcc->entry[s->picture_number];
  619. s->f_code = rce->f_code;
  620. s->b_code = rce->b_code;
  621. }
  622. // FIXME rd or at least approx for dquant
  623. float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
  624. {
  625. float q;
  626. int qmin, qmax;
  627. float br_compensation;
  628. double diff;
  629. double short_term_q;
  630. double fps;
  631. int picture_number = s->picture_number;
  632. int64_t wanted_bits;
  633. RateControlContext *rcc = &s->rc_context;
  634. AVCodecContext *a = s->avctx;
  635. RateControlEntry local_rce, *rce;
  636. double bits;
  637. double rate_factor;
  638. int var;
  639. const int pict_type = s->pict_type;
  640. Picture * const pic = &s->current_picture;
  641. emms_c();
  642. #if CONFIG_LIBXVID
  643. if ((s->avctx->flags & AV_CODEC_FLAG_PASS2) && s->rc_strategy == 1)
  644. return ff_xvid_rate_estimate_qscale(s, dry_run);
  645. #endif
  646. get_qminmax(&qmin, &qmax, s, pict_type);
  647. fps = 1 / av_q2d(s->avctx->time_base);
  648. /* update predictors */
  649. if (picture_number > 2 && !dry_run) {
  650. const int last_var = s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum
  651. : rcc->last_mc_mb_var_sum;
  652. update_predictor(&rcc->pred[s->last_pict_type],
  653. rcc->last_qscale,
  654. sqrt(last_var), s->frame_bits);
  655. }
  656. if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  657. assert(picture_number >= 0);
  658. assert(picture_number < rcc->num_entries);
  659. rce = &rcc->entry[picture_number];
  660. wanted_bits = rce->expected_bits;
  661. } else {
  662. Picture *dts_pic;
  663. rce = &local_rce;
  664. /* FIXME add a dts field to AVFrame and ensure it is set and use it
  665. * here instead of reordering but the reordering is simpler for now
  666. * until H.264 B-pyramid must be handled. */
  667. if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
  668. dts_pic = s->current_picture_ptr;
  669. else
  670. dts_pic = s->last_picture_ptr;
  671. if (!dts_pic || dts_pic->f->pts == AV_NOPTS_VALUE)
  672. wanted_bits = (uint64_t)(s->bit_rate * (double)picture_number / fps);
  673. else
  674. wanted_bits = (uint64_t)(s->bit_rate * (double)dts_pic->f->pts / fps);
  675. }
  676. diff = s->total_bits - wanted_bits;
  677. br_compensation = (a->bit_rate_tolerance - diff) / a->bit_rate_tolerance;
  678. if (br_compensation <= 0.0)
  679. br_compensation = 0.001;
  680. var = pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
  681. short_term_q = 0; /* avoid warning */
  682. if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  683. if (pict_type != AV_PICTURE_TYPE_I)
  684. assert(pict_type == rce->new_pict_type);
  685. q = rce->new_qscale / br_compensation;
  686. ff_dlog(s, "%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale,
  687. br_compensation, s->frame_bits, var, pict_type);
  688. } else {
  689. rce->pict_type =
  690. rce->new_pict_type = pict_type;
  691. rce->mc_mb_var_sum = pic->mc_mb_var_sum;
  692. rce->mb_var_sum = pic->mb_var_sum;
  693. rce->qscale = FF_QP2LAMBDA * 2;
  694. rce->f_code = s->f_code;
  695. rce->b_code = s->b_code;
  696. rce->misc_bits = 1;
  697. bits = predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
  698. if (pict_type == AV_PICTURE_TYPE_I) {
  699. rce->i_count = s->mb_num;
  700. rce->i_tex_bits = bits;
  701. rce->p_tex_bits = 0;
  702. rce->mv_bits = 0;
  703. } else {
  704. rce->i_count = 0; // FIXME we do know this approx
  705. rce->i_tex_bits = 0;
  706. rce->p_tex_bits = bits * 0.9;
  707. rce->mv_bits = bits * 0.1;
  708. }
  709. rcc->i_cplx_sum[pict_type] += rce->i_tex_bits * rce->qscale;
  710. rcc->p_cplx_sum[pict_type] += rce->p_tex_bits * rce->qscale;
  711. rcc->mv_bits_sum[pict_type] += rce->mv_bits;
  712. rcc->frame_count[pict_type]++;
  713. bits = rce->i_tex_bits + rce->p_tex_bits;
  714. rate_factor = rcc->pass1_wanted_bits /
  715. rcc->pass1_rc_eq_output_sum * br_compensation;
  716. q = get_qscale(s, rce, rate_factor, picture_number);
  717. if (q < 0)
  718. return -1;
  719. assert(q > 0.0);
  720. q = get_diff_limited_q(s, rce, q);
  721. assert(q > 0.0);
  722. // FIXME type dependent blur like in 2-pass
  723. if (pict_type == AV_PICTURE_TYPE_P || s->intra_only) {
  724. rcc->short_term_qsum *= a->qblur;
  725. rcc->short_term_qcount *= a->qblur;
  726. rcc->short_term_qsum += q;
  727. rcc->short_term_qcount++;
  728. q = short_term_q = rcc->short_term_qsum / rcc->short_term_qcount;
  729. }
  730. assert(q > 0.0);
  731. q = modify_qscale(s, rce, q, picture_number);
  732. rcc->pass1_wanted_bits += s->bit_rate / fps;
  733. assert(q > 0.0);
  734. }
  735. if (s->avctx->debug & FF_DEBUG_RC) {
  736. av_log(s->avctx, AV_LOG_DEBUG,
  737. "%c qp:%d<%2.1f<%d %d want:%d total:%d comp:%f st_q:%2.2f "
  738. "size:%d var:%d/%d br:%d fps:%d\n",
  739. av_get_picture_type_char(pict_type),
  740. qmin, q, qmax, picture_number,
  741. (int)wanted_bits / 1000, (int)s->total_bits / 1000,
  742. br_compensation, short_term_q, s->frame_bits,
  743. pic->mb_var_sum, pic->mc_mb_var_sum,
  744. s->bit_rate / 1000, (int)fps);
  745. }
  746. if (q < qmin)
  747. q = qmin;
  748. else if (q > qmax)
  749. q = qmax;
  750. if (s->adaptive_quant)
  751. adaptive_quantization(s, q);
  752. else
  753. q = (int)(q + 0.5);
  754. if (!dry_run) {
  755. rcc->last_qscale = q;
  756. rcc->last_mc_mb_var_sum = pic->mc_mb_var_sum;
  757. rcc->last_mb_var_sum = pic->mb_var_sum;
  758. }
  759. return q;
  760. }
  761. // ----------------------------------------------
  762. // 2-Pass code
  763. static int init_pass2(MpegEncContext *s)
  764. {
  765. RateControlContext *rcc = &s->rc_context;
  766. AVCodecContext *a = s->avctx;
  767. int i, toobig;
  768. double fps = 1 / av_q2d(s->avctx->time_base);
  769. double complexity[5] = { 0 }; // approximate bits at quant=1
  770. uint64_t const_bits[5] = { 0 }; // quantizer independent bits
  771. uint64_t all_const_bits;
  772. uint64_t all_available_bits = (uint64_t)(s->bit_rate *
  773. (double)rcc->num_entries / fps);
  774. double rate_factor = 0;
  775. double step;
  776. const int filter_size = (int)(a->qblur * 4) | 1;
  777. double expected_bits;
  778. double *qscale, *blurred_qscale, qscale_sum;
  779. /* find complexity & const_bits & decide the pict_types */
  780. for (i = 0; i < rcc->num_entries; i++) {
  781. RateControlEntry *rce = &rcc->entry[i];
  782. rce->new_pict_type = rce->pict_type;
  783. rcc->i_cplx_sum[rce->pict_type] += rce->i_tex_bits * rce->qscale;
  784. rcc->p_cplx_sum[rce->pict_type] += rce->p_tex_bits * rce->qscale;
  785. rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
  786. rcc->frame_count[rce->pict_type]++;
  787. complexity[rce->new_pict_type] += (rce->i_tex_bits + rce->p_tex_bits) *
  788. (double)rce->qscale;
  789. const_bits[rce->new_pict_type] += rce->mv_bits + rce->misc_bits;
  790. }
  791. all_const_bits = const_bits[AV_PICTURE_TYPE_I] +
  792. const_bits[AV_PICTURE_TYPE_P] +
  793. const_bits[AV_PICTURE_TYPE_B];
  794. if (all_available_bits < all_const_bits) {
  795. av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
  796. return -1;
  797. }
  798. qscale = av_malloc(sizeof(double) * rcc->num_entries);
  799. blurred_qscale = av_malloc(sizeof(double) * rcc->num_entries);
  800. if (!qscale || !blurred_qscale) {
  801. av_free(qscale);
  802. av_free(blurred_qscale);
  803. return AVERROR(ENOMEM);
  804. }
  805. toobig = 0;
  806. for (step = 256 * 256; step > 0.0000001; step *= 0.5) {
  807. expected_bits = 0;
  808. rate_factor += step;
  809. rcc->buffer_index = s->avctx->rc_buffer_size / 2;
  810. /* find qscale */
  811. for (i = 0; i < rcc->num_entries; i++) {
  812. RateControlEntry *rce = &rcc->entry[i];
  813. qscale[i] = get_qscale(s, &rcc->entry[i], rate_factor, i);
  814. rcc->last_qscale_for[rce->pict_type] = qscale[i];
  815. }
  816. assert(filter_size % 2 == 1);
  817. /* fixed I/B QP relative to P mode */
  818. for (i = rcc->num_entries - 1; i >= 0; i--) {
  819. RateControlEntry *rce = &rcc->entry[i];
  820. qscale[i] = get_diff_limited_q(s, rce, qscale[i]);
  821. }
  822. /* smooth curve */
  823. for (i = 0; i < rcc->num_entries; i++) {
  824. RateControlEntry *rce = &rcc->entry[i];
  825. const int pict_type = rce->new_pict_type;
  826. int j;
  827. double q = 0.0, sum = 0.0;
  828. for (j = 0; j < filter_size; j++) {
  829. int index = i + j - filter_size / 2;
  830. double d = index - i;
  831. double coeff = a->qblur == 0 ? 1.0 : exp(-d * d / (a->qblur * a->qblur));
  832. if (index < 0 || index >= rcc->num_entries)
  833. continue;
  834. if (pict_type != rcc->entry[index].new_pict_type)
  835. continue;
  836. q += qscale[index] * coeff;
  837. sum += coeff;
  838. }
  839. blurred_qscale[i] = q / sum;
  840. }
  841. /* find expected bits */
  842. for (i = 0; i < rcc->num_entries; i++) {
  843. RateControlEntry *rce = &rcc->entry[i];
  844. double bits;
  845. rce->new_qscale = modify_qscale(s, rce, blurred_qscale[i], i);
  846. bits = qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
  847. bits += 8 * ff_vbv_update(s, bits);
  848. rce->expected_bits = expected_bits;
  849. expected_bits += bits;
  850. }
  851. ff_dlog(s->avctx,
  852. "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
  853. expected_bits, (int)all_available_bits, rate_factor);
  854. if (expected_bits > all_available_bits) {
  855. rate_factor -= step;
  856. ++toobig;
  857. }
  858. }
  859. av_free(qscale);
  860. av_free(blurred_qscale);
  861. /* check bitrate calculations and print info */
  862. qscale_sum = 0.0;
  863. for (i = 0; i < rcc->num_entries; i++) {
  864. ff_dlog(s, "[lavc rc] entry[%d].new_qscale = %.3f qp = %.3f\n",
  865. i,
  866. rcc->entry[i].new_qscale,
  867. rcc->entry[i].new_qscale / FF_QP2LAMBDA);
  868. qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA,
  869. s->avctx->qmin, s->avctx->qmax);
  870. }
  871. assert(toobig <= 40);
  872. av_log(s->avctx, AV_LOG_DEBUG,
  873. "[lavc rc] requested bitrate: %d bps expected bitrate: %d bps\n",
  874. s->bit_rate,
  875. (int)(expected_bits / ((double)all_available_bits / s->bit_rate)));
  876. av_log(s->avctx, AV_LOG_DEBUG,
  877. "[lavc rc] estimated target average qp: %.3f\n",
  878. (float)qscale_sum / rcc->num_entries);
  879. if (toobig == 0) {
  880. av_log(s->avctx, AV_LOG_INFO,
  881. "[lavc rc] Using all of requested bitrate is not "
  882. "necessary for this video with these parameters.\n");
  883. } else if (toobig == 40) {
  884. av_log(s->avctx, AV_LOG_ERROR,
  885. "[lavc rc] Error: bitrate too low for this video "
  886. "with these parameters.\n");
  887. return -1;
  888. } else if (fabs(expected_bits / all_available_bits - 1.0) > 0.01) {
  889. av_log(s->avctx, AV_LOG_ERROR,
  890. "[lavc rc] Error: 2pass curve failed to converge\n");
  891. return -1;
  892. }
  893. return 0;
  894. }