frame_enc.c 29 KB

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