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.

1058 lines
35KB

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