frame.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. // Copyright 2011 Google Inc. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the COPYING file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. // -----------------------------------------------------------------------------
  9. //
  10. // frame coding and analysis
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #include <string.h>
  14. #include <math.h>
  15. #include "./vp8enci.h"
  16. #include "./cost.h"
  17. #include "../webp/format_constants.h" // RIFF constants
  18. #define SEGMENT_VISU 0
  19. #define DEBUG_SEARCH 0 // useful to track search convergence
  20. //------------------------------------------------------------------------------
  21. // multi-pass convergence
  22. #define HEADER_SIZE_ESTIMATE (RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + \
  23. VP8_FRAME_HEADER_SIZE)
  24. #define DQ_LIMIT 0.4 // convergence is considered reached if dq < DQ_LIMIT
  25. // we allow 2k of extra head-room in PARTITION0 limit.
  26. #define PARTITION0_SIZE_LIMIT ((VP8_MAX_PARTITION0_SIZE - 2048ULL) << 11)
  27. typedef struct { // struct for organizing convergence in either size or PSNR
  28. int is_first;
  29. float dq;
  30. float q, last_q;
  31. double value, last_value; // PSNR or size
  32. double target;
  33. int do_size_search;
  34. } PassStats;
  35. static int InitPassStats(const VP8Encoder* const enc, PassStats* const s) {
  36. const uint64_t target_size = (uint64_t)enc->config_->target_size;
  37. const int do_size_search = (target_size != 0);
  38. const float target_PSNR = enc->config_->target_PSNR;
  39. s->is_first = 1;
  40. s->dq = 10.f;
  41. s->q = s->last_q = enc->config_->quality;
  42. s->target = do_size_search ? (double)target_size
  43. : (target_PSNR > 0.) ? target_PSNR
  44. : 40.; // default, just in case
  45. s->value = s->last_value = 0.;
  46. s->do_size_search = do_size_search;
  47. return do_size_search;
  48. }
  49. static float Clamp(float v, float min, float max) {
  50. return (v < min) ? min : (v > max) ? max : v;
  51. }
  52. static float ComputeNextQ(PassStats* const s) {
  53. float dq;
  54. if (s->is_first) {
  55. dq = (s->value > s->target) ? -s->dq : s->dq;
  56. s->is_first = 0;
  57. } else if (s->value != s->last_value) {
  58. const double slope = (s->target - s->value) / (s->last_value - s->value);
  59. dq = (float)(slope * (s->last_q - s->q));
  60. } else {
  61. dq = 0.; // we're done?!
  62. }
  63. // Limit variable to avoid large swings.
  64. s->dq = Clamp(dq, -30.f, 30.f);
  65. s->last_q = s->q;
  66. s->last_value = s->value;
  67. s->q = Clamp(s->q + s->dq, 0.f, 100.f);
  68. return s->q;
  69. }
  70. //------------------------------------------------------------------------------
  71. // Tables for level coding
  72. const uint8_t VP8EncBands[16 + 1] = {
  73. 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7,
  74. 0 // sentinel
  75. };
  76. const uint8_t VP8Cat3[] = { 173, 148, 140 };
  77. const uint8_t VP8Cat4[] = { 176, 155, 140, 135 };
  78. const uint8_t VP8Cat5[] = { 180, 157, 141, 134, 130 };
  79. const uint8_t VP8Cat6[] =
  80. { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 };
  81. //------------------------------------------------------------------------------
  82. // Reset the statistics about: number of skips, token proba, level cost,...
  83. static void ResetStats(VP8Encoder* const enc) {
  84. VP8Proba* const proba = &enc->proba_;
  85. VP8CalculateLevelCosts(proba);
  86. proba->nb_skip_ = 0;
  87. }
  88. //------------------------------------------------------------------------------
  89. // Skip decision probability
  90. #define SKIP_PROBA_THRESHOLD 250 // value below which using skip_proba is OK.
  91. static int CalcSkipProba(uint64_t nb, uint64_t total) {
  92. return (int)(total ? (total - nb) * 255 / total : 255);
  93. }
  94. // Returns the bit-cost for coding the skip probability.
  95. static int FinalizeSkipProba(VP8Encoder* const enc) {
  96. VP8Proba* const proba = &enc->proba_;
  97. const int nb_mbs = enc->mb_w_ * enc->mb_h_;
  98. const int nb_events = proba->nb_skip_;
  99. int size;
  100. proba->skip_proba_ = CalcSkipProba(nb_events, nb_mbs);
  101. proba->use_skip_proba_ = (proba->skip_proba_ < SKIP_PROBA_THRESHOLD);
  102. size = 256; // 'use_skip_proba' bit
  103. if (proba->use_skip_proba_) {
  104. size += nb_events * VP8BitCost(1, proba->skip_proba_)
  105. + (nb_mbs - nb_events) * VP8BitCost(0, proba->skip_proba_);
  106. size += 8 * 256; // cost of signaling the skip_proba_ itself.
  107. }
  108. return size;
  109. }
  110. // Collect statistics and deduce probabilities for next coding pass.
  111. // Return the total bit-cost for coding the probability updates.
  112. static int CalcTokenProba(int nb, int total) {
  113. assert(nb <= total);
  114. return nb ? (255 - nb * 255 / total) : 255;
  115. }
  116. // Cost of coding 'nb' 1's and 'total-nb' 0's using 'proba' probability.
  117. static int BranchCost(int nb, int total, int proba) {
  118. return nb * VP8BitCost(1, proba) + (total - nb) * VP8BitCost(0, proba);
  119. }
  120. static void ResetTokenStats(VP8Encoder* const enc) {
  121. VP8Proba* const proba = &enc->proba_;
  122. memset(proba->stats_, 0, sizeof(proba->stats_));
  123. }
  124. static int FinalizeTokenProbas(VP8Proba* const proba) {
  125. int has_changed = 0;
  126. int size = 0;
  127. int t, b, c, p;
  128. for (t = 0; t < NUM_TYPES; ++t) {
  129. for (b = 0; b < NUM_BANDS; ++b) {
  130. for (c = 0; c < NUM_CTX; ++c) {
  131. for (p = 0; p < NUM_PROBAS; ++p) {
  132. const proba_t stats = proba->stats_[t][b][c][p];
  133. const int nb = (stats >> 0) & 0xffff;
  134. const int total = (stats >> 16) & 0xffff;
  135. const int update_proba = VP8CoeffsUpdateProba[t][b][c][p];
  136. const int old_p = VP8CoeffsProba0[t][b][c][p];
  137. const int new_p = CalcTokenProba(nb, total);
  138. const int old_cost = BranchCost(nb, total, old_p)
  139. + VP8BitCost(0, update_proba);
  140. const int new_cost = BranchCost(nb, total, new_p)
  141. + VP8BitCost(1, update_proba)
  142. + 8 * 256;
  143. const int use_new_p = (old_cost > new_cost);
  144. size += VP8BitCost(use_new_p, update_proba);
  145. if (use_new_p) { // only use proba that seem meaningful enough.
  146. proba->coeffs_[t][b][c][p] = new_p;
  147. has_changed |= (new_p != old_p);
  148. size += 8 * 256;
  149. } else {
  150. proba->coeffs_[t][b][c][p] = old_p;
  151. }
  152. }
  153. }
  154. }
  155. }
  156. proba->dirty_ = has_changed;
  157. return size;
  158. }
  159. //------------------------------------------------------------------------------
  160. // Finalize Segment probability based on the coding tree
  161. static int GetProba(int a, int b) {
  162. const int total = a + b;
  163. return (total == 0) ? 255 // that's the default probability.
  164. : (255 * a + total / 2) / total; // rounded proba
  165. }
  166. static void SetSegmentProbas(VP8Encoder* const enc) {
  167. int p[NUM_MB_SEGMENTS] = { 0 };
  168. int n;
  169. for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {
  170. const VP8MBInfo* const mb = &enc->mb_info_[n];
  171. p[mb->segment_]++;
  172. }
  173. if (enc->pic_->stats != NULL) {
  174. for (n = 0; n < NUM_MB_SEGMENTS; ++n) {
  175. enc->pic_->stats->segment_size[n] = p[n];
  176. }
  177. }
  178. if (enc->segment_hdr_.num_segments_ > 1) {
  179. uint8_t* const probas = enc->proba_.segments_;
  180. probas[0] = GetProba(p[0] + p[1], p[2] + p[3]);
  181. probas[1] = GetProba(p[0], p[1]);
  182. probas[2] = GetProba(p[2], p[3]);
  183. enc->segment_hdr_.update_map_ =
  184. (probas[0] != 255) || (probas[1] != 255) || (probas[2] != 255);
  185. enc->segment_hdr_.size_ =
  186. p[0] * (VP8BitCost(0, probas[0]) + VP8BitCost(0, probas[1])) +
  187. p[1] * (VP8BitCost(0, probas[0]) + VP8BitCost(1, probas[1])) +
  188. p[2] * (VP8BitCost(1, probas[0]) + VP8BitCost(0, probas[2])) +
  189. p[3] * (VP8BitCost(1, probas[0]) + VP8BitCost(1, probas[2]));
  190. } else {
  191. enc->segment_hdr_.update_map_ = 0;
  192. enc->segment_hdr_.size_ = 0;
  193. }
  194. }
  195. //------------------------------------------------------------------------------
  196. // Coefficient coding
  197. static int PutCoeffs(VP8BitWriter* const bw, int ctx, const VP8Residual* res) {
  198. int n = res->first;
  199. // should be prob[VP8EncBands[n]], but it's equivalent for n=0 or 1
  200. const uint8_t* p = res->prob[n][ctx];
  201. if (!VP8PutBit(bw, res->last >= 0, p[0])) {
  202. return 0;
  203. }
  204. while (n < 16) {
  205. const int c = res->coeffs[n++];
  206. const int sign = c < 0;
  207. int v = sign ? -c : c;
  208. if (!VP8PutBit(bw, v != 0, p[1])) {
  209. p = res->prob[VP8EncBands[n]][0];
  210. continue;
  211. }
  212. if (!VP8PutBit(bw, v > 1, p[2])) {
  213. p = res->prob[VP8EncBands[n]][1];
  214. } else {
  215. if (!VP8PutBit(bw, v > 4, p[3])) {
  216. if (VP8PutBit(bw, v != 2, p[4]))
  217. VP8PutBit(bw, v == 4, p[5]);
  218. } else if (!VP8PutBit(bw, v > 10, p[6])) {
  219. if (!VP8PutBit(bw, v > 6, p[7])) {
  220. VP8PutBit(bw, v == 6, 159);
  221. } else {
  222. VP8PutBit(bw, v >= 9, 165);
  223. VP8PutBit(bw, !(v & 1), 145);
  224. }
  225. } else {
  226. int mask;
  227. const uint8_t* tab;
  228. if (v < 3 + (8 << 1)) { // VP8Cat3 (3b)
  229. VP8PutBit(bw, 0, p[8]);
  230. VP8PutBit(bw, 0, p[9]);
  231. v -= 3 + (8 << 0);
  232. mask = 1 << 2;
  233. tab = VP8Cat3;
  234. } else if (v < 3 + (8 << 2)) { // VP8Cat4 (4b)
  235. VP8PutBit(bw, 0, p[8]);
  236. VP8PutBit(bw, 1, p[9]);
  237. v -= 3 + (8 << 1);
  238. mask = 1 << 3;
  239. tab = VP8Cat4;
  240. } else if (v < 3 + (8 << 3)) { // VP8Cat5 (5b)
  241. VP8PutBit(bw, 1, p[8]);
  242. VP8PutBit(bw, 0, p[10]);
  243. v -= 3 + (8 << 2);
  244. mask = 1 << 4;
  245. tab = VP8Cat5;
  246. } else { // VP8Cat6 (11b)
  247. VP8PutBit(bw, 1, p[8]);
  248. VP8PutBit(bw, 1, p[10]);
  249. v -= 3 + (8 << 3);
  250. mask = 1 << 10;
  251. tab = VP8Cat6;
  252. }
  253. while (mask) {
  254. VP8PutBit(bw, !!(v & mask), *tab++);
  255. mask >>= 1;
  256. }
  257. }
  258. p = res->prob[VP8EncBands[n]][2];
  259. }
  260. VP8PutBitUniform(bw, sign);
  261. if (n == 16 || !VP8PutBit(bw, n <= res->last, p[0])) {
  262. return 1; // EOB
  263. }
  264. }
  265. return 1;
  266. }
  267. static void CodeResiduals(VP8BitWriter* const bw, VP8EncIterator* const it,
  268. const VP8ModeScore* const rd) {
  269. int x, y, ch;
  270. VP8Residual res;
  271. uint64_t pos1, pos2, pos3;
  272. const int i16 = (it->mb_->type_ == 1);
  273. const int segment = it->mb_->segment_;
  274. VP8Encoder* const enc = it->enc_;
  275. VP8IteratorNzToBytes(it);
  276. pos1 = VP8BitWriterPos(bw);
  277. if (i16) {
  278. VP8InitResidual(0, 1, enc, &res);
  279. VP8SetResidualCoeffs(rd->y_dc_levels, &res);
  280. it->top_nz_[8] = it->left_nz_[8] =
  281. PutCoeffs(bw, it->top_nz_[8] + it->left_nz_[8], &res);
  282. VP8InitResidual(1, 0, enc, &res);
  283. } else {
  284. VP8InitResidual(0, 3, enc, &res);
  285. }
  286. // luma-AC
  287. for (y = 0; y < 4; ++y) {
  288. for (x = 0; x < 4; ++x) {
  289. const int ctx = it->top_nz_[x] + it->left_nz_[y];
  290. VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);
  291. it->top_nz_[x] = it->left_nz_[y] = PutCoeffs(bw, ctx, &res);
  292. }
  293. }
  294. pos2 = VP8BitWriterPos(bw);
  295. // U/V
  296. VP8InitResidual(0, 2, enc, &res);
  297. for (ch = 0; ch <= 2; ch += 2) {
  298. for (y = 0; y < 2; ++y) {
  299. for (x = 0; x < 2; ++x) {
  300. const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];
  301. VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);
  302. it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] =
  303. PutCoeffs(bw, ctx, &res);
  304. }
  305. }
  306. }
  307. pos3 = VP8BitWriterPos(bw);
  308. it->luma_bits_ = pos2 - pos1;
  309. it->uv_bits_ = pos3 - pos2;
  310. it->bit_count_[segment][i16] += it->luma_bits_;
  311. it->bit_count_[segment][2] += it->uv_bits_;
  312. VP8IteratorBytesToNz(it);
  313. }
  314. // Same as CodeResiduals, but doesn't actually write anything.
  315. // Instead, it just records the event distribution.
  316. static void RecordResiduals(VP8EncIterator* const it,
  317. const VP8ModeScore* const rd) {
  318. int x, y, ch;
  319. VP8Residual res;
  320. VP8Encoder* const enc = it->enc_;
  321. VP8IteratorNzToBytes(it);
  322. if (it->mb_->type_ == 1) { // i16x16
  323. VP8InitResidual(0, 1, enc, &res);
  324. VP8SetResidualCoeffs(rd->y_dc_levels, &res);
  325. it->top_nz_[8] = it->left_nz_[8] =
  326. VP8RecordCoeffs(it->top_nz_[8] + it->left_nz_[8], &res);
  327. VP8InitResidual(1, 0, enc, &res);
  328. } else {
  329. VP8InitResidual(0, 3, enc, &res);
  330. }
  331. // luma-AC
  332. for (y = 0; y < 4; ++y) {
  333. for (x = 0; x < 4; ++x) {
  334. const int ctx = it->top_nz_[x] + it->left_nz_[y];
  335. VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);
  336. it->top_nz_[x] = it->left_nz_[y] = VP8RecordCoeffs(ctx, &res);
  337. }
  338. }
  339. // U/V
  340. VP8InitResidual(0, 2, enc, &res);
  341. for (ch = 0; ch <= 2; ch += 2) {
  342. for (y = 0; y < 2; ++y) {
  343. for (x = 0; x < 2; ++x) {
  344. const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];
  345. VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);
  346. it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] =
  347. VP8RecordCoeffs(ctx, &res);
  348. }
  349. }
  350. }
  351. VP8IteratorBytesToNz(it);
  352. }
  353. //------------------------------------------------------------------------------
  354. // Token buffer
  355. #if !defined(DISABLE_TOKEN_BUFFER)
  356. static int RecordTokens(VP8EncIterator* const it, const VP8ModeScore* const rd,
  357. VP8TBuffer* const tokens) {
  358. int x, y, ch;
  359. VP8Residual res;
  360. VP8Encoder* const enc = it->enc_;
  361. VP8IteratorNzToBytes(it);
  362. if (it->mb_->type_ == 1) { // i16x16
  363. const int ctx = it->top_nz_[8] + it->left_nz_[8];
  364. VP8InitResidual(0, 1, enc, &res);
  365. VP8SetResidualCoeffs(rd->y_dc_levels, &res);
  366. it->top_nz_[8] = it->left_nz_[8] =
  367. VP8RecordCoeffTokens(ctx, 1,
  368. res.first, res.last, res.coeffs, tokens);
  369. VP8RecordCoeffs(ctx, &res);
  370. VP8InitResidual(1, 0, enc, &res);
  371. } else {
  372. VP8InitResidual(0, 3, enc, &res);
  373. }
  374. // luma-AC
  375. for (y = 0; y < 4; ++y) {
  376. for (x = 0; x < 4; ++x) {
  377. const int ctx = it->top_nz_[x] + it->left_nz_[y];
  378. VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);
  379. it->top_nz_[x] = it->left_nz_[y] =
  380. VP8RecordCoeffTokens(ctx, res.coeff_type,
  381. res.first, res.last, res.coeffs, tokens);
  382. VP8RecordCoeffs(ctx, &res);
  383. }
  384. }
  385. // U/V
  386. VP8InitResidual(0, 2, enc, &res);
  387. for (ch = 0; ch <= 2; ch += 2) {
  388. for (y = 0; y < 2; ++y) {
  389. for (x = 0; x < 2; ++x) {
  390. const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];
  391. VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);
  392. it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] =
  393. VP8RecordCoeffTokens(ctx, 2,
  394. res.first, res.last, res.coeffs, tokens);
  395. VP8RecordCoeffs(ctx, &res);
  396. }
  397. }
  398. }
  399. VP8IteratorBytesToNz(it);
  400. return !tokens->error_;
  401. }
  402. #endif // !DISABLE_TOKEN_BUFFER
  403. //------------------------------------------------------------------------------
  404. // ExtraInfo map / Debug function
  405. #if SEGMENT_VISU
  406. static void SetBlock(uint8_t* p, int value, int size) {
  407. int y;
  408. for (y = 0; y < size; ++y) {
  409. memset(p, value, size);
  410. p += BPS;
  411. }
  412. }
  413. #endif
  414. static void ResetSSE(VP8Encoder* const enc) {
  415. enc->sse_[0] = 0;
  416. enc->sse_[1] = 0;
  417. enc->sse_[2] = 0;
  418. // Note: enc->sse_[3] is managed by alpha.c
  419. enc->sse_count_ = 0;
  420. }
  421. static void StoreSSE(const VP8EncIterator* const it) {
  422. VP8Encoder* const enc = it->enc_;
  423. const uint8_t* const in = it->yuv_in_;
  424. const uint8_t* const out = it->yuv_out_;
  425. // Note: not totally accurate at boundary. And doesn't include in-loop filter.
  426. enc->sse_[0] += VP8SSE16x16(in + Y_OFF, out + Y_OFF);
  427. enc->sse_[1] += VP8SSE8x8(in + U_OFF, out + U_OFF);
  428. enc->sse_[2] += VP8SSE8x8(in + V_OFF, out + V_OFF);
  429. enc->sse_count_ += 16 * 16;
  430. }
  431. static void StoreSideInfo(const VP8EncIterator* const it) {
  432. VP8Encoder* const enc = it->enc_;
  433. const VP8MBInfo* const mb = it->mb_;
  434. WebPPicture* const pic = enc->pic_;
  435. if (pic->stats != NULL) {
  436. StoreSSE(it);
  437. enc->block_count_[0] += (mb->type_ == 0);
  438. enc->block_count_[1] += (mb->type_ == 1);
  439. enc->block_count_[2] += (mb->skip_ != 0);
  440. }
  441. if (pic->extra_info != NULL) {
  442. uint8_t* const info = &pic->extra_info[it->x_ + it->y_ * enc->mb_w_];
  443. switch (pic->extra_info_type) {
  444. case 1: *info = mb->type_; break;
  445. case 2: *info = mb->segment_; break;
  446. case 3: *info = enc->dqm_[mb->segment_].quant_; break;
  447. case 4: *info = (mb->type_ == 1) ? it->preds_[0] : 0xff; break;
  448. case 5: *info = mb->uv_mode_; break;
  449. case 6: {
  450. const int b = (int)((it->luma_bits_ + it->uv_bits_ + 7) >> 3);
  451. *info = (b > 255) ? 255 : b; break;
  452. }
  453. case 7: *info = mb->alpha_; break;
  454. default: *info = 0; break;
  455. }
  456. }
  457. #if SEGMENT_VISU // visualize segments and prediction modes
  458. SetBlock(it->yuv_out_ + Y_OFF, mb->segment_ * 64, 16);
  459. SetBlock(it->yuv_out_ + U_OFF, it->preds_[0] * 64, 8);
  460. SetBlock(it->yuv_out_ + V_OFF, mb->uv_mode_ * 64, 8);
  461. #endif
  462. }
  463. static double GetPSNR(uint64_t mse, uint64_t size) {
  464. return (mse > 0 && size > 0) ? 10. * log10(255. * 255. * size / mse) : 99;
  465. }
  466. //------------------------------------------------------------------------------
  467. // StatLoop(): only collect statistics (number of skips, token usage, ...).
  468. // This is used for deciding optimal probabilities. It also modifies the
  469. // quantizer value if some target (size, PSNR) was specified.
  470. static void SetLoopParams(VP8Encoder* const enc, float q) {
  471. // Make sure the quality parameter is inside valid bounds
  472. q = Clamp(q, 0.f, 100.f);
  473. VP8SetSegmentParams(enc, q); // setup segment quantizations and filters
  474. SetSegmentProbas(enc); // compute segment probabilities
  475. ResetStats(enc);
  476. ResetSSE(enc);
  477. }
  478. static uint64_t OneStatPass(VP8Encoder* const enc, VP8RDLevel rd_opt,
  479. int nb_mbs, int percent_delta,
  480. PassStats* const s) {
  481. VP8EncIterator it;
  482. uint64_t size = 0;
  483. uint64_t size_p0 = 0;
  484. uint64_t distortion = 0;
  485. const uint64_t pixel_count = nb_mbs * 384;
  486. VP8IteratorInit(enc, &it);
  487. SetLoopParams(enc, s->q);
  488. do {
  489. VP8ModeScore info;
  490. VP8IteratorImport(&it, NULL);
  491. if (VP8Decimate(&it, &info, rd_opt)) {
  492. // Just record the number of skips and act like skip_proba is not used.
  493. enc->proba_.nb_skip_++;
  494. }
  495. RecordResiduals(&it, &info);
  496. size += info.R + info.H;
  497. size_p0 += info.H;
  498. distortion += info.D;
  499. if (percent_delta && !VP8IteratorProgress(&it, percent_delta))
  500. return 0;
  501. VP8IteratorSaveBoundary(&it);
  502. } while (VP8IteratorNext(&it) && --nb_mbs > 0);
  503. size_p0 += enc->segment_hdr_.size_;
  504. if (s->do_size_search) {
  505. size += FinalizeSkipProba(enc);
  506. size += FinalizeTokenProbas(&enc->proba_);
  507. size = ((size + size_p0 + 1024) >> 11) + HEADER_SIZE_ESTIMATE;
  508. s->value = (double)size;
  509. } else {
  510. s->value = GetPSNR(distortion, pixel_count);
  511. }
  512. return size_p0;
  513. }
  514. static int StatLoop(VP8Encoder* const enc) {
  515. const int method = enc->method_;
  516. const int do_search = enc->do_search_;
  517. const int fast_probe = ((method == 0 || method == 3) && !do_search);
  518. int num_pass_left = enc->config_->pass;
  519. const int task_percent = 20;
  520. const int percent_per_pass =
  521. (task_percent + num_pass_left / 2) / num_pass_left;
  522. const int final_percent = enc->percent_ + task_percent;
  523. const VP8RDLevel rd_opt =
  524. (method >= 3 || do_search) ? RD_OPT_BASIC : RD_OPT_NONE;
  525. int nb_mbs = enc->mb_w_ * enc->mb_h_;
  526. PassStats stats;
  527. InitPassStats(enc, &stats);
  528. ResetTokenStats(enc);
  529. // Fast mode: quick analysis pass over few mbs. Better than nothing.
  530. if (fast_probe) {
  531. if (method == 3) { // we need more stats for method 3 to be reliable.
  532. nb_mbs = (nb_mbs > 200) ? nb_mbs >> 1 : 100;
  533. } else {
  534. nb_mbs = (nb_mbs > 200) ? nb_mbs >> 2 : 50;
  535. }
  536. }
  537. while (num_pass_left-- > 0) {
  538. const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) ||
  539. (num_pass_left == 0) ||
  540. (enc->max_i4_header_bits_ == 0);
  541. const uint64_t size_p0 =
  542. OneStatPass(enc, rd_opt, nb_mbs, percent_per_pass, &stats);
  543. if (size_p0 == 0) return 0;
  544. #if (DEBUG_SEARCH > 0)
  545. printf("#%d value:%.1lf -> %.1lf q:%.2f -> %.2f\n",
  546. num_pass_left, stats.last_value, stats.value, stats.last_q, stats.q);
  547. #endif
  548. if (enc->max_i4_header_bits_ > 0 && size_p0 > PARTITION0_SIZE_LIMIT) {
  549. ++num_pass_left;
  550. enc->max_i4_header_bits_ >>= 1; // strengthen header bit limitation...
  551. continue; // ...and start over
  552. }
  553. if (is_last_pass) {
  554. break;
  555. }
  556. // If no target size: just do several pass without changing 'q'
  557. if (do_search) {
  558. ComputeNextQ(&stats);
  559. if (fabs(stats.dq) <= DQ_LIMIT) break;
  560. }
  561. }
  562. if (!do_search || !stats.do_size_search) {
  563. // Need to finalize probas now, since it wasn't done during the search.
  564. FinalizeSkipProba(enc);
  565. FinalizeTokenProbas(&enc->proba_);
  566. }
  567. VP8CalculateLevelCosts(&enc->proba_); // finalize costs
  568. return WebPReportProgress(enc->pic_, final_percent, &enc->percent_);
  569. }
  570. //------------------------------------------------------------------------------
  571. // Main loops
  572. //
  573. static const int kAverageBytesPerMB[8] = { 50, 24, 16, 9, 7, 5, 3, 2 };
  574. static int PreLoopInitialize(VP8Encoder* const enc) {
  575. int p;
  576. int ok = 1;
  577. const int average_bytes_per_MB = kAverageBytesPerMB[enc->base_quant_ >> 4];
  578. const int bytes_per_parts =
  579. enc->mb_w_ * enc->mb_h_ * average_bytes_per_MB / enc->num_parts_;
  580. // Initialize the bit-writers
  581. for (p = 0; ok && p < enc->num_parts_; ++p) {
  582. ok = VP8BitWriterInit(enc->parts_ + p, bytes_per_parts);
  583. }
  584. if (!ok) {
  585. VP8EncFreeBitWriters(enc); // malloc error occurred
  586. WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY);
  587. }
  588. return ok;
  589. }
  590. static int PostLoopFinalize(VP8EncIterator* const it, int ok) {
  591. VP8Encoder* const enc = it->enc_;
  592. if (ok) { // Finalize the partitions, check for extra errors.
  593. int p;
  594. for (p = 0; p < enc->num_parts_; ++p) {
  595. VP8BitWriterFinish(enc->parts_ + p);
  596. ok &= !enc->parts_[p].error_;
  597. }
  598. }
  599. if (ok) { // All good. Finish up.
  600. if (enc->pic_->stats != NULL) { // finalize byte counters...
  601. int i, s;
  602. for (i = 0; i <= 2; ++i) {
  603. for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
  604. enc->residual_bytes_[i][s] = (int)((it->bit_count_[s][i] + 7) >> 3);
  605. }
  606. }
  607. }
  608. VP8AdjustFilterStrength(it); // ...and store filter stats.
  609. } else {
  610. // Something bad happened -> need to do some memory cleanup.
  611. VP8EncFreeBitWriters(enc);
  612. }
  613. return ok;
  614. }
  615. //------------------------------------------------------------------------------
  616. // VP8EncLoop(): does the final bitstream coding.
  617. static void ResetAfterSkip(VP8EncIterator* const it) {
  618. if (it->mb_->type_ == 1) {
  619. *it->nz_ = 0; // reset all predictors
  620. it->left_nz_[8] = 0;
  621. } else {
  622. *it->nz_ &= (1 << 24); // preserve the dc_nz bit
  623. }
  624. }
  625. int VP8EncLoop(VP8Encoder* const enc) {
  626. VP8EncIterator it;
  627. int ok = PreLoopInitialize(enc);
  628. if (!ok) return 0;
  629. StatLoop(enc); // stats-collection loop
  630. VP8IteratorInit(enc, &it);
  631. VP8InitFilter(&it);
  632. do {
  633. VP8ModeScore info;
  634. const int dont_use_skip = !enc->proba_.use_skip_proba_;
  635. const VP8RDLevel rd_opt = enc->rd_opt_level_;
  636. VP8IteratorImport(&it, NULL);
  637. // Warning! order is important: first call VP8Decimate() and
  638. // *then* decide how to code the skip decision if there's one.
  639. if (!VP8Decimate(&it, &info, rd_opt) || dont_use_skip) {
  640. CodeResiduals(it.bw_, &it, &info);
  641. } else { // reset predictors after a skip
  642. ResetAfterSkip(&it);
  643. }
  644. StoreSideInfo(&it);
  645. VP8StoreFilterStats(&it);
  646. VP8IteratorExport(&it);
  647. ok = VP8IteratorProgress(&it, 20);
  648. VP8IteratorSaveBoundary(&it);
  649. } while (ok && VP8IteratorNext(&it));
  650. return PostLoopFinalize(&it, ok);
  651. }
  652. //------------------------------------------------------------------------------
  653. // Single pass using Token Buffer.
  654. #if !defined(DISABLE_TOKEN_BUFFER)
  655. #define MIN_COUNT 96 // minimum number of macroblocks before updating stats
  656. int VP8EncTokenLoop(VP8Encoder* const enc) {
  657. // Roughly refresh the proba eight times per pass
  658. int max_count = (enc->mb_w_ * enc->mb_h_) >> 3;
  659. int num_pass_left = enc->config_->pass;
  660. const int do_search = enc->do_search_;
  661. VP8EncIterator it;
  662. VP8Proba* const proba = &enc->proba_;
  663. const VP8RDLevel rd_opt = enc->rd_opt_level_;
  664. const uint64_t pixel_count = enc->mb_w_ * enc->mb_h_ * 384;
  665. PassStats stats;
  666. int ok;
  667. InitPassStats(enc, &stats);
  668. ok = PreLoopInitialize(enc);
  669. if (!ok) return 0;
  670. if (max_count < MIN_COUNT) max_count = MIN_COUNT;
  671. assert(enc->num_parts_ == 1);
  672. assert(enc->use_tokens_);
  673. assert(proba->use_skip_proba_ == 0);
  674. assert(rd_opt >= RD_OPT_BASIC); // otherwise, token-buffer won't be useful
  675. assert(num_pass_left > 0);
  676. while (ok && num_pass_left-- > 0) {
  677. const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) ||
  678. (num_pass_left == 0) ||
  679. (enc->max_i4_header_bits_ == 0);
  680. uint64_t size_p0 = 0;
  681. uint64_t distortion = 0;
  682. int cnt = max_count;
  683. VP8IteratorInit(enc, &it);
  684. SetLoopParams(enc, stats.q);
  685. if (is_last_pass) {
  686. ResetTokenStats(enc);
  687. VP8InitFilter(&it); // don't collect stats until last pass (too costly)
  688. }
  689. VP8TBufferClear(&enc->tokens_);
  690. do {
  691. VP8ModeScore info;
  692. VP8IteratorImport(&it, NULL);
  693. if (--cnt < 0) {
  694. FinalizeTokenProbas(proba);
  695. VP8CalculateLevelCosts(proba); // refresh cost tables for rd-opt
  696. cnt = max_count;
  697. }
  698. VP8Decimate(&it, &info, rd_opt);
  699. ok = RecordTokens(&it, &info, &enc->tokens_);
  700. if (!ok) {
  701. WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY);
  702. break;
  703. }
  704. size_p0 += info.H;
  705. distortion += info.D;
  706. if (is_last_pass) {
  707. StoreSideInfo(&it);
  708. VP8StoreFilterStats(&it);
  709. VP8IteratorExport(&it);
  710. ok = VP8IteratorProgress(&it, 20);
  711. }
  712. VP8IteratorSaveBoundary(&it);
  713. } while (ok && VP8IteratorNext(&it));
  714. if (!ok) break;
  715. size_p0 += enc->segment_hdr_.size_;
  716. if (stats.do_size_search) {
  717. uint64_t size = FinalizeTokenProbas(&enc->proba_);
  718. size += VP8EstimateTokenSize(&enc->tokens_,
  719. (const uint8_t*)proba->coeffs_);
  720. size = (size + size_p0 + 1024) >> 11; // -> size in bytes
  721. size += HEADER_SIZE_ESTIMATE;
  722. stats.value = (double)size;
  723. } else { // compute and store PSNR
  724. stats.value = GetPSNR(distortion, pixel_count);
  725. }
  726. #if (DEBUG_SEARCH > 0)
  727. printf("#%2d metric:%.1lf -> %.1lf last_q=%.2lf q=%.2lf dq=%.2lf\n",
  728. num_pass_left, stats.last_value, stats.value,
  729. stats.last_q, stats.q, stats.dq);
  730. #endif
  731. if (size_p0 > PARTITION0_SIZE_LIMIT) {
  732. ++num_pass_left;
  733. enc->max_i4_header_bits_ >>= 1; // strengthen header bit limitation...
  734. continue; // ...and start over
  735. }
  736. if (is_last_pass) {
  737. break; // done
  738. }
  739. if (do_search) {
  740. ComputeNextQ(&stats); // Adjust q
  741. }
  742. }
  743. if (ok) {
  744. if (!stats.do_size_search) {
  745. FinalizeTokenProbas(&enc->proba_);
  746. }
  747. ok = VP8EmitTokens(&enc->tokens_, enc->parts_ + 0,
  748. (const uint8_t*)proba->coeffs_, 1);
  749. }
  750. ok = ok && WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
  751. return PostLoopFinalize(&it, ok);
  752. }
  753. #else
  754. int VP8EncTokenLoop(VP8Encoder* const enc) {
  755. (void)enc;
  756. return 0; // we shouldn't be here.
  757. }
  758. #endif // DISABLE_TOKEN_BUFFER
  759. //------------------------------------------------------------------------------