quant.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. // Quantization
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #include <assert.h>
  14. #include <math.h>
  15. #include <stdlib.h> // for abs()
  16. #include "./vp8enci.h"
  17. #include "./cost.h"
  18. #define DO_TRELLIS_I4 1
  19. #define DO_TRELLIS_I16 1 // not a huge gain, but ok at low bitrate.
  20. #define DO_TRELLIS_UV 0 // disable trellis for UV. Risky. Not worth.
  21. #define USE_TDISTO 1
  22. #define MID_ALPHA 64 // neutral value for susceptibility
  23. #define MIN_ALPHA 30 // lowest usable value for susceptibility
  24. #define MAX_ALPHA 100 // higher meaningful value for susceptibility
  25. #define SNS_TO_DQ 0.9 // Scaling constant between the sns value and the QP
  26. // power-law modulation. Must be strictly less than 1.
  27. #define I4_PENALTY 4000 // Rate-penalty for quick i4/i16 decision
  28. // number of non-zero coeffs below which we consider the block very flat
  29. // (and apply a penalty to complex predictions)
  30. #define FLATNESS_LIMIT_I16 10 // I16 mode
  31. #define FLATNESS_LIMIT_I4 3 // I4 mode
  32. #define FLATNESS_LIMIT_UV 2 // UV mode
  33. #define FLATNESS_PENALTY 140 // roughly ~1bit per block
  34. #define MULT_8B(a, b) (((a) * (b) + 128) >> 8)
  35. // #define DEBUG_BLOCK
  36. //------------------------------------------------------------------------------
  37. #if defined(DEBUG_BLOCK)
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. static void PrintBlockInfo(const VP8EncIterator* const it,
  41. const VP8ModeScore* const rd) {
  42. int i, j;
  43. const int is_i16 = (it->mb_->type_ == 1);
  44. printf("SOURCE / OUTPUT / ABS DELTA\n");
  45. for (j = 0; j < 24; ++j) {
  46. if (j == 16) printf("\n"); // newline before the U/V block
  47. for (i = 0; i < 16; ++i) printf("%3d ", it->yuv_in_[i + j * BPS]);
  48. printf(" ");
  49. for (i = 0; i < 16; ++i) printf("%3d ", it->yuv_out_[i + j * BPS]);
  50. printf(" ");
  51. for (i = 0; i < 16; ++i) {
  52. printf("%1d ", abs(it->yuv_out_[i + j * BPS] - it->yuv_in_[i + j * BPS]));
  53. }
  54. printf("\n");
  55. }
  56. printf("\nD:%d SD:%d R:%d H:%d nz:0x%x score:%d\n",
  57. (int)rd->D, (int)rd->SD, (int)rd->R, (int)rd->H, (int)rd->nz,
  58. (int)rd->score);
  59. if (is_i16) {
  60. printf("Mode: %d\n", rd->mode_i16);
  61. printf("y_dc_levels:");
  62. for (i = 0; i < 16; ++i) printf("%3d ", rd->y_dc_levels[i]);
  63. printf("\n");
  64. } else {
  65. printf("Modes[16]: ");
  66. for (i = 0; i < 16; ++i) printf("%d ", rd->modes_i4[i]);
  67. printf("\n");
  68. }
  69. printf("y_ac_levels:\n");
  70. for (j = 0; j < 16; ++j) {
  71. for (i = is_i16 ? 1 : 0; i < 16; ++i) {
  72. printf("%4d ", rd->y_ac_levels[j][i]);
  73. }
  74. printf("\n");
  75. }
  76. printf("\n");
  77. printf("uv_levels (mode=%d):\n", rd->mode_uv);
  78. for (j = 0; j < 8; ++j) {
  79. for (i = 0; i < 16; ++i) {
  80. printf("%4d ", rd->uv_levels[j][i]);
  81. }
  82. printf("\n");
  83. }
  84. }
  85. #endif // DEBUG_BLOCK
  86. //------------------------------------------------------------------------------
  87. static WEBP_INLINE int clip(int v, int m, int M) {
  88. return v < m ? m : v > M ? M : v;
  89. }
  90. static const uint8_t kZigzag[16] = {
  91. 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15
  92. };
  93. static const uint8_t kDcTable[128] = {
  94. 4, 5, 6, 7, 8, 9, 10, 10,
  95. 11, 12, 13, 14, 15, 16, 17, 17,
  96. 18, 19, 20, 20, 21, 21, 22, 22,
  97. 23, 23, 24, 25, 25, 26, 27, 28,
  98. 29, 30, 31, 32, 33, 34, 35, 36,
  99. 37, 37, 38, 39, 40, 41, 42, 43,
  100. 44, 45, 46, 46, 47, 48, 49, 50,
  101. 51, 52, 53, 54, 55, 56, 57, 58,
  102. 59, 60, 61, 62, 63, 64, 65, 66,
  103. 67, 68, 69, 70, 71, 72, 73, 74,
  104. 75, 76, 76, 77, 78, 79, 80, 81,
  105. 82, 83, 84, 85, 86, 87, 88, 89,
  106. 91, 93, 95, 96, 98, 100, 101, 102,
  107. 104, 106, 108, 110, 112, 114, 116, 118,
  108. 122, 124, 126, 128, 130, 132, 134, 136,
  109. 138, 140, 143, 145, 148, 151, 154, 157
  110. };
  111. static const uint16_t kAcTable[128] = {
  112. 4, 5, 6, 7, 8, 9, 10, 11,
  113. 12, 13, 14, 15, 16, 17, 18, 19,
  114. 20, 21, 22, 23, 24, 25, 26, 27,
  115. 28, 29, 30, 31, 32, 33, 34, 35,
  116. 36, 37, 38, 39, 40, 41, 42, 43,
  117. 44, 45, 46, 47, 48, 49, 50, 51,
  118. 52, 53, 54, 55, 56, 57, 58, 60,
  119. 62, 64, 66, 68, 70, 72, 74, 76,
  120. 78, 80, 82, 84, 86, 88, 90, 92,
  121. 94, 96, 98, 100, 102, 104, 106, 108,
  122. 110, 112, 114, 116, 119, 122, 125, 128,
  123. 131, 134, 137, 140, 143, 146, 149, 152,
  124. 155, 158, 161, 164, 167, 170, 173, 177,
  125. 181, 185, 189, 193, 197, 201, 205, 209,
  126. 213, 217, 221, 225, 229, 234, 239, 245,
  127. 249, 254, 259, 264, 269, 274, 279, 284
  128. };
  129. static const uint16_t kAcTable2[128] = {
  130. 8, 8, 9, 10, 12, 13, 15, 17,
  131. 18, 20, 21, 23, 24, 26, 27, 29,
  132. 31, 32, 34, 35, 37, 38, 40, 41,
  133. 43, 44, 46, 48, 49, 51, 52, 54,
  134. 55, 57, 58, 60, 62, 63, 65, 66,
  135. 68, 69, 71, 72, 74, 75, 77, 79,
  136. 80, 82, 83, 85, 86, 88, 89, 93,
  137. 96, 99, 102, 105, 108, 111, 114, 117,
  138. 120, 124, 127, 130, 133, 136, 139, 142,
  139. 145, 148, 151, 155, 158, 161, 164, 167,
  140. 170, 173, 176, 179, 184, 189, 193, 198,
  141. 203, 207, 212, 217, 221, 226, 230, 235,
  142. 240, 244, 249, 254, 258, 263, 268, 274,
  143. 280, 286, 292, 299, 305, 311, 317, 323,
  144. 330, 336, 342, 348, 354, 362, 370, 379,
  145. 385, 393, 401, 409, 416, 424, 432, 440
  146. };
  147. static const uint8_t kBiasMatrices[3][2] = { // [luma-ac,luma-dc,chroma][dc,ac]
  148. { 96, 110 }, { 96, 108 }, { 110, 115 }
  149. };
  150. // Sharpening by (slightly) raising the hi-frequency coeffs.
  151. // Hack-ish but helpful for mid-bitrate range. Use with care.
  152. #define SHARPEN_BITS 11 // number of descaling bits for sharpening bias
  153. static const uint8_t kFreqSharpening[16] = {
  154. 0, 30, 60, 90,
  155. 30, 60, 90, 90,
  156. 60, 90, 90, 90,
  157. 90, 90, 90, 90
  158. };
  159. //------------------------------------------------------------------------------
  160. // Initialize quantization parameters in VP8Matrix
  161. // Returns the average quantizer
  162. static int ExpandMatrix(VP8Matrix* const m, int type) {
  163. int i, sum;
  164. for (i = 0; i < 2; ++i) {
  165. const int is_ac_coeff = (i > 0);
  166. const int bias = kBiasMatrices[type][is_ac_coeff];
  167. m->iq_[i] = (1 << QFIX) / m->q_[i];
  168. m->bias_[i] = BIAS(bias);
  169. // zthresh_ is the exact value such that QUANTDIV(coeff, iQ, B) is:
  170. // * zero if coeff <= zthresh
  171. // * non-zero if coeff > zthresh
  172. m->zthresh_[i] = ((1 << QFIX) - 1 - m->bias_[i]) / m->iq_[i];
  173. }
  174. for (i = 2; i < 16; ++i) {
  175. m->q_[i] = m->q_[1];
  176. m->iq_[i] = m->iq_[1];
  177. m->bias_[i] = m->bias_[1];
  178. m->zthresh_[i] = m->zthresh_[1];
  179. }
  180. for (sum = 0, i = 0; i < 16; ++i) {
  181. if (type == 0) { // we only use sharpening for AC luma coeffs
  182. m->sharpen_[i] = (kFreqSharpening[i] * m->q_[i]) >> SHARPEN_BITS;
  183. } else {
  184. m->sharpen_[i] = 0;
  185. }
  186. sum += m->q_[i];
  187. }
  188. return (sum + 8) >> 4;
  189. }
  190. static void SetupMatrices(VP8Encoder* enc) {
  191. int i;
  192. const int tlambda_scale =
  193. (enc->method_ >= 4) ? enc->config_->sns_strength
  194. : 0;
  195. const int num_segments = enc->segment_hdr_.num_segments_;
  196. for (i = 0; i < num_segments; ++i) {
  197. VP8SegmentInfo* const m = &enc->dqm_[i];
  198. const int q = m->quant_;
  199. int q4, q16, quv;
  200. m->y1_.q_[0] = kDcTable[clip(q + enc->dq_y1_dc_, 0, 127)];
  201. m->y1_.q_[1] = kAcTable[clip(q, 0, 127)];
  202. m->y2_.q_[0] = kDcTable[ clip(q + enc->dq_y2_dc_, 0, 127)] * 2;
  203. m->y2_.q_[1] = kAcTable2[clip(q + enc->dq_y2_ac_, 0, 127)];
  204. m->uv_.q_[0] = kDcTable[clip(q + enc->dq_uv_dc_, 0, 117)];
  205. m->uv_.q_[1] = kAcTable[clip(q + enc->dq_uv_ac_, 0, 127)];
  206. q4 = ExpandMatrix(&m->y1_, 0);
  207. q16 = ExpandMatrix(&m->y2_, 1);
  208. quv = ExpandMatrix(&m->uv_, 2);
  209. m->lambda_i4_ = (3 * q4 * q4) >> 7;
  210. m->lambda_i16_ = (3 * q16 * q16);
  211. m->lambda_uv_ = (3 * quv * quv) >> 6;
  212. m->lambda_mode_ = (1 * q4 * q4) >> 7;
  213. m->lambda_trellis_i4_ = (7 * q4 * q4) >> 3;
  214. m->lambda_trellis_i16_ = (q16 * q16) >> 2;
  215. m->lambda_trellis_uv_ = (quv *quv) << 1;
  216. m->tlambda_ = (tlambda_scale * q4) >> 5;
  217. m->min_disto_ = 10 * m->y1_.q_[0]; // quantization-aware min disto
  218. m->max_edge_ = 0;
  219. }
  220. }
  221. //------------------------------------------------------------------------------
  222. // Initialize filtering parameters
  223. // Very small filter-strength values have close to no visual effect. So we can
  224. // save a little decoding-CPU by turning filtering off for these.
  225. #define FSTRENGTH_CUTOFF 2
  226. static void SetupFilterStrength(VP8Encoder* const enc) {
  227. int i;
  228. // level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering.
  229. const int level0 = 5 * enc->config_->filter_strength;
  230. for (i = 0; i < NUM_MB_SEGMENTS; ++i) {
  231. VP8SegmentInfo* const m = &enc->dqm_[i];
  232. // We focus on the quantization of AC coeffs.
  233. const int qstep = kAcTable[clip(m->quant_, 0, 127)] >> 2;
  234. const int base_strength =
  235. VP8FilterStrengthFromDelta(enc->filter_hdr_.sharpness_, qstep);
  236. // Segments with lower complexity ('beta') will be less filtered.
  237. const int f = base_strength * level0 / (256 + m->beta_);
  238. m->fstrength_ = (f < FSTRENGTH_CUTOFF) ? 0 : (f > 63) ? 63 : f;
  239. }
  240. // We record the initial strength (mainly for the case of 1-segment only).
  241. enc->filter_hdr_.level_ = enc->dqm_[0].fstrength_;
  242. enc->filter_hdr_.simple_ = (enc->config_->filter_type == 0);
  243. enc->filter_hdr_.sharpness_ = enc->config_->filter_sharpness;
  244. }
  245. //------------------------------------------------------------------------------
  246. // Note: if you change the values below, remember that the max range
  247. // allowed by the syntax for DQ_UV is [-16,16].
  248. #define MAX_DQ_UV (6)
  249. #define MIN_DQ_UV (-4)
  250. // We want to emulate jpeg-like behaviour where the expected "good" quality
  251. // is around q=75. Internally, our "good" middle is around c=50. So we
  252. // map accordingly using linear piece-wise function
  253. static double QualityToCompression(double c) {
  254. const double linear_c = (c < 0.75) ? c * (2. / 3.) : 2. * c - 1.;
  255. // The file size roughly scales as pow(quantizer, 3.). Actually, the
  256. // exponent is somewhere between 2.8 and 3.2, but we're mostly interested
  257. // in the mid-quant range. So we scale the compressibility inversely to
  258. // this power-law: quant ~= compression ^ 1/3. This law holds well for
  259. // low quant. Finer modeling for high-quant would make use of kAcTable[]
  260. // more explicitly.
  261. const double v = pow(linear_c, 1 / 3.);
  262. return v;
  263. }
  264. static double QualityToJPEGCompression(double c, double alpha) {
  265. // We map the complexity 'alpha' and quality setting 'c' to a compression
  266. // exponent empirically matched to the compression curve of libjpeg6b.
  267. // On average, the WebP output size will be roughly similar to that of a
  268. // JPEG file compressed with same quality factor.
  269. const double amin = 0.30;
  270. const double amax = 0.85;
  271. const double exp_min = 0.4;
  272. const double exp_max = 0.9;
  273. const double slope = (exp_min - exp_max) / (amax - amin);
  274. // Linearly interpolate 'expn' from exp_min to exp_max
  275. // in the [amin, amax] range.
  276. const double expn = (alpha > amax) ? exp_min
  277. : (alpha < amin) ? exp_max
  278. : exp_max + slope * (alpha - amin);
  279. const double v = pow(c, expn);
  280. return v;
  281. }
  282. static int SegmentsAreEquivalent(const VP8SegmentInfo* const S1,
  283. const VP8SegmentInfo* const S2) {
  284. return (S1->quant_ == S2->quant_) && (S1->fstrength_ == S2->fstrength_);
  285. }
  286. static void SimplifySegments(VP8Encoder* const enc) {
  287. int map[NUM_MB_SEGMENTS] = { 0, 1, 2, 3 };
  288. const int num_segments = enc->segment_hdr_.num_segments_;
  289. int num_final_segments = 1;
  290. int s1, s2;
  291. for (s1 = 1; s1 < num_segments; ++s1) { // find similar segments
  292. const VP8SegmentInfo* const S1 = &enc->dqm_[s1];
  293. int found = 0;
  294. // check if we already have similar segment
  295. for (s2 = 0; s2 < num_final_segments; ++s2) {
  296. const VP8SegmentInfo* const S2 = &enc->dqm_[s2];
  297. if (SegmentsAreEquivalent(S1, S2)) {
  298. found = 1;
  299. break;
  300. }
  301. }
  302. map[s1] = s2;
  303. if (!found) {
  304. if (num_final_segments != s1) {
  305. enc->dqm_[num_final_segments] = enc->dqm_[s1];
  306. }
  307. ++num_final_segments;
  308. }
  309. }
  310. if (num_final_segments < num_segments) { // Remap
  311. int i = enc->mb_w_ * enc->mb_h_;
  312. while (i-- > 0) enc->mb_info_[i].segment_ = map[enc->mb_info_[i].segment_];
  313. enc->segment_hdr_.num_segments_ = num_final_segments;
  314. // Replicate the trailing segment infos (it's mostly cosmetics)
  315. for (i = num_final_segments; i < num_segments; ++i) {
  316. enc->dqm_[i] = enc->dqm_[num_final_segments - 1];
  317. }
  318. }
  319. }
  320. void VP8SetSegmentParams(VP8Encoder* const enc, float quality) {
  321. int i;
  322. int dq_uv_ac, dq_uv_dc;
  323. const int num_segments = enc->segment_hdr_.num_segments_;
  324. const double amp = SNS_TO_DQ * enc->config_->sns_strength / 100. / 128.;
  325. const double Q = quality / 100.;
  326. const double c_base = enc->config_->emulate_jpeg_size ?
  327. QualityToJPEGCompression(Q, enc->alpha_ / 255.) :
  328. QualityToCompression(Q);
  329. for (i = 0; i < num_segments; ++i) {
  330. // We modulate the base coefficient to accommodate for the quantization
  331. // susceptibility and allow denser segments to be quantized more.
  332. const double expn = 1. - amp * enc->dqm_[i].alpha_;
  333. const double c = pow(c_base, expn);
  334. const int q = (int)(127. * (1. - c));
  335. assert(expn > 0.);
  336. enc->dqm_[i].quant_ = clip(q, 0, 127);
  337. }
  338. // purely indicative in the bitstream (except for the 1-segment case)
  339. enc->base_quant_ = enc->dqm_[0].quant_;
  340. // fill-in values for the unused segments (required by the syntax)
  341. for (i = num_segments; i < NUM_MB_SEGMENTS; ++i) {
  342. enc->dqm_[i].quant_ = enc->base_quant_;
  343. }
  344. // uv_alpha_ is normally spread around ~60. The useful range is
  345. // typically ~30 (quite bad) to ~100 (ok to decimate UV more).
  346. // We map it to the safe maximal range of MAX/MIN_DQ_UV for dq_uv.
  347. dq_uv_ac = (enc->uv_alpha_ - MID_ALPHA) * (MAX_DQ_UV - MIN_DQ_UV)
  348. / (MAX_ALPHA - MIN_ALPHA);
  349. // we rescale by the user-defined strength of adaptation
  350. dq_uv_ac = dq_uv_ac * enc->config_->sns_strength / 100;
  351. // and make it safe.
  352. dq_uv_ac = clip(dq_uv_ac, MIN_DQ_UV, MAX_DQ_UV);
  353. // We also boost the dc-uv-quant a little, based on sns-strength, since
  354. // U/V channels are quite more reactive to high quants (flat DC-blocks
  355. // tend to appear, and are unpleasant).
  356. dq_uv_dc = -4 * enc->config_->sns_strength / 100;
  357. dq_uv_dc = clip(dq_uv_dc, -15, 15); // 4bit-signed max allowed
  358. enc->dq_y1_dc_ = 0; // TODO(skal): dq-lum
  359. enc->dq_y2_dc_ = 0;
  360. enc->dq_y2_ac_ = 0;
  361. enc->dq_uv_dc_ = dq_uv_dc;
  362. enc->dq_uv_ac_ = dq_uv_ac;
  363. SetupFilterStrength(enc); // initialize segments' filtering, eventually
  364. if (num_segments > 1) SimplifySegments(enc);
  365. SetupMatrices(enc); // finalize quantization matrices
  366. }
  367. //------------------------------------------------------------------------------
  368. // Form the predictions in cache
  369. // Must be ordered using {DC_PRED, TM_PRED, V_PRED, H_PRED} as index
  370. const int VP8I16ModeOffsets[4] = { I16DC16, I16TM16, I16VE16, I16HE16 };
  371. const int VP8UVModeOffsets[4] = { C8DC8, C8TM8, C8VE8, C8HE8 };
  372. // Must be indexed using {B_DC_PRED -> B_HU_PRED} as index
  373. const int VP8I4ModeOffsets[NUM_BMODES] = {
  374. I4DC4, I4TM4, I4VE4, I4HE4, I4RD4, I4VR4, I4LD4, I4VL4, I4HD4, I4HU4
  375. };
  376. void VP8MakeLuma16Preds(const VP8EncIterator* const it) {
  377. const uint8_t* const left = it->x_ ? it->y_left_ : NULL;
  378. const uint8_t* const top = it->y_ ? it->y_top_ : NULL;
  379. VP8EncPredLuma16(it->yuv_p_, left, top);
  380. }
  381. void VP8MakeChroma8Preds(const VP8EncIterator* const it) {
  382. const uint8_t* const left = it->x_ ? it->u_left_ : NULL;
  383. const uint8_t* const top = it->y_ ? it->uv_top_ : NULL;
  384. VP8EncPredChroma8(it->yuv_p_, left, top);
  385. }
  386. void VP8MakeIntra4Preds(const VP8EncIterator* const it) {
  387. VP8EncPredLuma4(it->yuv_p_, it->i4_top_);
  388. }
  389. //------------------------------------------------------------------------------
  390. // Quantize
  391. // Layout:
  392. // +----+
  393. // |YYYY| 0
  394. // |YYYY| 4
  395. // |YYYY| 8
  396. // |YYYY| 12
  397. // +----+
  398. // |UUVV| 16
  399. // |UUVV| 20
  400. // +----+
  401. const int VP8Scan[16] = { // Luma
  402. 0 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS,
  403. 0 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS,
  404. 0 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS,
  405. 0 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS,
  406. };
  407. static const int VP8ScanUV[4 + 4] = {
  408. 0 + 0 * BPS, 4 + 0 * BPS, 0 + 4 * BPS, 4 + 4 * BPS, // U
  409. 8 + 0 * BPS, 12 + 0 * BPS, 8 + 4 * BPS, 12 + 4 * BPS // V
  410. };
  411. //------------------------------------------------------------------------------
  412. // Distortion measurement
  413. static const uint16_t kWeightY[16] = {
  414. 38, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2
  415. };
  416. static const uint16_t kWeightTrellis[16] = {
  417. #if USE_TDISTO == 0
  418. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16
  419. #else
  420. 30, 27, 19, 11,
  421. 27, 24, 17, 10,
  422. 19, 17, 12, 8,
  423. 11, 10, 8, 6
  424. #endif
  425. };
  426. // Init/Copy the common fields in score.
  427. static void InitScore(VP8ModeScore* const rd) {
  428. rd->D = 0;
  429. rd->SD = 0;
  430. rd->R = 0;
  431. rd->H = 0;
  432. rd->nz = 0;
  433. rd->score = MAX_COST;
  434. }
  435. static void CopyScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {
  436. dst->D = src->D;
  437. dst->SD = src->SD;
  438. dst->R = src->R;
  439. dst->H = src->H;
  440. dst->nz = src->nz; // note that nz is not accumulated, but just copied.
  441. dst->score = src->score;
  442. }
  443. static void AddScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {
  444. dst->D += src->D;
  445. dst->SD += src->SD;
  446. dst->R += src->R;
  447. dst->H += src->H;
  448. dst->nz |= src->nz; // here, new nz bits are accumulated.
  449. dst->score += src->score;
  450. }
  451. //------------------------------------------------------------------------------
  452. // Performs trellis-optimized quantization.
  453. // Trellis node
  454. typedef struct {
  455. int8_t prev; // best previous node
  456. int8_t sign; // sign of coeff_i
  457. int16_t level; // level
  458. } Node;
  459. // Score state
  460. typedef struct {
  461. score_t score; // partial RD score
  462. const uint16_t* costs; // shortcut to cost tables
  463. } ScoreState;
  464. // If a coefficient was quantized to a value Q (using a neutral bias),
  465. // we test all alternate possibilities between [Q-MIN_DELTA, Q+MAX_DELTA]
  466. // We don't test negative values though.
  467. #define MIN_DELTA 0 // how much lower level to try
  468. #define MAX_DELTA 1 // how much higher
  469. #define NUM_NODES (MIN_DELTA + 1 + MAX_DELTA)
  470. #define NODE(n, l) (nodes[(n)][(l) + MIN_DELTA])
  471. #define SCORE_STATE(n, l) (score_states[n][(l) + MIN_DELTA])
  472. static WEBP_INLINE void SetRDScore(int lambda, VP8ModeScore* const rd) {
  473. // TODO: incorporate the "* 256" in the tables?
  474. rd->score = (rd->R + rd->H) * lambda + 256 * (rd->D + rd->SD);
  475. }
  476. static WEBP_INLINE score_t RDScoreTrellis(int lambda, score_t rate,
  477. score_t distortion) {
  478. return rate * lambda + 256 * distortion;
  479. }
  480. static int TrellisQuantizeBlock(const VP8Encoder* const enc,
  481. int16_t in[16], int16_t out[16],
  482. int ctx0, int coeff_type,
  483. const VP8Matrix* const mtx,
  484. int lambda) {
  485. const ProbaArray* const probas = enc->proba_.coeffs_[coeff_type];
  486. const CostArray* const costs = enc->proba_.level_cost_[coeff_type];
  487. const int first = (coeff_type == 0) ? 1 : 0;
  488. Node nodes[16][NUM_NODES];
  489. ScoreState score_states[2][NUM_NODES];
  490. ScoreState* ss_cur = &SCORE_STATE(0, MIN_DELTA);
  491. ScoreState* ss_prev = &SCORE_STATE(1, MIN_DELTA);
  492. int best_path[3] = {-1, -1, -1}; // store best-last/best-level/best-previous
  493. score_t best_score;
  494. int n, m, p, last;
  495. {
  496. score_t cost;
  497. const int thresh = mtx->q_[1] * mtx->q_[1] / 4;
  498. const int last_proba = probas[VP8EncBands[first]][ctx0][0];
  499. // compute the position of the last interesting coefficient
  500. last = first - 1;
  501. for (n = 15; n >= first; --n) {
  502. const int j = kZigzag[n];
  503. const int err = in[j] * in[j];
  504. if (err > thresh) {
  505. last = n;
  506. break;
  507. }
  508. }
  509. // we don't need to go inspect up to n = 16 coeffs. We can just go up
  510. // to last + 1 (inclusive) without losing much.
  511. if (last < 15) ++last;
  512. // compute 'skip' score. This is the max score one can do.
  513. cost = VP8BitCost(0, last_proba);
  514. best_score = RDScoreTrellis(lambda, cost, 0);
  515. // initialize source node.
  516. for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {
  517. const score_t rate = (ctx0 == 0) ? VP8BitCost(1, last_proba) : 0;
  518. ss_cur[m].score = RDScoreTrellis(lambda, rate, 0);
  519. ss_cur[m].costs = costs[VP8EncBands[first]][ctx0];
  520. }
  521. }
  522. // traverse trellis.
  523. for (n = first; n <= last; ++n) {
  524. const int j = kZigzag[n];
  525. const uint32_t Q = mtx->q_[j];
  526. const uint32_t iQ = mtx->iq_[j];
  527. const uint32_t B = BIAS(0x00); // neutral bias
  528. // note: it's important to take sign of the _original_ coeff,
  529. // so we don't have to consider level < 0 afterward.
  530. const int sign = (in[j] < 0);
  531. const uint32_t coeff0 = (sign ? -in[j] : in[j]) + mtx->sharpen_[j];
  532. int level0 = QUANTDIV(coeff0, iQ, B);
  533. if (level0 > MAX_LEVEL) level0 = MAX_LEVEL;
  534. { // Swap current and previous score states
  535. ScoreState* const tmp = ss_cur;
  536. ss_cur = ss_prev;
  537. ss_prev = tmp;
  538. }
  539. // test all alternate level values around level0.
  540. for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {
  541. Node* const cur = &NODE(n, m);
  542. int level = level0 + m;
  543. const int ctx = (level > 2) ? 2 : level;
  544. const int band = VP8EncBands[n + 1];
  545. score_t base_score, last_pos_score;
  546. score_t best_cur_score = MAX_COST;
  547. int best_prev = 0; // default, in case
  548. ss_cur[m].score = MAX_COST;
  549. ss_cur[m].costs = costs[band][ctx];
  550. if (level > MAX_LEVEL || level < 0) { // node is dead?
  551. continue;
  552. }
  553. // Compute extra rate cost if last coeff's position is < 15
  554. {
  555. const score_t last_pos_cost =
  556. (n < 15) ? VP8BitCost(0, probas[band][ctx][0]) : 0;
  557. last_pos_score = RDScoreTrellis(lambda, last_pos_cost, 0);
  558. }
  559. {
  560. // Compute delta_error = how much coding this level will
  561. // subtract to max_error as distortion.
  562. // Here, distortion = sum of (|coeff_i| - level_i * Q_i)^2
  563. const int new_error = coeff0 - level * Q;
  564. const int delta_error =
  565. kWeightTrellis[j] * (new_error * new_error - coeff0 * coeff0);
  566. base_score = RDScoreTrellis(lambda, 0, delta_error);
  567. }
  568. // Inspect all possible non-dead predecessors. Retain only the best one.
  569. for (p = -MIN_DELTA; p <= MAX_DELTA; ++p) {
  570. // Dead nodes (with ss_prev[p].score >= MAX_COST) are automatically
  571. // eliminated since their score can't be better than the current best.
  572. const score_t cost = VP8LevelCost(ss_prev[p].costs, level);
  573. // Examine node assuming it's a non-terminal one.
  574. const score_t score =
  575. base_score + ss_prev[p].score + RDScoreTrellis(lambda, cost, 0);
  576. if (score < best_cur_score) {
  577. best_cur_score = score;
  578. best_prev = p;
  579. }
  580. }
  581. // Store best finding in current node.
  582. cur->sign = sign;
  583. cur->level = level;
  584. cur->prev = best_prev;
  585. ss_cur[m].score = best_cur_score;
  586. // Now, record best terminal node (and thus best entry in the graph).
  587. if (level != 0) {
  588. const score_t score = best_cur_score + last_pos_score;
  589. if (score < best_score) {
  590. best_score = score;
  591. best_path[0] = n; // best eob position
  592. best_path[1] = m; // best node index
  593. best_path[2] = best_prev; // best predecessor
  594. }
  595. }
  596. }
  597. }
  598. // Fresh start
  599. memset(in + first, 0, (16 - first) * sizeof(*in));
  600. memset(out + first, 0, (16 - first) * sizeof(*out));
  601. if (best_path[0] == -1) {
  602. return 0; // skip!
  603. }
  604. {
  605. // Unwind the best path.
  606. // Note: best-prev on terminal node is not necessarily equal to the
  607. // best_prev for non-terminal. So we patch best_path[2] in.
  608. int nz = 0;
  609. int best_node = best_path[1];
  610. n = best_path[0];
  611. NODE(n, best_node).prev = best_path[2]; // force best-prev for terminal
  612. for (; n >= first; --n) {
  613. const Node* const node = &NODE(n, best_node);
  614. const int j = kZigzag[n];
  615. out[n] = node->sign ? -node->level : node->level;
  616. nz |= node->level;
  617. in[j] = out[n] * mtx->q_[j];
  618. best_node = node->prev;
  619. }
  620. return (nz != 0);
  621. }
  622. }
  623. #undef NODE
  624. //------------------------------------------------------------------------------
  625. // Performs: difference, transform, quantize, back-transform, add
  626. // all at once. Output is the reconstructed block in *yuv_out, and the
  627. // quantized levels in *levels.
  628. static int ReconstructIntra16(VP8EncIterator* const it,
  629. VP8ModeScore* const rd,
  630. uint8_t* const yuv_out,
  631. int mode) {
  632. const VP8Encoder* const enc = it->enc_;
  633. const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];
  634. const uint8_t* const src = it->yuv_in_ + Y_OFF;
  635. const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];
  636. int nz = 0;
  637. int n;
  638. int16_t tmp[16][16], dc_tmp[16];
  639. for (n = 0; n < 16; ++n) {
  640. VP8FTransform(src + VP8Scan[n], ref + VP8Scan[n], tmp[n]);
  641. }
  642. VP8FTransformWHT(tmp[0], dc_tmp);
  643. nz |= VP8EncQuantizeBlockWHT(dc_tmp, rd->y_dc_levels, &dqm->y2_) << 24;
  644. if (DO_TRELLIS_I16 && it->do_trellis_) {
  645. int x, y;
  646. VP8IteratorNzToBytes(it);
  647. for (y = 0, n = 0; y < 4; ++y) {
  648. for (x = 0; x < 4; ++x, ++n) {
  649. const int ctx = it->top_nz_[x] + it->left_nz_[y];
  650. const int non_zero =
  651. TrellisQuantizeBlock(enc, tmp[n], rd->y_ac_levels[n], ctx, 0,
  652. &dqm->y1_, dqm->lambda_trellis_i16_);
  653. it->top_nz_[x] = it->left_nz_[y] = non_zero;
  654. rd->y_ac_levels[n][0] = 0;
  655. nz |= non_zero << n;
  656. }
  657. }
  658. } else {
  659. for (n = 0; n < 16; ++n) {
  660. // Zero-out the first coeff, so that: a) nz is correct below, and
  661. // b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified.
  662. tmp[n][0] = 0;
  663. nz |= VP8EncQuantizeBlock(tmp[n], rd->y_ac_levels[n], &dqm->y1_) << n;
  664. assert(rd->y_ac_levels[n][0] == 0);
  665. }
  666. }
  667. // Transform back
  668. VP8TransformWHT(dc_tmp, tmp[0]);
  669. for (n = 0; n < 16; n += 2) {
  670. VP8ITransform(ref + VP8Scan[n], tmp[n], yuv_out + VP8Scan[n], 1);
  671. }
  672. return nz;
  673. }
  674. static int ReconstructIntra4(VP8EncIterator* const it,
  675. int16_t levels[16],
  676. const uint8_t* const src,
  677. uint8_t* const yuv_out,
  678. int mode) {
  679. const VP8Encoder* const enc = it->enc_;
  680. const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];
  681. const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];
  682. int nz = 0;
  683. int16_t tmp[16];
  684. VP8FTransform(src, ref, tmp);
  685. if (DO_TRELLIS_I4 && it->do_trellis_) {
  686. const int x = it->i4_ & 3, y = it->i4_ >> 2;
  687. const int ctx = it->top_nz_[x] + it->left_nz_[y];
  688. nz = TrellisQuantizeBlock(enc, tmp, levels, ctx, 3, &dqm->y1_,
  689. dqm->lambda_trellis_i4_);
  690. } else {
  691. nz = VP8EncQuantizeBlock(tmp, levels, &dqm->y1_);
  692. }
  693. VP8ITransform(ref, tmp, yuv_out, 0);
  694. return nz;
  695. }
  696. static int ReconstructUV(VP8EncIterator* const it, VP8ModeScore* const rd,
  697. uint8_t* const yuv_out, int mode) {
  698. const VP8Encoder* const enc = it->enc_;
  699. const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode];
  700. const uint8_t* const src = it->yuv_in_ + U_OFF;
  701. const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];
  702. int nz = 0;
  703. int n;
  704. int16_t tmp[8][16];
  705. for (n = 0; n < 8; ++n) {
  706. VP8FTransform(src + VP8ScanUV[n], ref + VP8ScanUV[n], tmp[n]);
  707. }
  708. if (DO_TRELLIS_UV && it->do_trellis_) {
  709. int ch, x, y;
  710. for (ch = 0, n = 0; ch <= 2; ch += 2) {
  711. for (y = 0; y < 2; ++y) {
  712. for (x = 0; x < 2; ++x, ++n) {
  713. const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];
  714. const int non_zero =
  715. TrellisQuantizeBlock(enc, tmp[n], rd->uv_levels[n], ctx, 2,
  716. &dqm->uv_, dqm->lambda_trellis_uv_);
  717. it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = non_zero;
  718. nz |= non_zero << n;
  719. }
  720. }
  721. }
  722. } else {
  723. for (n = 0; n < 8; ++n) {
  724. nz |= VP8EncQuantizeBlock(tmp[n], rd->uv_levels[n], &dqm->uv_) << n;
  725. }
  726. }
  727. for (n = 0; n < 8; n += 2) {
  728. VP8ITransform(ref + VP8ScanUV[n], tmp[n], yuv_out + VP8ScanUV[n], 1);
  729. }
  730. return (nz << 16);
  731. }
  732. //------------------------------------------------------------------------------
  733. // RD-opt decision. Reconstruct each modes, evalue distortion and bit-cost.
  734. // Pick the mode is lower RD-cost = Rate + lambda * Distortion.
  735. static void StoreMaxDelta(VP8SegmentInfo* const dqm, const int16_t DCs[16]) {
  736. // We look at the first three AC coefficients to determine what is the average
  737. // delta between each sub-4x4 block.
  738. const int v0 = abs(DCs[1]);
  739. const int v1 = abs(DCs[4]);
  740. const int v2 = abs(DCs[5]);
  741. int max_v = (v0 > v1) ? v1 : v0;
  742. max_v = (v2 > max_v) ? v2 : max_v;
  743. if (max_v > dqm->max_edge_) dqm->max_edge_ = max_v;
  744. }
  745. static void SwapPtr(uint8_t** a, uint8_t** b) {
  746. uint8_t* const tmp = *a;
  747. *a = *b;
  748. *b = tmp;
  749. }
  750. static void SwapOut(VP8EncIterator* const it) {
  751. SwapPtr(&it->yuv_out_, &it->yuv_out2_);
  752. }
  753. static score_t IsFlat(const int16_t* levels, int num_blocks, score_t thresh) {
  754. score_t score = 0;
  755. while (num_blocks-- > 0) { // TODO(skal): refine positional scoring?
  756. int i;
  757. for (i = 1; i < 16; ++i) { // omit DC, we're only interested in AC
  758. score += (levels[i] != 0);
  759. if (score > thresh) return 0;
  760. }
  761. levels += 16;
  762. }
  763. return 1;
  764. }
  765. static void PickBestIntra16(VP8EncIterator* const it, VP8ModeScore* const rd) {
  766. const int kNumBlocks = 16;
  767. VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];
  768. const int lambda = dqm->lambda_i16_;
  769. const int tlambda = dqm->tlambda_;
  770. const uint8_t* const src = it->yuv_in_ + Y_OFF;
  771. VP8ModeScore rd16;
  772. int mode;
  773. rd->mode_i16 = -1;
  774. for (mode = 0; mode < NUM_PRED_MODES; ++mode) {
  775. uint8_t* const tmp_dst = it->yuv_out2_ + Y_OFF; // scratch buffer
  776. int nz;
  777. // Reconstruct
  778. nz = ReconstructIntra16(it, &rd16, tmp_dst, mode);
  779. // Measure RD-score
  780. rd16.D = VP8SSE16x16(src, tmp_dst);
  781. rd16.SD = tlambda ? MULT_8B(tlambda, VP8TDisto16x16(src, tmp_dst, kWeightY))
  782. : 0;
  783. rd16.H = VP8FixedCostsI16[mode];
  784. rd16.R = VP8GetCostLuma16(it, &rd16);
  785. if (mode > 0 &&
  786. IsFlat(rd16.y_ac_levels[0], kNumBlocks, FLATNESS_LIMIT_I16)) {
  787. // penalty to avoid flat area to be mispredicted by complex mode
  788. rd16.R += FLATNESS_PENALTY * kNumBlocks;
  789. }
  790. // Since we always examine Intra16 first, we can overwrite *rd directly.
  791. SetRDScore(lambda, &rd16);
  792. if (mode == 0 || rd16.score < rd->score) {
  793. CopyScore(rd, &rd16);
  794. rd->mode_i16 = mode;
  795. rd->nz = nz;
  796. memcpy(rd->y_ac_levels, rd16.y_ac_levels, sizeof(rd16.y_ac_levels));
  797. memcpy(rd->y_dc_levels, rd16.y_dc_levels, sizeof(rd16.y_dc_levels));
  798. SwapOut(it);
  799. }
  800. }
  801. SetRDScore(dqm->lambda_mode_, rd); // finalize score for mode decision.
  802. VP8SetIntra16Mode(it, rd->mode_i16);
  803. // we have a blocky macroblock (only DCs are non-zero) with fairly high
  804. // distortion, record max delta so we can later adjust the minimal filtering
  805. // strength needed to smooth these blocks out.
  806. if ((rd->nz & 0xffff) == 0 && rd->D > dqm->min_disto_) {
  807. StoreMaxDelta(dqm, rd->y_dc_levels);
  808. }
  809. }
  810. //------------------------------------------------------------------------------
  811. // return the cost array corresponding to the surrounding prediction modes.
  812. static const uint16_t* GetCostModeI4(VP8EncIterator* const it,
  813. const uint8_t modes[16]) {
  814. const int preds_w = it->enc_->preds_w_;
  815. const int x = (it->i4_ & 3), y = it->i4_ >> 2;
  816. const int left = (x == 0) ? it->preds_[y * preds_w - 1] : modes[it->i4_ - 1];
  817. const int top = (y == 0) ? it->preds_[-preds_w + x] : modes[it->i4_ - 4];
  818. return VP8FixedCostsI4[top][left];
  819. }
  820. static int PickBestIntra4(VP8EncIterator* const it, VP8ModeScore* const rd) {
  821. const VP8Encoder* const enc = it->enc_;
  822. const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];
  823. const int lambda = dqm->lambda_i4_;
  824. const int tlambda = dqm->tlambda_;
  825. const uint8_t* const src0 = it->yuv_in_ + Y_OFF;
  826. uint8_t* const best_blocks = it->yuv_out2_ + Y_OFF;
  827. int total_header_bits = 0;
  828. VP8ModeScore rd_best;
  829. if (enc->max_i4_header_bits_ == 0) {
  830. return 0;
  831. }
  832. InitScore(&rd_best);
  833. rd_best.H = 211; // '211' is the value of VP8BitCost(0, 145)
  834. SetRDScore(dqm->lambda_mode_, &rd_best);
  835. VP8IteratorStartI4(it);
  836. do {
  837. const int kNumBlocks = 1;
  838. VP8ModeScore rd_i4;
  839. int mode;
  840. int best_mode = -1;
  841. const uint8_t* const src = src0 + VP8Scan[it->i4_];
  842. const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);
  843. uint8_t* best_block = best_blocks + VP8Scan[it->i4_];
  844. uint8_t* tmp_dst = it->yuv_p_ + I4TMP; // scratch buffer.
  845. InitScore(&rd_i4);
  846. VP8MakeIntra4Preds(it);
  847. for (mode = 0; mode < NUM_BMODES; ++mode) {
  848. VP8ModeScore rd_tmp;
  849. int16_t tmp_levels[16];
  850. // Reconstruct
  851. rd_tmp.nz =
  852. ReconstructIntra4(it, tmp_levels, src, tmp_dst, mode) << it->i4_;
  853. // Compute RD-score
  854. rd_tmp.D = VP8SSE4x4(src, tmp_dst);
  855. rd_tmp.SD =
  856. tlambda ? MULT_8B(tlambda, VP8TDisto4x4(src, tmp_dst, kWeightY))
  857. : 0;
  858. rd_tmp.H = mode_costs[mode];
  859. rd_tmp.R = VP8GetCostLuma4(it, tmp_levels);
  860. if (mode > 0 && IsFlat(tmp_levels, kNumBlocks, FLATNESS_LIMIT_I4)) {
  861. rd_tmp.R += FLATNESS_PENALTY * kNumBlocks;
  862. }
  863. SetRDScore(lambda, &rd_tmp);
  864. if (best_mode < 0 || rd_tmp.score < rd_i4.score) {
  865. CopyScore(&rd_i4, &rd_tmp);
  866. best_mode = mode;
  867. SwapPtr(&tmp_dst, &best_block);
  868. memcpy(rd_best.y_ac_levels[it->i4_], tmp_levels, sizeof(tmp_levels));
  869. }
  870. }
  871. SetRDScore(dqm->lambda_mode_, &rd_i4);
  872. AddScore(&rd_best, &rd_i4);
  873. if (rd_best.score >= rd->score) {
  874. return 0;
  875. }
  876. total_header_bits += (int)rd_i4.H; // <- equal to mode_costs[best_mode];
  877. if (total_header_bits > enc->max_i4_header_bits_) {
  878. return 0;
  879. }
  880. // Copy selected samples if not in the right place already.
  881. if (best_block != best_blocks + VP8Scan[it->i4_]) {
  882. VP8Copy4x4(best_block, best_blocks + VP8Scan[it->i4_]);
  883. }
  884. rd->modes_i4[it->i4_] = best_mode;
  885. it->top_nz_[it->i4_ & 3] = it->left_nz_[it->i4_ >> 2] = (rd_i4.nz ? 1 : 0);
  886. } while (VP8IteratorRotateI4(it, best_blocks));
  887. // finalize state
  888. CopyScore(rd, &rd_best);
  889. VP8SetIntra4Mode(it, rd->modes_i4);
  890. SwapOut(it);
  891. memcpy(rd->y_ac_levels, rd_best.y_ac_levels, sizeof(rd->y_ac_levels));
  892. return 1; // select intra4x4 over intra16x16
  893. }
  894. //------------------------------------------------------------------------------
  895. static void PickBestUV(VP8EncIterator* const it, VP8ModeScore* const rd) {
  896. const int kNumBlocks = 8;
  897. const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];
  898. const int lambda = dqm->lambda_uv_;
  899. const uint8_t* const src = it->yuv_in_ + U_OFF;
  900. uint8_t* const tmp_dst = it->yuv_out2_ + U_OFF; // scratch buffer
  901. uint8_t* const dst0 = it->yuv_out_ + U_OFF;
  902. VP8ModeScore rd_best;
  903. int mode;
  904. rd->mode_uv = -1;
  905. InitScore(&rd_best);
  906. for (mode = 0; mode < NUM_PRED_MODES; ++mode) {
  907. VP8ModeScore rd_uv;
  908. // Reconstruct
  909. rd_uv.nz = ReconstructUV(it, &rd_uv, tmp_dst, mode);
  910. // Compute RD-score
  911. rd_uv.D = VP8SSE16x8(src, tmp_dst);
  912. rd_uv.SD = 0; // TODO: should we call TDisto? it tends to flatten areas.
  913. rd_uv.H = VP8FixedCostsUV[mode];
  914. rd_uv.R = VP8GetCostUV(it, &rd_uv);
  915. if (mode > 0 && IsFlat(rd_uv.uv_levels[0], kNumBlocks, FLATNESS_LIMIT_UV)) {
  916. rd_uv.R += FLATNESS_PENALTY * kNumBlocks;
  917. }
  918. SetRDScore(lambda, &rd_uv);
  919. if (mode == 0 || rd_uv.score < rd_best.score) {
  920. CopyScore(&rd_best, &rd_uv);
  921. rd->mode_uv = mode;
  922. memcpy(rd->uv_levels, rd_uv.uv_levels, sizeof(rd->uv_levels));
  923. memcpy(dst0, tmp_dst, UV_SIZE); // TODO: SwapUVOut() ?
  924. }
  925. }
  926. VP8SetIntraUVMode(it, rd->mode_uv);
  927. AddScore(rd, &rd_best);
  928. }
  929. //------------------------------------------------------------------------------
  930. // Final reconstruction and quantization.
  931. static void SimpleQuantize(VP8EncIterator* const it, VP8ModeScore* const rd) {
  932. const VP8Encoder* const enc = it->enc_;
  933. const int is_i16 = (it->mb_->type_ == 1);
  934. int nz = 0;
  935. if (is_i16) {
  936. nz = ReconstructIntra16(it, rd, it->yuv_out_ + Y_OFF, it->preds_[0]);
  937. } else {
  938. VP8IteratorStartI4(it);
  939. do {
  940. const int mode =
  941. it->preds_[(it->i4_ & 3) + (it->i4_ >> 2) * enc->preds_w_];
  942. const uint8_t* const src = it->yuv_in_ + Y_OFF + VP8Scan[it->i4_];
  943. uint8_t* const dst = it->yuv_out_ + Y_OFF + VP8Scan[it->i4_];
  944. VP8MakeIntra4Preds(it);
  945. nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4_],
  946. src, dst, mode) << it->i4_;
  947. } while (VP8IteratorRotateI4(it, it->yuv_out_ + Y_OFF));
  948. }
  949. nz |= ReconstructUV(it, rd, it->yuv_out_ + U_OFF, it->mb_->uv_mode_);
  950. rd->nz = nz;
  951. }
  952. // Refine intra16/intra4 sub-modes based on distortion only (not rate).
  953. static void DistoRefine(VP8EncIterator* const it, int try_both_i4_i16) {
  954. const int is_i16 = (it->mb_->type_ == 1);
  955. score_t best_score = MAX_COST;
  956. if (try_both_i4_i16 || is_i16) {
  957. int mode;
  958. int best_mode = -1;
  959. for (mode = 0; mode < NUM_PRED_MODES; ++mode) {
  960. const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];
  961. const uint8_t* const src = it->yuv_in_ + Y_OFF;
  962. const score_t score = VP8SSE16x16(src, ref);
  963. if (score < best_score) {
  964. best_mode = mode;
  965. best_score = score;
  966. }
  967. }
  968. VP8SetIntra16Mode(it, best_mode);
  969. }
  970. if (try_both_i4_i16 || !is_i16) {
  971. uint8_t modes_i4[16];
  972. // We don't evaluate the rate here, but just account for it through a
  973. // constant penalty (i4 mode usually needs more bits compared to i16).
  974. score_t score_i4 = (score_t)I4_PENALTY;
  975. VP8IteratorStartI4(it);
  976. do {
  977. int mode;
  978. int best_sub_mode = -1;
  979. score_t best_sub_score = MAX_COST;
  980. const uint8_t* const src = it->yuv_in_ + Y_OFF + VP8Scan[it->i4_];
  981. // TODO(skal): we don't really need the prediction pixels here,
  982. // but just the distortion against 'src'.
  983. VP8MakeIntra4Preds(it);
  984. for (mode = 0; mode < NUM_BMODES; ++mode) {
  985. const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];
  986. const score_t score = VP8SSE4x4(src, ref);
  987. if (score < best_sub_score) {
  988. best_sub_mode = mode;
  989. best_sub_score = score;
  990. }
  991. }
  992. modes_i4[it->i4_] = best_sub_mode;
  993. score_i4 += best_sub_score;
  994. if (score_i4 >= best_score) break;
  995. } while (VP8IteratorRotateI4(it, it->yuv_in_ + Y_OFF));
  996. if (score_i4 < best_score) {
  997. VP8SetIntra4Mode(it, modes_i4);
  998. }
  999. }
  1000. }
  1001. //------------------------------------------------------------------------------
  1002. // Entry point
  1003. int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd,
  1004. VP8RDLevel rd_opt) {
  1005. int is_skipped;
  1006. const int method = it->enc_->method_;
  1007. InitScore(rd);
  1008. // We can perform predictions for Luma16x16 and Chroma8x8 already.
  1009. // Luma4x4 predictions needs to be done as-we-go.
  1010. VP8MakeLuma16Preds(it);
  1011. VP8MakeChroma8Preds(it);
  1012. if (rd_opt > RD_OPT_NONE) {
  1013. it->do_trellis_ = (rd_opt >= RD_OPT_TRELLIS_ALL);
  1014. PickBestIntra16(it, rd);
  1015. if (method >= 2) {
  1016. PickBestIntra4(it, rd);
  1017. }
  1018. PickBestUV(it, rd);
  1019. if (rd_opt == RD_OPT_TRELLIS) { // finish off with trellis-optim now
  1020. it->do_trellis_ = 1;
  1021. SimpleQuantize(it, rd);
  1022. }
  1023. } else {
  1024. // For method == 2, pick the best intra4/intra16 based on SSE (~tad slower).
  1025. // For method <= 1, we refine intra4 or intra16 (but don't re-examine mode).
  1026. DistoRefine(it, (method >= 2));
  1027. SimpleQuantize(it, rd);
  1028. }
  1029. is_skipped = (rd->nz == 0);
  1030. VP8SetSkip(it, is_skipped);
  1031. return is_skipped;
  1032. }