ratecontrol.c 32 KB

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