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