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