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