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 // simple command line calling the WebPEncode function.
11 // Encodes a raw .YUV into WebP bitstream
12 //
13 // Author: Skal (pascal.massimino@gmail.com)
14
15 #include <assert.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19
20 #ifdef HAVE_CONFIG_H
21 #include "webp/config.h"
22 #endif
23
24 #include "../examples/example_util.h"
25 #include "../imageio/image_dec.h"
26 #include "../imageio/imageio_util.h"
27 #include "../imageio/webpdec.h"
28 #include "./stopwatch.h"
29 #include "./unicode.h"
30 #include "webp/encode.h"
31
32 #ifndef WEBP_DLL
33 #ifdef __cplusplus
34 extern "C" {
35 #endif
36
37 extern void* VP8GetCPUInfo; // opaque forward declaration.
38
39 #ifdef __cplusplus
40 } // extern "C"
41 #endif
42 #endif // WEBP_DLL
43
44 //------------------------------------------------------------------------------
45
46 static int verbose = 0;
47
ReadYUV(const uint8_t * const data,size_t data_size,WebPPicture * const pic)48 static int ReadYUV(const uint8_t* const data, size_t data_size,
49 WebPPicture* const pic) {
50 const int use_argb = pic->use_argb;
51 const int uv_width = (pic->width + 1) / 2;
52 const int uv_height = (pic->height + 1) / 2;
53 const int y_plane_size = pic->width * pic->height;
54 const int uv_plane_size = uv_width * uv_height;
55 const size_t expected_data_size = y_plane_size + 2 * uv_plane_size;
56
57 if (data_size != expected_data_size) {
58 fprintf(stderr,
59 "input data doesn't have the expected size (%d instead of %d)\n",
60 (int)data_size, (int)expected_data_size);
61 return 0;
62 }
63
64 pic->use_argb = 0;
65 if (!WebPPictureAlloc(pic)) return 0;
66 ImgIoUtilCopyPlane(data, pic->width, pic->y, pic->y_stride,
67 pic->width, pic->height);
68 ImgIoUtilCopyPlane(data + y_plane_size, uv_width,
69 pic->u, pic->uv_stride, uv_width, uv_height);
70 ImgIoUtilCopyPlane(data + y_plane_size + uv_plane_size, uv_width,
71 pic->v, pic->uv_stride, uv_width, uv_height);
72 return use_argb ? WebPPictureYUVAToARGB(pic) : 1;
73 }
74
75 #ifdef HAVE_WINCODEC_H
76
ReadPicture(const char * const filename,WebPPicture * const pic,int keep_alpha,Metadata * const metadata)77 static int ReadPicture(const char* const filename, WebPPicture* const pic,
78 int keep_alpha, Metadata* const metadata) {
79 int ok = 0;
80 const uint8_t* data = NULL;
81 size_t data_size = 0;
82 if (pic->width != 0 && pic->height != 0) {
83 ok = ImgIoUtilReadFile(filename, &data, &data_size);
84 ok = ok && ReadYUV(data, data_size, pic);
85 } else {
86 // If no size specified, try to decode it using WIC.
87 ok = ReadPictureWithWIC(filename, pic, keep_alpha, metadata);
88 if (!ok) {
89 ok = ImgIoUtilReadFile(filename, &data, &data_size);
90 ok = ok && ReadWebP(data, data_size, pic, keep_alpha, metadata);
91 }
92 }
93 if (!ok) {
94 WFPRINTF(stderr, "Error! Could not process file %s\n",
95 (const W_CHAR*)filename);
96 }
97 WebPFree((void*)data);
98 return ok;
99 }
100
101 #else // !HAVE_WINCODEC_H
102
ReadPicture(const char * const filename,WebPPicture * const pic,int keep_alpha,Metadata * const metadata)103 static int ReadPicture(const char* const filename, WebPPicture* const pic,
104 int keep_alpha, Metadata* const metadata) {
105 const uint8_t* data = NULL;
106 size_t data_size = 0;
107 int ok = 0;
108
109 ok = ImgIoUtilReadFile(filename, &data, &data_size);
110 if (!ok) goto End;
111
112 if (pic->width == 0 || pic->height == 0) {
113 WebPImageReader reader = WebPGuessImageReader(data, data_size);
114 ok = reader(data, data_size, pic, keep_alpha, metadata);
115 } else {
116 // If image size is specified, infer it as YUV format.
117 ok = ReadYUV(data, data_size, pic);
118 }
119 End:
120 if (!ok) {
121 WFPRINTF(stderr, "Error! Could not process file %s\n",
122 (const W_CHAR*)filename);
123 }
124 WebPFree((void*)data);
125 return ok;
126 }
127
128 #endif // !HAVE_WINCODEC_H
129
AllocExtraInfo(WebPPicture * const pic)130 static void AllocExtraInfo(WebPPicture* const pic) {
131 const int mb_w = (pic->width + 15) / 16;
132 const int mb_h = (pic->height + 15) / 16;
133 pic->extra_info =
134 (uint8_t*)WebPMalloc(mb_w * mb_h * sizeof(*pic->extra_info));
135 }
136
PrintByteCount(const int bytes[4],int total_size,int * const totals)137 static void PrintByteCount(const int bytes[4], int total_size,
138 int* const totals) {
139 int s;
140 int total = 0;
141 for (s = 0; s < 4; ++s) {
142 fprintf(stderr, "| %7d ", bytes[s]);
143 total += bytes[s];
144 if (totals) totals[s] += bytes[s];
145 }
146 fprintf(stderr, "| %7d (%.1f%%)\n", total, 100.f * total / total_size);
147 }
148
PrintPercents(const int counts[4])149 static void PrintPercents(const int counts[4]) {
150 int s;
151 const int total = counts[0] + counts[1] + counts[2] + counts[3];
152 for (s = 0; s < 4; ++s) {
153 fprintf(stderr, "| %3d%%", (int)(100. * counts[s] / total + .5));
154 }
155 fprintf(stderr, "| %7d\n", total);
156 }
157
PrintValues(const int values[4])158 static void PrintValues(const int values[4]) {
159 int s;
160 for (s = 0; s < 4; ++s) {
161 fprintf(stderr, "| %7d ", values[s]);
162 }
163 fprintf(stderr, "|\n");
164 }
165
PrintFullLosslessInfo(const WebPAuxStats * const stats,const char * const description)166 static void PrintFullLosslessInfo(const WebPAuxStats* const stats,
167 const char* const description) {
168 fprintf(stderr, "Lossless-%s compressed size: %d bytes\n",
169 description, stats->lossless_size);
170 fprintf(stderr, " * Header size: %d bytes, image data size: %d\n",
171 stats->lossless_hdr_size, stats->lossless_data_size);
172 if (stats->lossless_features) {
173 fprintf(stderr, " * Lossless features used:");
174 if (stats->lossless_features & 1) fprintf(stderr, " PREDICTION");
175 if (stats->lossless_features & 2) fprintf(stderr, " CROSS-COLOR-TRANSFORM");
176 if (stats->lossless_features & 4) fprintf(stderr, " SUBTRACT-GREEN");
177 if (stats->lossless_features & 8) fprintf(stderr, " PALETTE");
178 fprintf(stderr, "\n");
179 }
180 fprintf(stderr, " * Precision Bits: histogram=%d transform=%d cache=%d\n",
181 stats->histogram_bits, stats->transform_bits, stats->cache_bits);
182 if (stats->palette_size > 0) {
183 fprintf(stderr, " * Palette size: %d\n", stats->palette_size);
184 }
185 }
186
PrintExtraInfoLossless(const WebPPicture * const pic,int short_output,const char * const file_name)187 static void PrintExtraInfoLossless(const WebPPicture* const pic,
188 int short_output,
189 const char* const file_name) {
190 const WebPAuxStats* const stats = pic->stats;
191 if (short_output) {
192 fprintf(stderr, "%7d %2.2f\n", stats->coded_size, stats->PSNR[3]);
193 } else {
194 WFPRINTF(stderr, "File: %s\n", (const W_CHAR*)file_name);
195 fprintf(stderr, "Dimension: %d x %d\n", pic->width, pic->height);
196 fprintf(stderr, "Output: %d bytes (%.2f bpp)\n", stats->coded_size,
197 8.f * stats->coded_size / pic->width / pic->height);
198 PrintFullLosslessInfo(stats, "ARGB");
199 }
200 }
201
PrintExtraInfoLossy(const WebPPicture * const pic,int short_output,int full_details,const char * const file_name)202 static void PrintExtraInfoLossy(const WebPPicture* const pic, int short_output,
203 int full_details,
204 const char* const file_name) {
205 const WebPAuxStats* const stats = pic->stats;
206 if (short_output) {
207 fprintf(stderr, "%7d %2.2f\n", stats->coded_size, stats->PSNR[3]);
208 } else {
209 const int num_i4 = stats->block_count[0];
210 const int num_i16 = stats->block_count[1];
211 const int num_skip = stats->block_count[2];
212 const int total = num_i4 + num_i16;
213 WFPRINTF(stderr, "File: %s\n", (const W_CHAR*)file_name);
214 fprintf(stderr, "Dimension: %d x %d%s\n",
215 pic->width, pic->height,
216 stats->alpha_data_size ? " (with alpha)" : "");
217 fprintf(stderr, "Output: "
218 "%d bytes Y-U-V-All-PSNR %2.2f %2.2f %2.2f %2.2f dB\n"
219 " (%.2f bpp)\n",
220 stats->coded_size,
221 stats->PSNR[0], stats->PSNR[1], stats->PSNR[2], stats->PSNR[3],
222 8.f * stats->coded_size / pic->width / pic->height);
223 if (total > 0) {
224 int totals[4] = { 0, 0, 0, 0 };
225 fprintf(stderr, "block count: intra4: %6d (%.2f%%)\n"
226 " intra16: %6d (%.2f%%)\n"
227 " skipped: %6d (%.2f%%)\n",
228 num_i4, 100.f * num_i4 / total,
229 num_i16, 100.f * num_i16 / total,
230 num_skip, 100.f * num_skip / total);
231 fprintf(stderr, "bytes used: header: %6d (%.1f%%)\n"
232 " mode-partition: %6d (%.1f%%)\n",
233 stats->header_bytes[0],
234 100.f * stats->header_bytes[0] / stats->coded_size,
235 stats->header_bytes[1],
236 100.f * stats->header_bytes[1] / stats->coded_size);
237 if (stats->alpha_data_size > 0) {
238 fprintf(stderr, " transparency: %6d (%.1f dB)\n",
239 stats->alpha_data_size, stats->PSNR[4]);
240 }
241 fprintf(stderr, " Residuals bytes "
242 "|segment 1|segment 2|segment 3"
243 "|segment 4| total\n");
244 if (full_details) {
245 fprintf(stderr, " intra4-coeffs: ");
246 PrintByteCount(stats->residual_bytes[0], stats->coded_size, totals);
247 fprintf(stderr, " intra16-coeffs: ");
248 PrintByteCount(stats->residual_bytes[1], stats->coded_size, totals);
249 fprintf(stderr, " chroma coeffs: ");
250 PrintByteCount(stats->residual_bytes[2], stats->coded_size, totals);
251 }
252 fprintf(stderr, " macroblocks: ");
253 PrintPercents(stats->segment_size);
254 fprintf(stderr, " quantizer: ");
255 PrintValues(stats->segment_quant);
256 fprintf(stderr, " filter level: ");
257 PrintValues(stats->segment_level);
258 if (full_details) {
259 fprintf(stderr, "------------------+---------");
260 fprintf(stderr, "+---------+---------+---------+-----------------\n");
261 fprintf(stderr, " segments total: ");
262 PrintByteCount(totals, stats->coded_size, NULL);
263 }
264 }
265 if (stats->lossless_size > 0) {
266 PrintFullLosslessInfo(stats, "alpha");
267 }
268 }
269 }
270
PrintMapInfo(const WebPPicture * const pic)271 static void PrintMapInfo(const WebPPicture* const pic) {
272 if (pic->extra_info != NULL) {
273 const int mb_w = (pic->width + 15) / 16;
274 const int mb_h = (pic->height + 15) / 16;
275 const int type = pic->extra_info_type;
276 int x, y;
277 for (y = 0; y < mb_h; ++y) {
278 for (x = 0; x < mb_w; ++x) {
279 const int c = pic->extra_info[x + y * mb_w];
280 if (type == 1) { // intra4/intra16
281 fprintf(stderr, "%c", "+."[c]);
282 } else if (type == 2) { // segments
283 fprintf(stderr, "%c", ".-*X"[c]);
284 } else if (type == 3) { // quantizers
285 fprintf(stderr, "%.2d ", c);
286 } else if (type == 6 || type == 7) {
287 fprintf(stderr, "%3d ", c);
288 } else {
289 fprintf(stderr, "0x%.2x ", c);
290 }
291 }
292 fprintf(stderr, "\n");
293 }
294 }
295 }
296
297 //------------------------------------------------------------------------------
298
MyWriter(const uint8_t * data,size_t data_size,const WebPPicture * const pic)299 static int MyWriter(const uint8_t* data, size_t data_size,
300 const WebPPicture* const pic) {
301 FILE* const out = (FILE*)pic->custom_ptr;
302 return data_size ? (fwrite(data, data_size, 1, out) == 1) : 1;
303 }
304
305 // Dumps a picture as a PGM file using the IMC4 layout.
DumpPicture(const WebPPicture * const picture,const char * PGM_name)306 static int DumpPicture(const WebPPicture* const picture, const char* PGM_name) {
307 int y;
308 const int uv_width = (picture->width + 1) / 2;
309 const int uv_height = (picture->height + 1) / 2;
310 const int stride = (picture->width + 1) & ~1;
311 const uint8_t* src_y = picture->y;
312 const uint8_t* src_u = picture->u;
313 const uint8_t* src_v = picture->v;
314 const uint8_t* src_a = picture->a;
315 const int alpha_height =
316 WebPPictureHasTransparency(picture) ? picture->height : 0;
317 const int height = picture->height + uv_height + alpha_height;
318 FILE* const f = WFOPEN(PGM_name, "wb");
319 if (f == NULL) return 0;
320 fprintf(f, "P5\n%d %d\n255\n", stride, height);
321 for (y = 0; y < picture->height; ++y) {
322 if (fwrite(src_y, picture->width, 1, f) != 1) return 0;
323 if (picture->width & 1) fputc(0, f); // pad
324 src_y += picture->y_stride;
325 }
326 for (y = 0; y < uv_height; ++y) {
327 if (fwrite(src_u, uv_width, 1, f) != 1) return 0;
328 if (fwrite(src_v, uv_width, 1, f) != 1) return 0;
329 src_u += picture->uv_stride;
330 src_v += picture->uv_stride;
331 }
332 for (y = 0; y < alpha_height; ++y) {
333 if (fwrite(src_a, picture->width, 1, f) != 1) return 0;
334 if (picture->width & 1) fputc(0, f); // pad
335 src_a += picture->a_stride;
336 }
337 fclose(f);
338 return 1;
339 }
340
341 // -----------------------------------------------------------------------------
342 // Metadata writing.
343
344 enum {
345 METADATA_EXIF = (1 << 0),
346 METADATA_ICC = (1 << 1),
347 METADATA_XMP = (1 << 2),
348 METADATA_ALL = METADATA_EXIF | METADATA_ICC | METADATA_XMP
349 };
350
351 static const int kChunkHeaderSize = 8;
352 static const int kTagSize = 4;
353
PrintMetadataInfo(const Metadata * const metadata,int metadata_written)354 static void PrintMetadataInfo(const Metadata* const metadata,
355 int metadata_written) {
356 if (metadata == NULL || metadata_written == 0) return;
357
358 fprintf(stderr, "Metadata:\n");
359 if (metadata_written & METADATA_ICC) {
360 fprintf(stderr, " * ICC profile: %6d bytes\n", (int)metadata->iccp.size);
361 }
362 if (metadata_written & METADATA_EXIF) {
363 fprintf(stderr, " * EXIF data: %6d bytes\n", (int)metadata->exif.size);
364 }
365 if (metadata_written & METADATA_XMP) {
366 fprintf(stderr, " * XMP data: %6d bytes\n", (int)metadata->xmp.size);
367 }
368 }
369
370 // Outputs, in little endian, 'num' bytes from 'val' to 'out'.
WriteLE(FILE * const out,uint32_t val,int num)371 static int WriteLE(FILE* const out, uint32_t val, int num) {
372 uint8_t buf[4];
373 int i;
374 for (i = 0; i < num; ++i) {
375 buf[i] = (uint8_t)(val & 0xff);
376 val >>= 8;
377 }
378 return (fwrite(buf, num, 1, out) == 1);
379 }
380
WriteLE24(FILE * const out,uint32_t val)381 static int WriteLE24(FILE* const out, uint32_t val) {
382 return WriteLE(out, val, 3);
383 }
384
WriteLE32(FILE * const out,uint32_t val)385 static int WriteLE32(FILE* const out, uint32_t val) {
386 return WriteLE(out, val, 4);
387 }
388
WriteMetadataChunk(FILE * const out,const char fourcc[4],const MetadataPayload * const payload)389 static int WriteMetadataChunk(FILE* const out, const char fourcc[4],
390 const MetadataPayload* const payload) {
391 const uint8_t zero = 0;
392 const size_t need_padding = payload->size & 1;
393 int ok = (fwrite(fourcc, kTagSize, 1, out) == 1);
394 ok = ok && WriteLE32(out, (uint32_t)payload->size);
395 ok = ok && (fwrite(payload->bytes, payload->size, 1, out) == 1);
396 return ok && (fwrite(&zero, need_padding, need_padding, out) == need_padding);
397 }
398
399 // Sets 'flag' in 'vp8x_flags' and updates 'metadata_size' with the size of the
400 // chunk if there is metadata and 'keep' is true.
UpdateFlagsAndSize(const MetadataPayload * const payload,int keep,int flag,uint32_t * vp8x_flags,uint64_t * metadata_size)401 static int UpdateFlagsAndSize(const MetadataPayload* const payload,
402 int keep, int flag,
403 uint32_t* vp8x_flags, uint64_t* metadata_size) {
404 if (keep && payload->bytes != NULL && payload->size > 0) {
405 *vp8x_flags |= flag;
406 *metadata_size += kChunkHeaderSize + payload->size + (payload->size & 1);
407 return 1;
408 }
409 return 0;
410 }
411
412 // Writes a WebP file using the image contained in 'memory_writer' and the
413 // metadata from 'metadata'. Metadata is controlled by 'keep_metadata' and the
414 // availability in 'metadata'. Returns true on success.
415 // For details see doc/webp-container-spec.txt#extended-file-format.
WriteWebPWithMetadata(FILE * const out,const WebPPicture * const picture,const WebPMemoryWriter * const memory_writer,const Metadata * const metadata,int keep_metadata,int * const metadata_written)416 static int WriteWebPWithMetadata(FILE* const out,
417 const WebPPicture* const picture,
418 const WebPMemoryWriter* const memory_writer,
419 const Metadata* const metadata,
420 int keep_metadata,
421 int* const metadata_written) {
422 const char kVP8XHeader[] = "VP8X\x0a\x00\x00\x00";
423 const int kAlphaFlag = 0x10;
424 const int kEXIFFlag = 0x08;
425 const int kICCPFlag = 0x20;
426 const int kXMPFlag = 0x04;
427 const size_t kRiffHeaderSize = 12;
428 const size_t kMaxChunkPayload = ~0 - kChunkHeaderSize - 1;
429 const size_t kMinSize = kRiffHeaderSize + kChunkHeaderSize;
430 uint32_t flags = 0;
431 uint64_t metadata_size = 0;
432 const int write_exif = UpdateFlagsAndSize(&metadata->exif,
433 !!(keep_metadata & METADATA_EXIF),
434 kEXIFFlag, &flags, &metadata_size);
435 const int write_iccp = UpdateFlagsAndSize(&metadata->iccp,
436 !!(keep_metadata & METADATA_ICC),
437 kICCPFlag, &flags, &metadata_size);
438 const int write_xmp = UpdateFlagsAndSize(&metadata->xmp,
439 !!(keep_metadata & METADATA_XMP),
440 kXMPFlag, &flags, &metadata_size);
441 uint8_t* webp = memory_writer->mem;
442 size_t webp_size = memory_writer->size;
443
444 *metadata_written = 0;
445
446 if (webp_size < kMinSize) return 0;
447 if (webp_size - kChunkHeaderSize + metadata_size > kMaxChunkPayload) {
448 fprintf(stderr, "Error! Addition of metadata would exceed "
449 "container size limit.\n");
450 return 0;
451 }
452
453 if (metadata_size > 0) {
454 const int kVP8XChunkSize = 18;
455 const int has_vp8x = !memcmp(webp + kRiffHeaderSize, "VP8X", kTagSize);
456 const uint32_t riff_size = (uint32_t)(webp_size - kChunkHeaderSize +
457 (has_vp8x ? 0 : kVP8XChunkSize) +
458 metadata_size);
459 // RIFF
460 int ok = (fwrite(webp, kTagSize, 1, out) == 1);
461 // RIFF size (file header size is not recorded)
462 ok = ok && WriteLE32(out, riff_size);
463 webp += kChunkHeaderSize;
464 webp_size -= kChunkHeaderSize;
465 // WEBP
466 ok = ok && (fwrite(webp, kTagSize, 1, out) == 1);
467 webp += kTagSize;
468 webp_size -= kTagSize;
469 if (has_vp8x) { // update the existing VP8X flags
470 webp[kChunkHeaderSize] |= (uint8_t)(flags & 0xff);
471 ok = ok && (fwrite(webp, kVP8XChunkSize, 1, out) == 1);
472 webp += kVP8XChunkSize;
473 webp_size -= kVP8XChunkSize;
474 } else {
475 const int is_lossless = !memcmp(webp, "VP8L", kTagSize);
476 if (is_lossless) {
477 // Presence of alpha is stored in the 37th bit (29th after the
478 // signature) of VP8L data.
479 if (webp[kChunkHeaderSize + 4] & (1 << 4)) flags |= kAlphaFlag;
480 }
481 ok = ok && (fwrite(kVP8XHeader, kChunkHeaderSize, 1, out) == 1);
482 ok = ok && WriteLE32(out, flags);
483 ok = ok && WriteLE24(out, picture->width - 1);
484 ok = ok && WriteLE24(out, picture->height - 1);
485 }
486 if (write_iccp) {
487 ok = ok && WriteMetadataChunk(out, "ICCP", &metadata->iccp);
488 *metadata_written |= METADATA_ICC;
489 }
490 // Image
491 ok = ok && (fwrite(webp, webp_size, 1, out) == 1);
492 if (write_exif) {
493 ok = ok && WriteMetadataChunk(out, "EXIF", &metadata->exif);
494 *metadata_written |= METADATA_EXIF;
495 }
496 if (write_xmp) {
497 ok = ok && WriteMetadataChunk(out, "XMP ", &metadata->xmp);
498 *metadata_written |= METADATA_XMP;
499 }
500 return ok;
501 }
502
503 // No metadata, just write the original image file.
504 return (fwrite(webp, webp_size, 1, out) == 1);
505 }
506
507 //------------------------------------------------------------------------------
508
ProgressReport(int percent,const WebPPicture * const picture)509 static int ProgressReport(int percent, const WebPPicture* const picture) {
510 fprintf(stderr, "[%s]: %3d %% \r",
511 (char*)picture->user_data, percent);
512 return 1; // all ok
513 }
514
515 //------------------------------------------------------------------------------
516
HelpShort(void)517 static void HelpShort(void) {
518 printf("Usage:\n\n");
519 printf(" cwebp [options] -q quality input.png -o output.webp\n\n");
520 printf("where quality is between 0 (poor) to 100 (very good).\n");
521 printf("Typical value is around 80.\n\n");
522 printf("Try -longhelp for an exhaustive list of advanced options.\n");
523 }
524
HelpLong(void)525 static void HelpLong(void) {
526 printf("Usage:\n");
527 printf(" cwebp [-preset <...>] [options] in_file [-o out_file]\n\n");
528 printf("If input size (-s) for an image is not specified, it is\n"
529 "assumed to be a PNG, JPEG, TIFF or WebP file.\n");
530 printf("Note: Animated PNG and WebP files are not supported.\n");
531 #ifdef HAVE_WINCODEC_H
532 printf("Windows builds can take as input any of the files handled by WIC.\n");
533 #endif
534 printf("\nOptions:\n");
535 printf(" -h / -help ............. short help\n");
536 printf(" -H / -longhelp ......... long help\n");
537 printf(" -q <float> ............. quality factor (0:small..100:big), "
538 "default=75\n");
539 printf(" -alpha_q <int> ......... transparency-compression quality (0..100),"
540 "\n default=100\n");
541 printf(" -preset <string> ....... preset setting, one of:\n");
542 printf(" default, photo, picture,\n");
543 printf(" drawing, icon, text\n");
544 printf(" -preset must come first, as it overwrites other parameters\n");
545 printf(" -z <int> ............... activates lossless preset with given\n"
546 " level in [0:fast, ..., 9:slowest]\n");
547 printf("\n");
548 printf(" -m <int> ............... compression method (0=fast, 6=slowest), "
549 "default=4\n");
550 printf(" -segments <int> ........ number of segments to use (1..4), "
551 "default=4\n");
552 printf(" -size <int> ............ target size (in bytes)\n");
553 printf(" -psnr <float> .......... target PSNR (in dB. typically: 42)\n");
554 printf("\n");
555 printf(" -s <int> <int> ......... input size (width x height) for YUV\n");
556 printf(" -sns <int> ............. spatial noise shaping (0:off, 100:max), "
557 "default=50\n");
558 printf(" -f <int> ............... filter strength (0=off..100), "
559 "default=60\n");
560 printf(" -sharpness <int> ....... "
561 "filter sharpness (0:most .. 7:least sharp), default=0\n");
562 printf(" -strong ................ use strong filter instead "
563 "of simple (default)\n");
564 printf(" -nostrong .............. use simple filter instead of strong\n");
565 printf(" -sharp_yuv ............. use sharper (and slower) RGB->YUV "
566 "conversion\n");
567 printf(" -partition_limit <int> . limit quality to fit the 512k limit on\n");
568 printf(" "
569 "the first partition (0=no degradation ... 100=full)\n");
570 printf(" -pass <int> ............ analysis pass number (1..10)\n");
571 printf(" -qrange <min> <max> .... specifies the permissible quality range\n"
572 " (default: 0 100)\n");
573 printf(" -crop <x> <y> <w> <h> .. crop picture with the given rectangle\n");
574 printf(" -resize <w> <h> ........ resize picture (after any cropping)\n");
575 printf(" -mt .................... use multi-threading if available\n");
576 printf(" -low_memory ............ reduce memory usage (slower encoding)\n");
577 printf(" -map <int> ............. print map of extra info\n");
578 printf(" -print_psnr ............ prints averaged PSNR distortion\n");
579 printf(" -print_ssim ............ prints averaged SSIM distortion\n");
580 printf(" -print_lsim ............ prints local-similarity distortion\n");
581 printf(" -d <file.pgm> .......... dump the compressed output (PGM file)\n");
582 printf(" -alpha_method <int> .... transparency-compression method (0..1), "
583 "default=1\n");
584 printf(" -alpha_filter <string> . predictive filtering for alpha plane,\n");
585 printf(" one of: none, fast (default) or best\n");
586 printf(" -exact ................. preserve RGB values in transparent area, "
587 "default=off\n");
588 printf(" -blend_alpha <hex> ..... blend colors against background color\n"
589 " expressed as RGB values written in\n"
590 " hexadecimal, e.g. 0xc0e0d0 for red=0xc0\n"
591 " green=0xe0 and blue=0xd0\n");
592 printf(" -noalpha ............... discard any transparency information\n");
593 printf(" -lossless .............. encode image losslessly, default=off\n");
594 printf(" -near_lossless <int> ... use near-lossless image\n"
595 " preprocessing (0..100=off), "
596 "default=100\n");
597 printf(" -hint <string> ......... specify image characteristics hint,\n");
598 printf(" one of: photo, picture or graph\n");
599
600 printf("\n");
601 printf(" -metadata <string> ..... comma separated list of metadata to\n");
602 printf(" ");
603 printf("copy from the input to the output if present.\n");
604 printf(" "
605 "Valid values: all, none (default), exif, icc, xmp\n");
606
607 printf("\n");
608 printf(" -short ................. condense printed message\n");
609 printf(" -quiet ................. don't print anything\n");
610 printf(" -version ............... print version number and exit\n");
611 #ifndef WEBP_DLL
612 printf(" -noasm ................. disable all assembly optimizations\n");
613 #endif
614 printf(" -v ..................... verbose, e.g. print encoding/decoding "
615 "times\n");
616 printf(" -progress .............. report encoding progress\n");
617 printf("\n");
618 printf("Experimental Options:\n");
619 printf(" -jpeg_like ............. roughly match expected JPEG size\n");
620 printf(" -af .................... auto-adjust filter strength\n");
621 printf(" -pre <int> ............. pre-processing filter\n");
622 printf("\n");
623 }
624
625 //------------------------------------------------------------------------------
626 // Error messages
627
628 static const char* const kErrorMessages[VP8_ENC_ERROR_LAST] = {
629 "OK",
630 "OUT_OF_MEMORY: Out of memory allocating objects",
631 "BITSTREAM_OUT_OF_MEMORY: Out of memory re-allocating byte buffer",
632 "NULL_PARAMETER: NULL parameter passed to function",
633 "INVALID_CONFIGURATION: configuration is invalid",
634 "BAD_DIMENSION: Bad picture dimension. Maximum width and height "
635 "allowed is 16383 pixels.",
636 "PARTITION0_OVERFLOW: Partition #0 is too big to fit 512k.\n"
637 "To reduce the size of this partition, try using less segments "
638 "with the -segments option, and eventually reduce the number of "
639 "header bits using -partition_limit. More details are available "
640 "in the manual (`man cwebp`)",
641 "PARTITION_OVERFLOW: Partition is too big to fit 16M",
642 "BAD_WRITE: Picture writer returned an I/O error",
643 "FILE_TOO_BIG: File would be too big to fit in 4G",
644 "USER_ABORT: encoding abort requested by user"
645 };
646
647 //------------------------------------------------------------------------------
648
main(int argc,const char * argv[])649 int main(int argc, const char* argv[]) {
650 int return_value = -1;
651 const char* in_file = NULL, *out_file = NULL, *dump_file = NULL;
652 FILE* out = NULL;
653 int c;
654 int short_output = 0;
655 int quiet = 0;
656 int keep_alpha = 1;
657 int blend_alpha = 0;
658 uint32_t background_color = 0xffffffu;
659 int crop = 0, crop_x = 0, crop_y = 0, crop_w = 0, crop_h = 0;
660 int resize_w = 0, resize_h = 0;
661 int lossless_preset = 6;
662 int use_lossless_preset = -1; // -1=unset, 0=don't use, 1=use it
663 int show_progress = 0;
664 int keep_metadata = 0;
665 int metadata_written = 0;
666 WebPPicture picture;
667 int print_distortion = -1; // -1=off, 0=PSNR, 1=SSIM, 2=LSIM
668 WebPPicture original_picture; // when PSNR or SSIM is requested
669 WebPConfig config;
670 WebPAuxStats stats;
671 WebPMemoryWriter memory_writer;
672 int use_memory_writer;
673 Metadata metadata;
674 Stopwatch stop_watch;
675
676 INIT_WARGV(argc, argv);
677
678 MetadataInit(&metadata);
679 WebPMemoryWriterInit(&memory_writer);
680 if (!WebPPictureInit(&picture) ||
681 !WebPPictureInit(&original_picture) ||
682 !WebPConfigInit(&config)) {
683 fprintf(stderr, "Error! Version mismatch!\n");
684 FREE_WARGV_AND_RETURN(-1);
685 }
686
687 if (argc == 1) {
688 HelpShort();
689 FREE_WARGV_AND_RETURN(0);
690 }
691
692 for (c = 1; c < argc; ++c) {
693 int parse_error = 0;
694 if (!strcmp(argv[c], "-h") || !strcmp(argv[c], "-help")) {
695 HelpShort();
696 FREE_WARGV_AND_RETURN(0);
697 } else if (!strcmp(argv[c], "-H") || !strcmp(argv[c], "-longhelp")) {
698 HelpLong();
699 FREE_WARGV_AND_RETURN(0);
700 } else if (!strcmp(argv[c], "-o") && c + 1 < argc) {
701 out_file = (const char*)GET_WARGV(argv, ++c);
702 } else if (!strcmp(argv[c], "-d") && c + 1 < argc) {
703 dump_file = (const char*)GET_WARGV(argv, ++c);
704 config.show_compressed = 1;
705 } else if (!strcmp(argv[c], "-print_psnr")) {
706 config.show_compressed = 1;
707 print_distortion = 0;
708 } else if (!strcmp(argv[c], "-print_ssim")) {
709 config.show_compressed = 1;
710 print_distortion = 1;
711 } else if (!strcmp(argv[c], "-print_lsim")) {
712 config.show_compressed = 1;
713 print_distortion = 2;
714 } else if (!strcmp(argv[c], "-short")) {
715 ++short_output;
716 } else if (!strcmp(argv[c], "-s") && c + 2 < argc) {
717 picture.width = ExUtilGetInt(argv[++c], 0, &parse_error);
718 picture.height = ExUtilGetInt(argv[++c], 0, &parse_error);
719 if (picture.width > WEBP_MAX_DIMENSION || picture.width < 0 ||
720 picture.height > WEBP_MAX_DIMENSION || picture.height < 0) {
721 fprintf(stderr,
722 "Specified dimension (%d x %d) is out of range.\n",
723 picture.width, picture.height);
724 goto Error;
725 }
726 } else if (!strcmp(argv[c], "-m") && c + 1 < argc) {
727 config.method = ExUtilGetInt(argv[++c], 0, &parse_error);
728 use_lossless_preset = 0; // disable -z option
729 } else if (!strcmp(argv[c], "-q") && c + 1 < argc) {
730 config.quality = ExUtilGetFloat(argv[++c], &parse_error);
731 use_lossless_preset = 0; // disable -z option
732 } else if (!strcmp(argv[c], "-z") && c + 1 < argc) {
733 lossless_preset = ExUtilGetInt(argv[++c], 0, &parse_error);
734 if (use_lossless_preset != 0) use_lossless_preset = 1;
735 } else if (!strcmp(argv[c], "-alpha_q") && c + 1 < argc) {
736 config.alpha_quality = ExUtilGetInt(argv[++c], 0, &parse_error);
737 } else if (!strcmp(argv[c], "-alpha_method") && c + 1 < argc) {
738 config.alpha_compression = ExUtilGetInt(argv[++c], 0, &parse_error);
739 } else if (!strcmp(argv[c], "-alpha_cleanup")) {
740 // This flag is obsolete, does opposite of -exact.
741 config.exact = 0;
742 } else if (!strcmp(argv[c], "-exact")) {
743 config.exact = 1;
744 } else if (!strcmp(argv[c], "-blend_alpha") && c + 1 < argc) {
745 blend_alpha = 1;
746 // background color is given in hex with an optional '0x' prefix
747 background_color = ExUtilGetInt(argv[++c], 16, &parse_error);
748 background_color = background_color & 0x00ffffffu;
749 } else if (!strcmp(argv[c], "-alpha_filter") && c + 1 < argc) {
750 ++c;
751 if (!strcmp(argv[c], "none")) {
752 config.alpha_filtering = 0;
753 } else if (!strcmp(argv[c], "fast")) {
754 config.alpha_filtering = 1;
755 } else if (!strcmp(argv[c], "best")) {
756 config.alpha_filtering = 2;
757 } else {
758 fprintf(stderr, "Error! Unrecognized alpha filter: %s\n", argv[c]);
759 goto Error;
760 }
761 } else if (!strcmp(argv[c], "-noalpha")) {
762 keep_alpha = 0;
763 } else if (!strcmp(argv[c], "-lossless")) {
764 config.lossless = 1;
765 } else if (!strcmp(argv[c], "-near_lossless") && c + 1 < argc) {
766 config.near_lossless = ExUtilGetInt(argv[++c], 0, &parse_error);
767 config.lossless = 1; // use near-lossless only with lossless
768 } else if (!strcmp(argv[c], "-hint") && c + 1 < argc) {
769 ++c;
770 if (!strcmp(argv[c], "photo")) {
771 config.image_hint = WEBP_HINT_PHOTO;
772 } else if (!strcmp(argv[c], "picture")) {
773 config.image_hint = WEBP_HINT_PICTURE;
774 } else if (!strcmp(argv[c], "graph")) {
775 config.image_hint = WEBP_HINT_GRAPH;
776 } else {
777 fprintf(stderr, "Error! Unrecognized image hint: %s\n", argv[c]);
778 goto Error;
779 }
780 } else if (!strcmp(argv[c], "-size") && c + 1 < argc) {
781 config.target_size = ExUtilGetInt(argv[++c], 0, &parse_error);
782 } else if (!strcmp(argv[c], "-psnr") && c + 1 < argc) {
783 config.target_PSNR = ExUtilGetFloat(argv[++c], &parse_error);
784 } else if (!strcmp(argv[c], "-sns") && c + 1 < argc) {
785 config.sns_strength = ExUtilGetInt(argv[++c], 0, &parse_error);
786 } else if (!strcmp(argv[c], "-f") && c + 1 < argc) {
787 config.filter_strength = ExUtilGetInt(argv[++c], 0, &parse_error);
788 } else if (!strcmp(argv[c], "-af")) {
789 config.autofilter = 1;
790 } else if (!strcmp(argv[c], "-jpeg_like")) {
791 config.emulate_jpeg_size = 1;
792 } else if (!strcmp(argv[c], "-mt")) {
793 ++config.thread_level; // increase thread level
794 } else if (!strcmp(argv[c], "-low_memory")) {
795 config.low_memory = 1;
796 } else if (!strcmp(argv[c], "-strong")) {
797 config.filter_type = 1;
798 } else if (!strcmp(argv[c], "-nostrong")) {
799 config.filter_type = 0;
800 } else if (!strcmp(argv[c], "-sharpness") && c + 1 < argc) {
801 config.filter_sharpness = ExUtilGetInt(argv[++c], 0, &parse_error);
802 } else if (!strcmp(argv[c], "-sharp_yuv")) {
803 config.use_sharp_yuv = 1;
804 } else if (!strcmp(argv[c], "-pass") && c + 1 < argc) {
805 config.pass = ExUtilGetInt(argv[++c], 0, &parse_error);
806 } else if (!strcmp(argv[c], "-qrange") && c + 2 < argc) {
807 config.qmin = ExUtilGetInt(argv[++c], 0, &parse_error);
808 config.qmax = ExUtilGetInt(argv[++c], 0, &parse_error);
809 if (config.qmin < 0) config.qmin = 0;
810 if (config.qmax > 100) config.qmax = 100;
811 } else if (!strcmp(argv[c], "-pre") && c + 1 < argc) {
812 config.preprocessing = ExUtilGetInt(argv[++c], 0, &parse_error);
813 } else if (!strcmp(argv[c], "-segments") && c + 1 < argc) {
814 config.segments = ExUtilGetInt(argv[++c], 0, &parse_error);
815 } else if (!strcmp(argv[c], "-partition_limit") && c + 1 < argc) {
816 config.partition_limit = ExUtilGetInt(argv[++c], 0, &parse_error);
817 } else if (!strcmp(argv[c], "-map") && c + 1 < argc) {
818 picture.extra_info_type = ExUtilGetInt(argv[++c], 0, &parse_error);
819 } else if (!strcmp(argv[c], "-crop") && c + 4 < argc) {
820 crop = 1;
821 crop_x = ExUtilGetInt(argv[++c], 0, &parse_error);
822 crop_y = ExUtilGetInt(argv[++c], 0, &parse_error);
823 crop_w = ExUtilGetInt(argv[++c], 0, &parse_error);
824 crop_h = ExUtilGetInt(argv[++c], 0, &parse_error);
825 } else if (!strcmp(argv[c], "-resize") && c + 2 < argc) {
826 resize_w = ExUtilGetInt(argv[++c], 0, &parse_error);
827 resize_h = ExUtilGetInt(argv[++c], 0, &parse_error);
828 #ifndef WEBP_DLL
829 } else if (!strcmp(argv[c], "-noasm")) {
830 VP8GetCPUInfo = NULL;
831 #endif
832 } else if (!strcmp(argv[c], "-version")) {
833 const int version = WebPGetEncoderVersion();
834 printf("%d.%d.%d\n",
835 (version >> 16) & 0xff, (version >> 8) & 0xff, version & 0xff);
836 FREE_WARGV_AND_RETURN(0);
837 } else if (!strcmp(argv[c], "-progress")) {
838 show_progress = 1;
839 } else if (!strcmp(argv[c], "-quiet")) {
840 quiet = 1;
841 } else if (!strcmp(argv[c], "-preset") && c + 1 < argc) {
842 WebPPreset preset;
843 ++c;
844 if (!strcmp(argv[c], "default")) {
845 preset = WEBP_PRESET_DEFAULT;
846 } else if (!strcmp(argv[c], "photo")) {
847 preset = WEBP_PRESET_PHOTO;
848 } else if (!strcmp(argv[c], "picture")) {
849 preset = WEBP_PRESET_PICTURE;
850 } else if (!strcmp(argv[c], "drawing")) {
851 preset = WEBP_PRESET_DRAWING;
852 } else if (!strcmp(argv[c], "icon")) {
853 preset = WEBP_PRESET_ICON;
854 } else if (!strcmp(argv[c], "text")) {
855 preset = WEBP_PRESET_TEXT;
856 } else {
857 fprintf(stderr, "Error! Unrecognized preset: %s\n", argv[c]);
858 goto Error;
859 }
860 if (!WebPConfigPreset(&config, preset, config.quality)) {
861 fprintf(stderr, "Error! Could initialize configuration with preset.\n");
862 goto Error;
863 }
864 } else if (!strcmp(argv[c], "-metadata") && c + 1 < argc) {
865 static const struct {
866 const char* option;
867 int flag;
868 } kTokens[] = {
869 { "all", METADATA_ALL },
870 { "none", 0 },
871 { "exif", METADATA_EXIF },
872 { "icc", METADATA_ICC },
873 { "xmp", METADATA_XMP },
874 };
875 const size_t kNumTokens = sizeof(kTokens) / sizeof(kTokens[0]);
876 const char* start = argv[++c];
877 const char* const end = start + strlen(start);
878
879 while (start < end) {
880 size_t i;
881 const char* token = strchr(start, ',');
882 if (token == NULL) token = end;
883
884 for (i = 0; i < kNumTokens; ++i) {
885 if ((size_t)(token - start) == strlen(kTokens[i].option) &&
886 !strncmp(start, kTokens[i].option, strlen(kTokens[i].option))) {
887 if (kTokens[i].flag != 0) {
888 keep_metadata |= kTokens[i].flag;
889 } else {
890 keep_metadata = 0;
891 }
892 break;
893 }
894 }
895 if (i == kNumTokens) {
896 fprintf(stderr, "Error! Unknown metadata type '%.*s'\n",
897 (int)(token - start), start);
898 FREE_WARGV_AND_RETURN(-1);
899 }
900 start = token + 1;
901 }
902 #ifdef HAVE_WINCODEC_H
903 if (keep_metadata != 0 && keep_metadata != METADATA_ICC) {
904 // TODO(jzern): remove when -metadata is supported on all platforms.
905 fprintf(stderr, "Warning: only ICC profile extraction is currently"
906 " supported on this platform!\n");
907 }
908 #endif
909 } else if (!strcmp(argv[c], "-v")) {
910 verbose = 1;
911 } else if (!strcmp(argv[c], "--")) {
912 if (c + 1 < argc) in_file = (const char*)GET_WARGV(argv, ++c);
913 break;
914 } else if (argv[c][0] == '-') {
915 fprintf(stderr, "Error! Unknown option '%s'\n", argv[c]);
916 HelpLong();
917 FREE_WARGV_AND_RETURN(-1);
918 } else {
919 in_file = (const char*)GET_WARGV(argv, c);
920 }
921
922 if (parse_error) {
923 HelpLong();
924 FREE_WARGV_AND_RETURN(-1);
925 }
926 }
927 if (in_file == NULL) {
928 fprintf(stderr, "No input file specified!\n");
929 HelpShort();
930 goto Error;
931 }
932
933 if (use_lossless_preset == 1) {
934 if (!WebPConfigLosslessPreset(&config, lossless_preset)) {
935 fprintf(stderr, "Invalid lossless preset (-z %d)\n", lossless_preset);
936 goto Error;
937 }
938 }
939
940 // Check for unsupported command line options for lossless mode and log
941 // warning for such options.
942 if (!quiet && config.lossless == 1) {
943 if (config.target_size > 0 || config.target_PSNR > 0) {
944 fprintf(stderr, "Encoding for specified size or PSNR is not supported"
945 " for lossless encoding. Ignoring such option(s)!\n");
946 }
947 if (config.partition_limit > 0) {
948 fprintf(stderr, "Partition limit option is not required for lossless"
949 " encoding. Ignoring this option!\n");
950 }
951 }
952 // If a target size or PSNR was given, but somehow the -pass option was
953 // omitted, force a reasonable value.
954 if (config.target_size > 0 || config.target_PSNR > 0) {
955 if (config.pass == 1) config.pass = 6;
956 }
957
958 if (!WebPValidateConfig(&config)) {
959 fprintf(stderr, "Error! Invalid configuration.\n");
960 goto Error;
961 }
962
963 // Read the input. We need to decide if we prefer ARGB or YUVA
964 // samples, depending on the expected compression mode (this saves
965 // some conversion steps).
966 picture.use_argb = (config.lossless || config.use_sharp_yuv ||
967 config.preprocessing > 0 ||
968 crop || (resize_w | resize_h) > 0);
969 if (verbose) {
970 StopwatchReset(&stop_watch);
971 }
972 if (!ReadPicture(in_file, &picture, keep_alpha,
973 (keep_metadata == 0) ? NULL : &metadata)) {
974 WFPRINTF(stderr, "Error! Cannot read input picture file '%s'\n",
975 (const W_CHAR*)in_file);
976 goto Error;
977 }
978 picture.progress_hook = (show_progress && !quiet) ? ProgressReport : NULL;
979
980 if (blend_alpha) {
981 WebPBlendAlpha(&picture, background_color);
982 }
983
984 if (verbose) {
985 const double read_time = StopwatchReadAndReset(&stop_watch);
986 fprintf(stderr, "Time to read input: %.3fs\n", read_time);
987 }
988 // The bitstream should be kept in memory when metadata must be appended
989 // before writing it to a file/stream, and/or when the near-losslessly encoded
990 // bitstream must be decoded for distortion computation (lossy will modify the
991 // 'picture' but not the lossless pipeline).
992 // Otherwise directly write the bitstream to a file.
993 use_memory_writer = (out_file != NULL && keep_metadata) ||
994 (!quiet && print_distortion >= 0 && config.lossless &&
995 config.near_lossless < 100);
996
997 // Open the output
998 if (out_file != NULL) {
999 const int use_stdout = !WSTRCMP(out_file, "-");
1000 out = use_stdout ? ImgIoUtilSetBinaryMode(stdout) : WFOPEN(out_file, "wb");
1001 if (out == NULL) {
1002 WFPRINTF(stderr, "Error! Cannot open output file '%s'\n",
1003 (const W_CHAR*)out_file);
1004 goto Error;
1005 } else {
1006 if (!short_output && !quiet) {
1007 WFPRINTF(stderr, "Saving file '%s'\n", (const W_CHAR*)out_file);
1008 }
1009 }
1010 if (use_memory_writer) {
1011 picture.writer = WebPMemoryWrite;
1012 picture.custom_ptr = (void*)&memory_writer;
1013 } else {
1014 picture.writer = MyWriter;
1015 picture.custom_ptr = (void*)out;
1016 }
1017 } else {
1018 out = NULL;
1019 if (use_memory_writer) {
1020 picture.writer = WebPMemoryWrite;
1021 picture.custom_ptr = (void*)&memory_writer;
1022 }
1023 if (!quiet && !short_output) {
1024 fprintf(stderr, "No output file specified (no -o flag). Encoding will\n");
1025 fprintf(stderr, "be performed, but its results discarded.\n\n");
1026 }
1027 }
1028 if (!quiet) {
1029 picture.stats = &stats;
1030 picture.user_data = (void*)in_file;
1031 }
1032
1033 // Crop & resize.
1034 if (verbose) {
1035 StopwatchReset(&stop_watch);
1036 }
1037 if (crop != 0) {
1038 // We use self-cropping using a view.
1039 if (!WebPPictureView(&picture, crop_x, crop_y, crop_w, crop_h, &picture)) {
1040 fprintf(stderr, "Error! Cannot crop picture\n");
1041 goto Error;
1042 }
1043 }
1044 if ((resize_w | resize_h) > 0) {
1045 WebPPicture picture_no_alpha;
1046 if (config.exact) {
1047 // If -exact, we can't premultiply RGB by A otherwise RGB is lost if A=0.
1048 // We rescale an opaque copy and assemble scaled A and non-premultiplied
1049 // RGB channels. This is slower but it's a very uncommon use case. Color
1050 // leak at sharp alpha edges is possible.
1051 if (!WebPPictureCopy(&picture, &picture_no_alpha)) {
1052 fprintf(stderr, "Error! Cannot copy temporary picture\n");
1053 goto Error;
1054 }
1055
1056 // We enforced picture.use_argb = 1 above. Now, remove the alpha values.
1057 {
1058 int x, y;
1059 uint32_t* argb_no_alpha = picture_no_alpha.argb;
1060 for (y = 0; y < picture_no_alpha.height; ++y) {
1061 for (x = 0; x < picture_no_alpha.width; ++x) {
1062 argb_no_alpha[x] |= 0xff000000; // Opaque copy.
1063 }
1064 argb_no_alpha += picture_no_alpha.argb_stride;
1065 }
1066 }
1067
1068 if (!WebPPictureRescale(&picture_no_alpha, resize_w, resize_h)) {
1069 fprintf(stderr, "Error! Cannot resize temporary picture\n");
1070 goto Error;
1071 }
1072 }
1073
1074 if (!WebPPictureRescale(&picture, resize_w, resize_h)) {
1075 fprintf(stderr, "Error! Cannot resize picture\n");
1076 goto Error;
1077 }
1078
1079 if (config.exact) { // Put back the alpha information.
1080 int x, y;
1081 uint32_t* argb_no_alpha = picture_no_alpha.argb;
1082 uint32_t* argb = picture.argb;
1083 for (y = 0; y < picture_no_alpha.height; ++y) {
1084 for (x = 0; x < picture_no_alpha.width; ++x) {
1085 argb[x] = (argb[x] & 0xff000000) | (argb_no_alpha[x] & 0x00ffffff);
1086 }
1087 argb_no_alpha += picture_no_alpha.argb_stride;
1088 argb += picture.argb_stride;
1089 }
1090 WebPPictureFree(&picture_no_alpha);
1091 }
1092 }
1093 if (verbose && (crop != 0 || (resize_w | resize_h) > 0)) {
1094 const double preproc_time = StopwatchReadAndReset(&stop_watch);
1095 fprintf(stderr, "Time to crop/resize picture: %.3fs\n", preproc_time);
1096 }
1097
1098 if (picture.extra_info_type > 0) {
1099 AllocExtraInfo(&picture);
1100 }
1101 // Save original picture for later comparison. Only for lossy as lossless does
1102 // not modify 'picture' (even near-lossless).
1103 if (print_distortion >= 0 && !config.lossless &&
1104 !WebPPictureCopy(&picture, &original_picture)) {
1105 fprintf(stderr, "Error! Cannot copy temporary picture\n");
1106 goto Error;
1107 }
1108
1109 // Compress.
1110 if (verbose) {
1111 StopwatchReset(&stop_watch);
1112 }
1113 if (!WebPEncode(&config, &picture)) {
1114 fprintf(stderr, "Error! Cannot encode picture as WebP\n");
1115 fprintf(stderr, "Error code: %d (%s)\n",
1116 picture.error_code, kErrorMessages[picture.error_code]);
1117 goto Error;
1118 }
1119 if (verbose) {
1120 const double encode_time = StopwatchReadAndReset(&stop_watch);
1121 fprintf(stderr, "Time to encode picture: %.3fs\n", encode_time);
1122 }
1123
1124 // Get the decompressed image for the lossless pipeline.
1125 if (!quiet && print_distortion >= 0 && config.lossless) {
1126 if (config.near_lossless == 100) {
1127 // Pure lossless: image was not modified, make 'original_picture' a view
1128 // of 'picture' by copying all members except the freeable pointers.
1129 original_picture = picture;
1130 original_picture.memory_ = original_picture.memory_argb_ = NULL;
1131 } else {
1132 // Decode the bitstream stored in 'memory_writer' to get the altered image
1133 // to 'picture'; save the 'original_picture' beforehand.
1134 assert(use_memory_writer);
1135 original_picture = picture;
1136 if (!WebPPictureInit(&picture)) { // Do not free 'picture'.
1137 fprintf(stderr, "Error! Version mismatch!\n");
1138 goto Error;
1139 }
1140
1141 picture.use_argb = 1;
1142 if (!ReadWebP(memory_writer.mem, memory_writer.size, &picture,
1143 /*keep_alpha=*/WebPPictureHasTransparency(&picture),
1144 /*metadata=*/NULL)) {
1145 fprintf(stderr, "Error! Cannot decode encoded WebP bitstream\n");
1146 fprintf(stderr, "Error code: %d (%s)\n", picture.error_code,
1147 kErrorMessages[picture.error_code]);
1148 goto Error;
1149 }
1150 picture.stats = original_picture.stats;
1151 }
1152 original_picture.stats = NULL;
1153 }
1154
1155 // Write the YUV planes to a PGM file. Only available for lossy.
1156 if (dump_file) {
1157 if (picture.use_argb) {
1158 fprintf(stderr, "Warning: can't dump file (-d option) "
1159 "in lossless mode.\n");
1160 } else if (!DumpPicture(&picture, dump_file)) {
1161 WFPRINTF(stderr, "Warning, couldn't dump picture %s\n",
1162 (const W_CHAR*)dump_file);
1163 }
1164 }
1165
1166 if (use_memory_writer && out != NULL &&
1167 !WriteWebPWithMetadata(out, &picture, &memory_writer, &metadata,
1168 keep_metadata, &metadata_written)) {
1169 fprintf(stderr, "Error writing WebP file!\n");
1170 goto Error;
1171 }
1172
1173 if (out == NULL && keep_metadata) {
1174 // output is disabled, just display the metadata stats.
1175 const struct {
1176 const MetadataPayload* const payload;
1177 int flag;
1178 } *iter, info[] = {{&metadata.exif, METADATA_EXIF},
1179 {&metadata.iccp, METADATA_ICC},
1180 {&metadata.xmp, METADATA_XMP},
1181 {NULL, 0}};
1182 uint32_t unused1 = 0;
1183 uint64_t unused2 = 0;
1184
1185 for (iter = info; iter->payload != NULL; ++iter) {
1186 if (UpdateFlagsAndSize(iter->payload, !!(keep_metadata & iter->flag),
1187 /*flag=*/0, &unused1, &unused2)) {
1188 metadata_written |= iter->flag;
1189 }
1190 }
1191 }
1192
1193 if (!quiet) {
1194 if (!short_output || print_distortion < 0) {
1195 if (config.lossless) {
1196 PrintExtraInfoLossless(&picture, short_output, in_file);
1197 } else {
1198 PrintExtraInfoLossy(&picture, short_output, config.low_memory, in_file);
1199 }
1200 }
1201 if (!short_output && picture.extra_info_type > 0) {
1202 PrintMapInfo(&picture);
1203 }
1204 if (print_distortion >= 0) { // print distortion
1205 static const char* distortion_names[] = { "PSNR", "SSIM", "LSIM" };
1206 float values[5];
1207 if (!WebPPictureDistortion(&picture, &original_picture,
1208 print_distortion, values)) {
1209 fprintf(stderr, "Error while computing the distortion.\n");
1210 goto Error;
1211 }
1212 if (!short_output) {
1213 fprintf(stderr, "%s: ", distortion_names[print_distortion]);
1214 fprintf(stderr, "B:%.2f G:%.2f R:%.2f A:%.2f Total:%.2f\n",
1215 values[0], values[1], values[2], values[3], values[4]);
1216 } else {
1217 fprintf(stderr, "%7d %.4f\n", picture.stats->coded_size, values[4]);
1218 }
1219 }
1220 if (!short_output) {
1221 PrintMetadataInfo(&metadata, metadata_written);
1222 }
1223 }
1224 return_value = 0;
1225
1226 Error:
1227 WebPMemoryWriterClear(&memory_writer);
1228 WebPFree(picture.extra_info);
1229 MetadataFree(&metadata);
1230 WebPPictureFree(&picture);
1231 WebPPictureFree(&original_picture);
1232 if (out != NULL && out != stdout) {
1233 fclose(out);
1234 }
1235
1236 FREE_WARGV_AND_RETURN(return_value);
1237 }
1238
1239 //------------------------------------------------------------------------------
1240