Coverage Report

Created: 2025-07-01 06:35

/src/libwebp/imageio/pnmdec.c
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2017 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
// (limited) PNM decoder
11
12
#include "./pnmdec.h"
13
14
#include <assert.h>
15
#include <ctype.h>
16
#include <stdio.h>
17
#include <stdlib.h>
18
#include <string.h>
19
20
#include "./imageio_util.h"
21
#include "webp/encode.h"
22
#include "webp/types.h"
23
24
#if defined(_MSC_VER) && _MSC_VER < 1900
25
#define snprintf _snprintf
26
#endif
27
28
typedef enum {
29
  WIDTH_FLAG      = 1 << 0,
30
  HEIGHT_FLAG     = 1 << 1,
31
  DEPTH_FLAG      = 1 << 2,
32
  MAXVAL_FLAG     = 1 << 3,
33
  TUPLE_FLAG      = 1 << 4,
34
  ALL_NEEDED_FLAGS = WIDTH_FLAG | HEIGHT_FLAG | DEPTH_FLAG | MAXVAL_FLAG
35
} PNMFlags;
36
37
typedef struct {
38
  const uint8_t* data;
39
  size_t data_size;
40
  int width, height;
41
  int bytes_per_px;
42
  int depth;          // 1 (grayscale), 2 (grayscale + alpha), 3 (rgb), 4 (rgba)
43
  int max_value;
44
  int type;           // 5, 6 or 7
45
  int seen_flags;
46
} PNMInfo;
47
48
// -----------------------------------------------------------------------------
49
// PNM decoding
50
51
0
#define MAX_LINE_SIZE 1024
52
static const size_t kMinPNMHeaderSize = 3;
53
54
static size_t ReadLine(const uint8_t* const data, size_t off, size_t data_size,
55
0
                       char out[MAX_LINE_SIZE + 1], size_t* const out_size) {
56
0
  size_t i = 0;
57
0
  *out_size = 0;
58
0
 redo:
59
0
  for (i = 0; i < MAX_LINE_SIZE && off < data_size; ++i) {
60
0
    out[i] = data[off++];
61
0
    if (out[i] == '\n') break;
62
0
  }
63
0
  if (off < data_size) {
64
0
    if (i == 0) goto redo;         // empty line
65
0
    if (out[0] == '#') goto redo;  // skip comment
66
0
  }
67
0
  out[i] = 0;   // safety sentinel
68
0
  *out_size = i;
69
0
  return off;
70
0
}
71
72
0
static size_t FlagError(const char flag[]) {
73
0
  fprintf(stderr, "PAM header error: flags '%s' already seen.\n", flag);
74
0
  return 0;
75
0
}
76
77
// inspired from http://netpbm.sourceforge.net/doc/pam.html
78
0
static size_t ReadPAMFields(PNMInfo* const info, size_t off) {
79
0
  char out[MAX_LINE_SIZE + 1];
80
0
  size_t out_size;
81
0
  int tmp;
82
0
  int expected_depth = -1;
83
0
  assert(info != NULL);
84
0
  while (1) {
85
0
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
86
0
    if (off == 0) return 0;
87
0
    if (sscanf(out, "WIDTH %d", &tmp) == 1) {
88
0
      if (info->seen_flags & WIDTH_FLAG) return FlagError("WIDTH");
89
0
      info->seen_flags |= WIDTH_FLAG;
90
0
      info->width = tmp;
91
0
    } else if (sscanf(out, "HEIGHT %d", &tmp) == 1) {
92
0
      if (info->seen_flags & HEIGHT_FLAG) return FlagError("HEIGHT");
93
0
      info->seen_flags |= HEIGHT_FLAG;
94
0
      info->height = tmp;
95
0
    } else if (sscanf(out, "DEPTH %d", &tmp) == 1) {
96
0
      if (info->seen_flags & DEPTH_FLAG) return FlagError("DEPTH");
97
0
      info->seen_flags |= DEPTH_FLAG;
98
0
      info->depth = tmp;
99
0
    } else if (sscanf(out, "MAXVAL %d", &tmp) == 1) {
100
0
      if (info->seen_flags & MAXVAL_FLAG) return FlagError("MAXVAL");
101
0
      info->seen_flags |= MAXVAL_FLAG;
102
0
      info->max_value = tmp;
103
0
    } else if (!strcmp(out, "TUPLTYPE RGB_ALPHA")) {
104
0
      expected_depth = 4;
105
0
      info->seen_flags |= TUPLE_FLAG;
106
0
    } else if (!strcmp(out, "TUPLTYPE RGB")) {
107
0
      expected_depth = 3;
108
0
      info->seen_flags |= TUPLE_FLAG;
109
0
    } else if (!strcmp(out, "TUPLTYPE GRAYSCALE_ALPHA")) {
110
0
      expected_depth = 2;
111
0
      info->seen_flags |= TUPLE_FLAG;
112
0
    } else if (!strcmp(out, "TUPLTYPE GRAYSCALE")) {
113
0
      expected_depth = 1;
114
0
      info->seen_flags |= TUPLE_FLAG;
115
0
    } else if (!strcmp(out, "ENDHDR")) {
116
0
      break;
117
0
    } else {
118
0
      static const char kEllipsis[] = " ...";
119
0
      const size_t kLen = strlen(kEllipsis) + 1;  // +1 = trailing \0
120
0
      int i;
121
0
      if (out_size > 20) snprintf(out + 20 - kLen, kLen, kEllipsis);
122
0
      for (i = 0; i < (int)strlen(out); ++i) {
123
        // isprint() might trigger a "char-subscripts" warning if given a char.
124
0
        if (!isprint((int)out[i])) out[i] = ' ';
125
0
      }
126
0
      fprintf(stderr, "PAM header error: unrecognized entry [%s]\n", out);
127
0
      return 0;
128
0
    }
129
0
  }
130
0
  if (!(info->seen_flags & ALL_NEEDED_FLAGS)) {
131
0
    fprintf(stderr, "PAM header error: missing tags%s%s%s%s\n",
132
0
            (info->seen_flags & WIDTH_FLAG) ? "" : " WIDTH",
133
0
            (info->seen_flags & HEIGHT_FLAG) ? "" : " HEIGHT",
134
0
            (info->seen_flags & DEPTH_FLAG) ? "" : " DEPTH",
135
0
            (info->seen_flags & MAXVAL_FLAG) ? "" : " MAXVAL");
136
0
    return 0;
137
0
  }
138
0
  if (expected_depth != -1 && info->depth != expected_depth) {
139
0
    fprintf(stderr, "PAM header error: expected DEPTH %d but got DEPTH %d\n",
140
0
            expected_depth, info->depth);
141
0
    return 0;
142
0
  }
143
0
  return off;
144
0
}
145
146
0
static size_t ReadHeader(PNMInfo* const info) {
147
0
  size_t off = 0;
148
0
  char out[MAX_LINE_SIZE + 1];
149
0
  size_t out_size;
150
0
  if (info == NULL) return 0;
151
0
  if (info->data == NULL || info->data_size < kMinPNMHeaderSize) return 0;
152
153
0
  info->width = info->height = 0;
154
0
  info->type = -1;
155
0
  info->seen_flags = 0;
156
0
  info->bytes_per_px = 0;
157
0
  info->depth = 0;
158
0
  info->max_value = 0;
159
160
0
  off = ReadLine(info->data, off, info->data_size, out, &out_size);
161
0
  if (off == 0 || sscanf(out, "P%d", &info->type) != 1) return 0;
162
0
  if (info->type == 7) {
163
0
    off = ReadPAMFields(info, off);
164
0
  } else {
165
0
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
166
0
    if (off == 0 || sscanf(out, "%d %d", &info->width, &info->height) != 2) {
167
0
      return 0;
168
0
    }
169
0
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
170
0
    if (off == 0 || sscanf(out, "%d", &info->max_value) != 1) return 0;
171
172
    // finish initializing missing fields
173
0
    info->depth = (info->type == 5) ? 1 : 3;
174
0
  }
175
  // perform some basic numerical validation
176
0
  if (info->width <= 0 || info->height <= 0 ||
177
0
      info->type <= 0 || info->type >= 9 ||
178
0
      info->depth <= 0 || info->depth > 4 ||
179
0
      info->max_value <= 0 || info->max_value >= 65536) {
180
0
    return 0;
181
0
  }
182
0
  info->bytes_per_px = info->depth * (info->max_value > 255 ? 2 : 1);
183
0
  return off;
184
0
}
185
186
int ReadPNM(const uint8_t* const data, size_t data_size,
187
            WebPPicture* const pic, int keep_alpha,
188
0
            struct Metadata* const metadata) {
189
0
  int ok = 0;
190
0
  int i, j;
191
0
  uint64_t stride, pixel_bytes, sample_size, depth;
192
0
  uint8_t* rgb = NULL, *tmp_rgb;
193
0
  size_t offset;
194
0
  PNMInfo info;
195
196
0
  info.data = data;
197
0
  info.data_size = data_size;
198
0
  offset = ReadHeader(&info);
199
0
  if (offset == 0) {
200
0
    fprintf(stderr, "Error parsing PNM header.\n");
201
0
    goto End;
202
0
  }
203
204
0
  if (info.type < 5 || info.type > 7) {
205
0
    fprintf(stderr, "Unsupported P%d PNM format.\n", info.type);
206
0
    goto End;
207
0
  }
208
209
  // Some basic validations.
210
0
  if (pic == NULL) goto End;
211
0
  if (info.width > WEBP_MAX_DIMENSION || info.height > WEBP_MAX_DIMENSION) {
212
0
    fprintf(stderr, "Invalid %dx%d dimension for PNM\n",
213
0
                    info.width, info.height);
214
0
    goto End;
215
0
  }
216
217
0
  pixel_bytes = (uint64_t)info.width * info.height * info.bytes_per_px;
218
0
  if (data_size < offset + pixel_bytes) {
219
0
    fprintf(stderr, "Truncated PNM file (P%d).\n", info.type);
220
0
    goto End;
221
0
  }
222
0
  sample_size = (info.max_value > 255) ? 2 : 1;
223
  // final depth
224
0
  depth = (info.depth == 1 || info.depth == 3 || !keep_alpha) ? 3 : 4;
225
0
  stride = depth * info.width;
226
0
  if (stride != (size_t)stride ||
227
0
      !ImgIoUtilCheckSizeArgumentsOverflow(stride, info.height)) {
228
0
    goto End;
229
0
  }
230
231
0
  rgb = (uint8_t*)malloc((size_t)stride * info.height);
232
0
  if (rgb == NULL) goto End;
233
234
  // Convert input.
235
  // We only optimize for the sample_size=1, max_value=255, depth=1 case.
236
0
  tmp_rgb = rgb;
237
0
  for (j = 0; j < info.height; ++j) {
238
0
    const uint8_t* in = data + offset;
239
0
    offset += info.bytes_per_px * info.width;
240
0
    assert(offset <= data_size);
241
0
    if (info.max_value == 255 && info.depth >= 3) {
242
      // RGB or RGBA
243
0
      if (info.depth == 3 || keep_alpha) {
244
0
        memcpy(tmp_rgb, in, info.depth * info.width * sizeof(*in));
245
0
      } else {
246
0
        assert(info.depth == 4 && !keep_alpha);
247
0
        for (i = 0; i < info.width; ++i) {
248
0
          tmp_rgb[3 * i + 0] = in[4 * i + 0];
249
0
          tmp_rgb[3 * i + 1] = in[4 * i + 1];
250
0
          tmp_rgb[3 * i + 2] = in[4 * i + 2];
251
0
        }
252
0
      }
253
0
    } else {
254
      // Unoptimized case, we need to handle non-trivial operations:
255
      //   * convert 16b to 8b (if max_value > 255)
256
      //   * rescale to [0..255] range (if max_value != 255)
257
      //   * drop the alpha channel (if keep_alpha is false)
258
0
      const uint32_t round = info.max_value / 2;
259
0
      int k = 0;
260
0
      for (i = 0; i < info.width * info.depth; ++i) {
261
0
        uint32_t v = (sample_size == 2) ? 256u * in[2 * i + 0] + in[2 * i + 1]
262
0
                   : in[i];
263
0
        if (info.max_value != 255) v = (v * 255u + round) / info.max_value;
264
0
        if (v > 255u) v = 255u;
265
0
        if (info.depth > 2) {
266
0
          if (!keep_alpha && info.depth == 4 && (i % 4) == 3) {
267
            // skip alpha
268
0
          } else {
269
0
            tmp_rgb[k] = v;
270
0
            k += 1;
271
0
          }
272
0
        } else if (info.depth == 1 || (i % 2) == 0) {
273
0
          tmp_rgb[k + 0] = tmp_rgb[k + 1] = tmp_rgb[k + 2] = v;
274
0
          k += 3;
275
0
        } else if (keep_alpha && info.depth == 2) {
276
0
          tmp_rgb[k] = v;
277
0
          k += 1;
278
0
        } else {
279
          // skip alpha
280
0
        }
281
0
      }
282
0
    }
283
0
    tmp_rgb += stride;
284
0
  }
285
286
  // WebP conversion.
287
0
  pic->width = info.width;
288
0
  pic->height = info.height;
289
0
  ok = (depth == 4) ? WebPPictureImportRGBA(pic, rgb, (int)stride)
290
0
                    : WebPPictureImportRGB(pic, rgb, (int)stride);
291
0
  if (!ok) goto End;
292
293
0
  ok = 1;
294
0
 End:
295
0
  free((void*)rgb);
296
297
0
  (void)metadata;
298
0
  (void)keep_alpha;
299
0
  return ok;
300
0
}
301
302
// -----------------------------------------------------------------------------