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