webp_enc.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. // WebP encoder: main entry point
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #include <assert.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <math.h>
  17. #include "./cost_enc.h"
  18. #include "./vp8i_enc.h"
  19. #include "./vp8li_enc.h"
  20. #include "../utils/utils.h"
  21. // #define PRINT_MEMORY_INFO
  22. #ifdef PRINT_MEMORY_INFO
  23. #include <stdio.h>
  24. #endif
  25. //------------------------------------------------------------------------------
  26. int WebPGetEncoderVersion(void) {
  27. return (ENC_MAJ_VERSION << 16) | (ENC_MIN_VERSION << 8) | ENC_REV_VERSION;
  28. }
  29. //------------------------------------------------------------------------------
  30. // VP8Encoder
  31. //------------------------------------------------------------------------------
  32. static void ResetSegmentHeader(VP8Encoder* const enc) {
  33. VP8EncSegmentHeader* const hdr = &enc->segment_hdr_;
  34. hdr->num_segments_ = enc->config_->segments;
  35. hdr->update_map_ = (hdr->num_segments_ > 1);
  36. hdr->size_ = 0;
  37. }
  38. static void ResetFilterHeader(VP8Encoder* const enc) {
  39. VP8EncFilterHeader* const hdr = &enc->filter_hdr_;
  40. hdr->simple_ = 1;
  41. hdr->level_ = 0;
  42. hdr->sharpness_ = 0;
  43. hdr->i4x4_lf_delta_ = 0;
  44. }
  45. static void ResetBoundaryPredictions(VP8Encoder* const enc) {
  46. // init boundary values once for all
  47. // Note: actually, initializing the preds_[] is only needed for intra4.
  48. int i;
  49. uint8_t* const top = enc->preds_ - enc->preds_w_;
  50. uint8_t* const left = enc->preds_ - 1;
  51. for (i = -1; i < 4 * enc->mb_w_; ++i) {
  52. top[i] = B_DC_PRED;
  53. }
  54. for (i = 0; i < 4 * enc->mb_h_; ++i) {
  55. left[i * enc->preds_w_] = B_DC_PRED;
  56. }
  57. enc->nz_[-1] = 0; // constant
  58. }
  59. // Mapping from config->method_ to coding tools used.
  60. //-------------------+---+---+---+---+---+---+---+
  61. // Method | 0 | 1 | 2 | 3 |(4)| 5 | 6 |
  62. //-------------------+---+---+---+---+---+---+---+
  63. // fast probe | x | | | x | | | |
  64. //-------------------+---+---+---+---+---+---+---+
  65. // dynamic proba | ~ | x | x | x | x | x | x |
  66. //-------------------+---+---+---+---+---+---+---+
  67. // fast mode analysis|[x]|[x]| | | x | x | x |
  68. //-------------------+---+---+---+---+---+---+---+
  69. // basic rd-opt | | | | x | x | x | x |
  70. //-------------------+---+---+---+---+---+---+---+
  71. // disto-refine i4/16| x | x | x | | | | |
  72. //-------------------+---+---+---+---+---+---+---+
  73. // disto-refine uv | | x | x | | | | |
  74. //-------------------+---+---+---+---+---+---+---+
  75. // rd-opt i4/16 | | | ~ | x | x | x | x |
  76. //-------------------+---+---+---+---+---+---+---+
  77. // token buffer (opt)| | | | x | x | x | x |
  78. //-------------------+---+---+---+---+---+---+---+
  79. // Trellis | | | | | | x |Ful|
  80. //-------------------+---+---+---+---+---+---+---+
  81. // full-SNS | | | | | x | x | x |
  82. //-------------------+---+---+---+---+---+---+---+
  83. static void MapConfigToTools(VP8Encoder* const enc) {
  84. const WebPConfig* const config = enc->config_;
  85. const int method = config->method;
  86. const int limit = 100 - config->partition_limit;
  87. enc->method_ = method;
  88. enc->rd_opt_level_ = (method >= 6) ? RD_OPT_TRELLIS_ALL
  89. : (method >= 5) ? RD_OPT_TRELLIS
  90. : (method >= 3) ? RD_OPT_BASIC
  91. : RD_OPT_NONE;
  92. enc->max_i4_header_bits_ =
  93. 256 * 16 * 16 * // upper bound: up to 16bit per 4x4 block
  94. (limit * limit) / (100 * 100); // ... modulated with a quadratic curve.
  95. // partition0 = 512k max.
  96. enc->mb_header_limit_ =
  97. (score_t)256 * 510 * 8 * 1024 / (enc->mb_w_ * enc->mb_h_);
  98. enc->thread_level_ = config->thread_level;
  99. enc->do_search_ = (config->target_size > 0 || config->target_PSNR > 0);
  100. if (!config->low_memory) {
  101. #if !defined(DISABLE_TOKEN_BUFFER)
  102. enc->use_tokens_ = (enc->rd_opt_level_ >= RD_OPT_BASIC); // need rd stats
  103. #endif
  104. if (enc->use_tokens_) {
  105. enc->num_parts_ = 1; // doesn't work with multi-partition
  106. }
  107. }
  108. }
  109. // Memory scaling with dimensions:
  110. // memory (bytes) ~= 2.25 * w + 0.0625 * w * h
  111. //
  112. // Typical memory footprint (614x440 picture)
  113. // encoder: 22111
  114. // info: 4368
  115. // preds: 17741
  116. // top samples: 1263
  117. // non-zero: 175
  118. // lf-stats: 0
  119. // total: 45658
  120. // Transient object sizes:
  121. // VP8EncIterator: 3360
  122. // VP8ModeScore: 872
  123. // VP8SegmentInfo: 732
  124. // VP8EncProba: 18352
  125. // LFStats: 2048
  126. // Picture size (yuv): 419328
  127. static VP8Encoder* InitVP8Encoder(const WebPConfig* const config,
  128. WebPPicture* const picture) {
  129. VP8Encoder* enc;
  130. const int use_filter =
  131. (config->filter_strength > 0) || (config->autofilter > 0);
  132. const int mb_w = (picture->width + 15) >> 4;
  133. const int mb_h = (picture->height + 15) >> 4;
  134. const int preds_w = 4 * mb_w + 1;
  135. const int preds_h = 4 * mb_h + 1;
  136. const size_t preds_size = preds_w * preds_h * sizeof(*enc->preds_);
  137. const int top_stride = mb_w * 16;
  138. const size_t nz_size = (mb_w + 1) * sizeof(*enc->nz_) + WEBP_ALIGN_CST;
  139. const size_t info_size = mb_w * mb_h * sizeof(*enc->mb_info_);
  140. const size_t samples_size =
  141. 2 * top_stride * sizeof(*enc->y_top_) // top-luma/u/v
  142. + WEBP_ALIGN_CST; // align all
  143. const size_t lf_stats_size =
  144. config->autofilter ? sizeof(*enc->lf_stats_) + WEBP_ALIGN_CST : 0;
  145. const size_t top_derr_size =
  146. (config->quality <= ERROR_DIFFUSION_QUALITY || config->pass > 1) ?
  147. mb_w * sizeof(*enc->top_derr_) : 0;
  148. uint8_t* mem;
  149. const uint64_t size = (uint64_t)sizeof(*enc) // main struct
  150. + WEBP_ALIGN_CST // cache alignment
  151. + info_size // modes info
  152. + preds_size // prediction modes
  153. + samples_size // top/left samples
  154. + top_derr_size // top diffusion error
  155. + nz_size // coeff context bits
  156. + lf_stats_size; // autofilter stats
  157. #ifdef PRINT_MEMORY_INFO
  158. printf("===================================\n");
  159. printf("Memory used:\n"
  160. " encoder: %ld\n"
  161. " info: %ld\n"
  162. " preds: %ld\n"
  163. " top samples: %ld\n"
  164. " top diffusion: %ld\n"
  165. " non-zero: %ld\n"
  166. " lf-stats: %ld\n"
  167. " total: %ld\n",
  168. sizeof(*enc) + WEBP_ALIGN_CST, info_size,
  169. preds_size, samples_size, top_derr_size, nz_size, lf_stats_size, size);
  170. printf("Transient object sizes:\n"
  171. " VP8EncIterator: %ld\n"
  172. " VP8ModeScore: %ld\n"
  173. " VP8SegmentInfo: %ld\n"
  174. " VP8EncProba: %ld\n"
  175. " LFStats: %ld\n",
  176. sizeof(VP8EncIterator), sizeof(VP8ModeScore),
  177. sizeof(VP8SegmentInfo), sizeof(VP8EncProba),
  178. sizeof(LFStats));
  179. printf("Picture size (yuv): %ld\n",
  180. mb_w * mb_h * 384 * sizeof(uint8_t));
  181. printf("===================================\n");
  182. #endif
  183. mem = (uint8_t*)WebPSafeMalloc(size, sizeof(*mem));
  184. if (mem == NULL) {
  185. WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
  186. return NULL;
  187. }
  188. enc = (VP8Encoder*)mem;
  189. mem = (uint8_t*)WEBP_ALIGN(mem + sizeof(*enc));
  190. memset(enc, 0, sizeof(*enc));
  191. enc->num_parts_ = 1 << config->partitions;
  192. enc->mb_w_ = mb_w;
  193. enc->mb_h_ = mb_h;
  194. enc->preds_w_ = preds_w;
  195. enc->mb_info_ = (VP8MBInfo*)mem;
  196. mem += info_size;
  197. enc->preds_ = mem + 1 + enc->preds_w_;
  198. mem += preds_size;
  199. enc->nz_ = 1 + (uint32_t*)WEBP_ALIGN(mem);
  200. mem += nz_size;
  201. enc->lf_stats_ = lf_stats_size ? (LFStats*)WEBP_ALIGN(mem) : NULL;
  202. mem += lf_stats_size;
  203. // top samples (all 16-aligned)
  204. mem = (uint8_t*)WEBP_ALIGN(mem);
  205. enc->y_top_ = mem;
  206. enc->uv_top_ = enc->y_top_ + top_stride;
  207. mem += 2 * top_stride;
  208. enc->top_derr_ = top_derr_size ? (DError*)mem : NULL;
  209. mem += top_derr_size;
  210. assert(mem <= (uint8_t*)enc + size);
  211. enc->config_ = config;
  212. enc->profile_ = use_filter ? ((config->filter_type == 1) ? 0 : 1) : 2;
  213. enc->pic_ = picture;
  214. enc->percent_ = 0;
  215. MapConfigToTools(enc);
  216. VP8EncDspInit();
  217. VP8DefaultProbas(enc);
  218. ResetSegmentHeader(enc);
  219. ResetFilterHeader(enc);
  220. ResetBoundaryPredictions(enc);
  221. VP8EncDspCostInit();
  222. VP8EncInitAlpha(enc);
  223. // lower quality means smaller output -> we modulate a little the page
  224. // size based on quality. This is just a crude 1rst-order prediction.
  225. {
  226. const float scale = 1.f + config->quality * 5.f / 100.f; // in [1,6]
  227. VP8TBufferInit(&enc->tokens_, (int)(mb_w * mb_h * 4 * scale));
  228. }
  229. return enc;
  230. }
  231. static int DeleteVP8Encoder(VP8Encoder* enc) {
  232. int ok = 1;
  233. if (enc != NULL) {
  234. ok = VP8EncDeleteAlpha(enc);
  235. VP8TBufferClear(&enc->tokens_);
  236. WebPSafeFree(enc);
  237. }
  238. return ok;
  239. }
  240. //------------------------------------------------------------------------------
  241. #if !defined(WEBP_DISABLE_STATS)
  242. static double GetPSNR(uint64_t err, uint64_t size) {
  243. return (err > 0 && size > 0) ? 10. * log10(255. * 255. * size / err) : 99.;
  244. }
  245. static void FinalizePSNR(const VP8Encoder* const enc) {
  246. WebPAuxStats* stats = enc->pic_->stats;
  247. const uint64_t size = enc->sse_count_;
  248. const uint64_t* const sse = enc->sse_;
  249. stats->PSNR[0] = (float)GetPSNR(sse[0], size);
  250. stats->PSNR[1] = (float)GetPSNR(sse[1], size / 4);
  251. stats->PSNR[2] = (float)GetPSNR(sse[2], size / 4);
  252. stats->PSNR[3] = (float)GetPSNR(sse[0] + sse[1] + sse[2], size * 3 / 2);
  253. stats->PSNR[4] = (float)GetPSNR(sse[3], size);
  254. }
  255. #endif // !defined(WEBP_DISABLE_STATS)
  256. static void StoreStats(VP8Encoder* const enc) {
  257. #if !defined(WEBP_DISABLE_STATS)
  258. WebPAuxStats* const stats = enc->pic_->stats;
  259. if (stats != NULL) {
  260. int i, s;
  261. for (i = 0; i < NUM_MB_SEGMENTS; ++i) {
  262. stats->segment_level[i] = enc->dqm_[i].fstrength_;
  263. stats->segment_quant[i] = enc->dqm_[i].quant_;
  264. for (s = 0; s <= 2; ++s) {
  265. stats->residual_bytes[s][i] = enc->residual_bytes_[s][i];
  266. }
  267. }
  268. FinalizePSNR(enc);
  269. stats->coded_size = enc->coded_size_;
  270. for (i = 0; i < 3; ++i) {
  271. stats->block_count[i] = enc->block_count_[i];
  272. }
  273. }
  274. #else // defined(WEBP_DISABLE_STATS)
  275. WebPReportProgress(enc->pic_, 100, &enc->percent_); // done!
  276. #endif // !defined(WEBP_DISABLE_STATS)
  277. }
  278. int WebPEncodingSetError(const WebPPicture* const pic,
  279. WebPEncodingError error) {
  280. assert((int)error < VP8_ENC_ERROR_LAST);
  281. assert((int)error >= VP8_ENC_OK);
  282. ((WebPPicture*)pic)->error_code = error;
  283. return 0;
  284. }
  285. int WebPReportProgress(const WebPPicture* const pic,
  286. int percent, int* const percent_store) {
  287. if (percent_store != NULL && percent != *percent_store) {
  288. *percent_store = percent;
  289. if (pic->progress_hook && !pic->progress_hook(percent, pic)) {
  290. // user abort requested
  291. WebPEncodingSetError(pic, VP8_ENC_ERROR_USER_ABORT);
  292. return 0;
  293. }
  294. }
  295. return 1; // ok
  296. }
  297. //------------------------------------------------------------------------------
  298. int WebPEncode(const WebPConfig* config, WebPPicture* pic) {
  299. int ok = 0;
  300. if (pic == NULL) return 0;
  301. WebPEncodingSetError(pic, VP8_ENC_OK); // all ok so far
  302. if (config == NULL) { // bad params
  303. return WebPEncodingSetError(pic, VP8_ENC_ERROR_NULL_PARAMETER);
  304. }
  305. if (!WebPValidateConfig(config)) {
  306. return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);
  307. }
  308. if (pic->width <= 0 || pic->height <= 0) {
  309. return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
  310. }
  311. if (pic->width > WEBP_MAX_DIMENSION || pic->height > WEBP_MAX_DIMENSION) {
  312. return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
  313. }
  314. if (pic->stats != NULL) memset(pic->stats, 0, sizeof(*pic->stats));
  315. if (!config->lossless) {
  316. VP8Encoder* enc = NULL;
  317. if (pic->use_argb || pic->y == NULL || pic->u == NULL || pic->v == NULL) {
  318. // Make sure we have YUVA samples.
  319. if (config->use_sharp_yuv || (config->preprocessing & 4)) {
  320. if (!WebPPictureSharpARGBToYUVA(pic)) {
  321. return 0;
  322. }
  323. } else {
  324. float dithering = 0.f;
  325. if (config->preprocessing & 2) {
  326. const float x = config->quality / 100.f;
  327. const float x2 = x * x;
  328. // slowly decreasing from max dithering at low quality (q->0)
  329. // to 0.5 dithering amplitude at high quality (q->100)
  330. dithering = 1.0f + (0.5f - 1.0f) * x2 * x2;
  331. }
  332. if (!WebPPictureARGBToYUVADithered(pic, WEBP_YUV420, dithering)) {
  333. return 0;
  334. }
  335. }
  336. }
  337. if (!config->exact) {
  338. WebPCleanupTransparentArea(pic);
  339. }
  340. enc = InitVP8Encoder(config, pic);
  341. if (enc == NULL) return 0; // pic->error is already set.
  342. // Note: each of the tasks below account for 20% in the progress report.
  343. ok = VP8EncAnalyze(enc);
  344. // Analysis is done, proceed to actual coding.
  345. ok = ok && VP8EncStartAlpha(enc); // possibly done in parallel
  346. if (!enc->use_tokens_) {
  347. ok = ok && VP8EncLoop(enc);
  348. } else {
  349. ok = ok && VP8EncTokenLoop(enc);
  350. }
  351. ok = ok && VP8EncFinishAlpha(enc);
  352. ok = ok && VP8EncWrite(enc);
  353. StoreStats(enc);
  354. if (!ok) {
  355. VP8EncFreeBitWriters(enc);
  356. }
  357. ok &= DeleteVP8Encoder(enc); // must always be called, even if !ok
  358. } else {
  359. // Make sure we have ARGB samples.
  360. if (pic->argb == NULL && !WebPPictureYUVAToARGB(pic)) {
  361. return 0;
  362. }
  363. if (!config->exact) {
  364. WebPReplaceTransparentPixels(pic, 0x000000);
  365. }
  366. ok = VP8LEncodeImage(config, pic); // Sets pic->error in case of problem.
  367. }
  368. return ok;
  369. }