2
0

ratecontrol.c 34 KB

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