1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // This code is licensed under the same terms as WebM:
4 // Software License Agreement: http://www.webmproject.org/license/software/
5 // Additional IP Rights Grant: http://www.webmproject.org/license/additional/
6 // -----------------------------------------------------------------------------
7 //
8 // WebP encoder: main entry point
9 //
10 // Author: Skal (pascal.massimino@gmail.com)
11
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <math.h>
16
17 #include "./vp8enci.h"
18 #include "./vp8li.h"
19 #include "../utils/utils.h"
20
21 // #define PRINT_MEMORY_INFO
22
23 #if defined(__cplusplus) || defined(c_plusplus)
24 extern "C" {
25 #endif
26
27 #ifdef PRINT_MEMORY_INFO
28 #include <stdio.h>
29 #endif
30
31 //------------------------------------------------------------------------------
32
WebPGetEncoderVersion(void)33 int WebPGetEncoderVersion(void) {
34 return (ENC_MAJ_VERSION << 16) | (ENC_MIN_VERSION << 8) | ENC_REV_VERSION;
35 }
36
37 //------------------------------------------------------------------------------
38 // WebPPicture
39 //------------------------------------------------------------------------------
40
DummyWriter(const uint8_t * data,size_t data_size,const WebPPicture * const picture)41 static int DummyWriter(const uint8_t* data, size_t data_size,
42 const WebPPicture* const picture) {
43 // The following are to prevent 'unused variable' error message.
44 (void)data;
45 (void)data_size;
46 (void)picture;
47 return 1;
48 }
49
WebPPictureInitInternal(WebPPicture * picture,int version)50 int WebPPictureInitInternal(WebPPicture* picture, int version) {
51 if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_ENCODER_ABI_VERSION)) {
52 return 0; // caller/system version mismatch!
53 }
54 if (picture != NULL) {
55 memset(picture, 0, sizeof(*picture));
56 picture->writer = DummyWriter;
57 WebPEncodingSetError(picture, VP8_ENC_OK);
58 }
59 return 1;
60 }
61
62 //------------------------------------------------------------------------------
63 // VP8Encoder
64 //------------------------------------------------------------------------------
65
ResetSegmentHeader(VP8Encoder * const enc)66 static void ResetSegmentHeader(VP8Encoder* const enc) {
67 VP8SegmentHeader* const hdr = &enc->segment_hdr_;
68 hdr->num_segments_ = enc->config_->segments;
69 hdr->update_map_ = (hdr->num_segments_ > 1);
70 hdr->size_ = 0;
71 }
72
ResetFilterHeader(VP8Encoder * const enc)73 static void ResetFilterHeader(VP8Encoder* const enc) {
74 VP8FilterHeader* const hdr = &enc->filter_hdr_;
75 hdr->simple_ = 1;
76 hdr->level_ = 0;
77 hdr->sharpness_ = 0;
78 hdr->i4x4_lf_delta_ = 0;
79 }
80
ResetBoundaryPredictions(VP8Encoder * const enc)81 static void ResetBoundaryPredictions(VP8Encoder* const enc) {
82 // init boundary values once for all
83 // Note: actually, initializing the preds_[] is only needed for intra4.
84 int i;
85 uint8_t* const top = enc->preds_ - enc->preds_w_;
86 uint8_t* const left = enc->preds_ - 1;
87 for (i = -1; i < 4 * enc->mb_w_; ++i) {
88 top[i] = B_DC_PRED;
89 }
90 for (i = 0; i < 4 * enc->mb_h_; ++i) {
91 left[i * enc->preds_w_] = B_DC_PRED;
92 }
93 enc->nz_[-1] = 0; // constant
94 }
95
96 // Map configured quality level to coding tools used.
97 //-------------+---+---+---+---+---+---+
98 // Quality | 0 | 1 | 2 | 3 | 4 | 5 +
99 //-------------+---+---+---+---+---+---+
100 // dynamic prob| ~ | x | x | x | x | x |
101 //-------------+---+---+---+---+---+---+
102 // rd-opt modes| | | x | x | x | x |
103 //-------------+---+---+---+---+---+---+
104 // fast i4/i16 | x | x | | | | |
105 //-------------+---+---+---+---+---+---+
106 // rd-opt i4/16| | | x | x | x | x |
107 //-------------+---+---+---+---+---+---+
108 // Trellis | | x | | | x | x |
109 //-------------+---+---+---+---+---+---+
110 // full-SNS | | | | | | x |
111 //-------------+---+---+---+---+---+---+
112
MapConfigToTools(VP8Encoder * const enc)113 static void MapConfigToTools(VP8Encoder* const enc) {
114 const int method = enc->config_->method;
115 const int limit = 100 - enc->config_->partition_limit;
116 enc->method_ = method;
117 enc->rd_opt_level_ = (method >= 6) ? 3
118 : (method >= 5) ? 2
119 : (method >= 3) ? 1
120 : 0;
121 enc->max_i4_header_bits_ =
122 256 * 16 * 16 * // upper bound: up to 16bit per 4x4 block
123 (limit * limit) / (100 * 100); // ... modulated with a quadratic curve.
124 }
125
126 // Memory scaling with dimensions:
127 // memory (bytes) ~= 2.25 * w + 0.0625 * w * h
128 //
129 // Typical memory footprint (768x510 picture)
130 // Memory used:
131 // encoder: 33919
132 // block cache: 2880
133 // info: 3072
134 // preds: 24897
135 // top samples: 1623
136 // non-zero: 196
137 // lf-stats: 2048
138 // total: 68635
139 // Transcient object sizes:
140 // VP8EncIterator: 352
141 // VP8ModeScore: 912
142 // VP8SegmentInfo: 532
143 // VP8Proba: 31032
144 // LFStats: 2048
145 // Picture size (yuv): 589824
146
InitVP8Encoder(const WebPConfig * const config,WebPPicture * const picture)147 static VP8Encoder* InitVP8Encoder(const WebPConfig* const config,
148 WebPPicture* const picture) {
149 const int use_filter =
150 (config->filter_strength > 0) || (config->autofilter > 0);
151 const int mb_w = (picture->width + 15) >> 4;
152 const int mb_h = (picture->height + 15) >> 4;
153 const int preds_w = 4 * mb_w + 1;
154 const int preds_h = 4 * mb_h + 1;
155 const size_t preds_size = preds_w * preds_h * sizeof(uint8_t);
156 const int top_stride = mb_w * 16;
157 const size_t nz_size = (mb_w + 1) * sizeof(uint32_t);
158 const size_t cache_size = (3 * YUV_SIZE + PRED_SIZE) * sizeof(uint8_t);
159 const size_t info_size = mb_w * mb_h * sizeof(VP8MBInfo);
160 const size_t samples_size = (2 * top_stride + // top-luma/u/v
161 16 + 16 + 16 + 8 + 1 + // left y/u/v
162 2 * ALIGN_CST) // align all
163 * sizeof(uint8_t);
164 const size_t lf_stats_size =
165 config->autofilter ? sizeof(LFStats) + ALIGN_CST : 0;
166 VP8Encoder* enc;
167 uint8_t* mem;
168 const uint64_t size = (uint64_t)sizeof(VP8Encoder) // main struct
169 + ALIGN_CST // cache alignment
170 + cache_size // working caches
171 + info_size // modes info
172 + preds_size // prediction modes
173 + samples_size // top/left samples
174 + nz_size // coeff context bits
175 + lf_stats_size; // autofilter stats
176
177 #ifdef PRINT_MEMORY_INFO
178 printf("===================================\n");
179 printf("Memory used:\n"
180 " encoder: %ld\n"
181 " block cache: %ld\n"
182 " info: %ld\n"
183 " preds: %ld\n"
184 " top samples: %ld\n"
185 " non-zero: %ld\n"
186 " lf-stats: %ld\n"
187 " total: %ld\n",
188 sizeof(VP8Encoder) + ALIGN_CST, cache_size, info_size,
189 preds_size, samples_size, nz_size, lf_stats_size, size);
190 printf("Transcient object sizes:\n"
191 " VP8EncIterator: %ld\n"
192 " VP8ModeScore: %ld\n"
193 " VP8SegmentInfo: %ld\n"
194 " VP8Proba: %ld\n"
195 " LFStats: %ld\n",
196 sizeof(VP8EncIterator), sizeof(VP8ModeScore),
197 sizeof(VP8SegmentInfo), sizeof(VP8Proba),
198 sizeof(LFStats));
199 printf("Picture size (yuv): %ld\n",
200 mb_w * mb_h * 384 * sizeof(uint8_t));
201 printf("===================================\n");
202 #endif
203 mem = (uint8_t*)WebPSafeMalloc(size, sizeof(*mem));
204 if (mem == NULL) {
205 WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
206 return NULL;
207 }
208 enc = (VP8Encoder*)mem;
209 mem = (uint8_t*)DO_ALIGN(mem + sizeof(*enc));
210 memset(enc, 0, sizeof(*enc));
211 enc->num_parts_ = 1 << config->partitions;
212 enc->mb_w_ = mb_w;
213 enc->mb_h_ = mb_h;
214 enc->preds_w_ = preds_w;
215 enc->yuv_in_ = (uint8_t*)mem;
216 mem += YUV_SIZE;
217 enc->yuv_out_ = (uint8_t*)mem;
218 mem += YUV_SIZE;
219 enc->yuv_out2_ = (uint8_t*)mem;
220 mem += YUV_SIZE;
221 enc->yuv_p_ = (uint8_t*)mem;
222 mem += PRED_SIZE;
223 enc->mb_info_ = (VP8MBInfo*)mem;
224 mem += info_size;
225 enc->preds_ = ((uint8_t*)mem) + 1 + enc->preds_w_;
226 mem += preds_w * preds_h * sizeof(uint8_t);
227 enc->nz_ = 1 + (uint32_t*)mem;
228 mem += nz_size;
229 enc->lf_stats_ = lf_stats_size ? (LFStats*)DO_ALIGN(mem) : NULL;
230 mem += lf_stats_size;
231
232 // top samples (all 16-aligned)
233 mem = (uint8_t*)DO_ALIGN(mem);
234 enc->y_top_ = (uint8_t*)mem;
235 enc->uv_top_ = enc->y_top_ + top_stride;
236 mem += 2 * top_stride;
237 mem = (uint8_t*)DO_ALIGN(mem + 1);
238 enc->y_left_ = (uint8_t*)mem;
239 mem += 16 + 16;
240 enc->u_left_ = (uint8_t*)mem;
241 mem += 16;
242 enc->v_left_ = (uint8_t*)mem;
243 mem += 8;
244
245 enc->config_ = config;
246 enc->profile_ = use_filter ? ((config->filter_type == 1) ? 0 : 1) : 2;
247 enc->pic_ = picture;
248 enc->percent_ = 0;
249
250 MapConfigToTools(enc);
251 VP8EncDspInit();
252 VP8DefaultProbas(enc);
253 ResetSegmentHeader(enc);
254 ResetFilterHeader(enc);
255 ResetBoundaryPredictions(enc);
256
257 VP8EncInitAlpha(enc);
258 #ifdef WEBP_EXPERIMENTAL_FEATURES
259 VP8EncInitLayer(enc);
260 #endif
261
262 return enc;
263 }
264
DeleteVP8Encoder(VP8Encoder * enc)265 static void DeleteVP8Encoder(VP8Encoder* enc) {
266 if (enc != NULL) {
267 VP8EncDeleteAlpha(enc);
268 #ifdef WEBP_EXPERIMENTAL_FEATURES
269 VP8EncDeleteLayer(enc);
270 #endif
271 free(enc);
272 }
273 }
274
275 //------------------------------------------------------------------------------
276
GetPSNR(uint64_t err,uint64_t size)277 static double GetPSNR(uint64_t err, uint64_t size) {
278 return err ? 10. * log10(255. * 255. * size / err) : 99.;
279 }
280
FinalizePSNR(const VP8Encoder * const enc)281 static void FinalizePSNR(const VP8Encoder* const enc) {
282 WebPAuxStats* stats = enc->pic_->stats;
283 const uint64_t size = enc->sse_count_;
284 const uint64_t* const sse = enc->sse_;
285 stats->PSNR[0] = (float)GetPSNR(sse[0], size);
286 stats->PSNR[1] = (float)GetPSNR(sse[1], size / 4);
287 stats->PSNR[2] = (float)GetPSNR(sse[2], size / 4);
288 stats->PSNR[3] = (float)GetPSNR(sse[0] + sse[1] + sse[2], size * 3 / 2);
289 stats->PSNR[4] = (float)GetPSNR(sse[3], size);
290 }
291
StoreStats(VP8Encoder * const enc)292 static void StoreStats(VP8Encoder* const enc) {
293 WebPAuxStats* const stats = enc->pic_->stats;
294 if (stats != NULL) {
295 int i, s;
296 for (i = 0; i < NUM_MB_SEGMENTS; ++i) {
297 stats->segment_level[i] = enc->dqm_[i].fstrength_;
298 stats->segment_quant[i] = enc->dqm_[i].quant_;
299 for (s = 0; s <= 2; ++s) {
300 stats->residual_bytes[s][i] = enc->residual_bytes_[s][i];
301 }
302 }
303 FinalizePSNR(enc);
304 stats->coded_size = enc->coded_size_;
305 for (i = 0; i < 3; ++i) {
306 stats->block_count[i] = enc->block_count_[i];
307 }
308 }
309 WebPReportProgress(enc->pic_, 100, &enc->percent_); // done!
310 }
311
WebPEncodingSetError(const WebPPicture * const pic,WebPEncodingError error)312 int WebPEncodingSetError(const WebPPicture* const pic,
313 WebPEncodingError error) {
314 assert((int)error < VP8_ENC_ERROR_LAST);
315 assert((int)error >= VP8_ENC_OK);
316 ((WebPPicture*)pic)->error_code = error;
317 return 0;
318 }
319
WebPReportProgress(const WebPPicture * const pic,int percent,int * const percent_store)320 int WebPReportProgress(const WebPPicture* const pic,
321 int percent, int* const percent_store) {
322 if (percent_store != NULL && percent != *percent_store) {
323 *percent_store = percent;
324 if (pic->progress_hook && !pic->progress_hook(percent, pic)) {
325 // user abort requested
326 WebPEncodingSetError(pic, VP8_ENC_ERROR_USER_ABORT);
327 return 0;
328 }
329 }
330 return 1; // ok
331 }
332 //------------------------------------------------------------------------------
333
WebPEncode(const WebPConfig * config,WebPPicture * pic)334 int WebPEncode(const WebPConfig* config, WebPPicture* pic) {
335 int ok;
336
337 if (pic == NULL)
338 return 0;
339 WebPEncodingSetError(pic, VP8_ENC_OK); // all ok so far
340 if (config == NULL) // bad params
341 return WebPEncodingSetError(pic, VP8_ENC_ERROR_NULL_PARAMETER);
342 if (!WebPValidateConfig(config))
343 return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);
344 if (pic->width <= 0 || pic->height <= 0)
345 return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
346 if (pic->width > WEBP_MAX_DIMENSION || pic->height > WEBP_MAX_DIMENSION)
347 return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
348
349 if (pic->stats != NULL) memset(pic->stats, 0, sizeof(*pic->stats));
350
351 if (!config->lossless) {
352 VP8Encoder* enc = NULL;
353 if (pic->y == NULL || pic->u == NULL || pic->v == NULL) {
354 if (pic->argb != NULL) {
355 if (!WebPPictureARGBToYUVA(pic, WEBP_YUV420)) return 0;
356 } else {
357 return WebPEncodingSetError(pic, VP8_ENC_ERROR_NULL_PARAMETER);
358 }
359 }
360
361 enc = InitVP8Encoder(config, pic);
362 if (enc == NULL) return 0; // pic->error is already set.
363 // Note: each of the tasks below account for 20% in the progress report.
364 ok = VP8EncAnalyze(enc)
365 && VP8StatLoop(enc)
366 && VP8EncLoop(enc)
367 && VP8EncFinishAlpha(enc)
368 #ifdef WEBP_EXPERIMENTAL_FEATURES
369 && VP8EncFinishLayer(enc)
370 #endif
371 && VP8EncWrite(enc);
372 StoreStats(enc);
373 if (!ok) {
374 VP8EncFreeBitWriters(enc);
375 }
376 DeleteVP8Encoder(enc);
377 } else {
378 if (pic->argb == NULL)
379 return WebPEncodingSetError(pic, VP8_ENC_ERROR_NULL_PARAMETER);
380
381 ok = VP8LEncodeImage(config, pic); // Sets pic->error in case of problem.
382 }
383
384 return ok;
385 }
386
387 #if defined(__cplusplus) || defined(c_plusplus)
388 } // extern "C"
389 #endif
390