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.

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