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