Coverage Report

Created: 2025-07-18 06:23

/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
6.24M
#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
22.6k
                       char out[MAX_LINE_SIZE + 1], size_t* const out_size) {
56
22.6k
  size_t i = 0;
57
22.6k
  *out_size = 0;
58
29.1k
 redo:
59
3.12M
  for (i = 0; i < MAX_LINE_SIZE && off < data_size; ++i) {
60
3.11M
    out[i] = data[off++];
61
3.11M
    if (out[i] == '\n') break;
62
3.11M
  }
63
29.1k
  if (off < data_size) {
64
27.7k
    if (i == 0) goto redo;         // empty line
65
24.8k
    if (out[0] == '#') goto redo;  // skip comment
66
24.8k
  }
67
22.6k
  out[i] = 0;   // safety sentinel
68
22.6k
  *out_size = i;
69
22.6k
  return off;
70
29.1k
}
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
567
static size_t ReadPAMFields(PNMInfo* const info, size_t off) {
79
567
  char out[MAX_LINE_SIZE + 1];
80
567
  size_t out_size;
81
567
  int tmp;
82
567
  int expected_depth = -1;
83
567
  assert(info != NULL);
84
571
  while (1) {
85
571
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
86
571
    if (off == 0) return 0;
87
571
    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
571
    } 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
571
    } 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
571
    } 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
571
    } else if (!strcmp(out, "TUPLTYPE RGB_ALPHA")) {
104
0
      expected_depth = 4;
105
0
      info->seen_flags |= TUPLE_FLAG;
106
571
    } else if (!strcmp(out, "TUPLTYPE RGB")) {
107
3
      expected_depth = 3;
108
3
      info->seen_flags |= TUPLE_FLAG;
109
568
    } else if (!strcmp(out, "TUPLTYPE GRAYSCALE_ALPHA")) {
110
0
      expected_depth = 2;
111
0
      info->seen_flags |= TUPLE_FLAG;
112
568
    } else if (!strcmp(out, "TUPLTYPE GRAYSCALE")) {
113
1
      expected_depth = 1;
114
1
      info->seen_flags |= TUPLE_FLAG;
115
567
    } else if (!strcmp(out, "ENDHDR")) {
116
2
      break;
117
565
    } else {
118
565
      static const char kEllipsis[] = " ...";
119
565
      const size_t kLen = strlen(kEllipsis) + 1;  // +1 = trailing \0
120
565
      int i;
121
565
      if (out_size > 20) snprintf(out + 20 - kLen, kLen, kEllipsis);
122
5.65k
      for (i = 0; i < (int)strlen(out); ++i) {
123
        // isprint() might trigger a "char-subscripts" warning if given a char.
124
5.09k
        if (!isprint((int)out[i])) out[i] = ' ';
125
5.09k
      }
126
565
      fprintf(stderr, "PAM header error: unrecognized entry [%s]\n", out);
127
565
      return 0;
128
565
    }
129
571
  }
130
2
  if (!(info->seen_flags & ALL_NEEDED_FLAGS)) {
131
2
    fprintf(stderr, "PAM header error: missing tags%s%s%s%s\n",
132
2
            (info->seen_flags & WIDTH_FLAG) ? "" : " WIDTH",
133
2
            (info->seen_flags & HEIGHT_FLAG) ? "" : " HEIGHT",
134
2
            (info->seen_flags & DEPTH_FLAG) ? "" : " DEPTH",
135
2
            (info->seen_flags & MAXVAL_FLAG) ? "" : " MAXVAL");
136
2
    return 0;
137
2
  }
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
7.88k
static size_t ReadHeader(PNMInfo* const info) {
147
7.88k
  size_t off = 0;
148
7.88k
  char out[MAX_LINE_SIZE + 1];
149
7.88k
  size_t out_size;
150
7.88k
  if (info == NULL) return 0;
151
7.88k
  if (info->data == NULL || info->data_size < kMinPNMHeaderSize) return 0;
152
153
7.88k
  info->width = info->height = 0;
154
7.88k
  info->type = -1;
155
7.88k
  info->seen_flags = 0;
156
7.88k
  info->bytes_per_px = 0;
157
7.88k
  info->depth = 0;
158
7.88k
  info->max_value = 0;
159
160
7.88k
  off = ReadLine(info->data, off, info->data_size, out, &out_size);
161
7.88k
  if (off == 0 || sscanf(out, "P%d", &info->type) != 1) return 0;
162
7.76k
  if (info->type == 7) {
163
567
    off = ReadPAMFields(info, off);
164
7.19k
  } else {
165
7.19k
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
166
7.19k
    if (off == 0 || sscanf(out, "%d %d", &info->width, &info->height) != 2) {
167
168
      return 0;
168
168
    }
169
7.02k
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
170
7.02k
    if (off == 0 || sscanf(out, "%d", &info->max_value) != 1) return 0;
171
172
    // finish initializing missing fields
173
6.94k
    info->depth = (info->type == 5) ? 1 : 3;
174
6.94k
  }
175
  // perform some basic numerical validation
176
7.51k
  if (info->width <= 0 || info->height <= 0 ||
177
7.51k
      info->type <= 0 || info->type >= 9 ||
178
7.51k
      info->depth <= 0 || info->depth > 4 ||
179
7.51k
      info->max_value <= 0 || info->max_value >= 65536) {
180
873
    return 0;
181
873
  }
182
6.63k
  info->bytes_per_px = info->depth * (info->max_value > 255 ? 2 : 1);
183
6.63k
  return off;
184
7.51k
}
185
186
int ReadPNM(const uint8_t* const data, size_t data_size,
187
            WebPPicture* const pic, int keep_alpha,
188
7.88k
            struct Metadata* const metadata) {
189
7.88k
  int ok = 0;
190
7.88k
  int i, j;
191
7.88k
  uint64_t stride, pixel_bytes, sample_size, depth;
192
7.88k
  uint8_t* rgb = NULL, *tmp_rgb;
193
7.88k
  size_t offset;
194
7.88k
  PNMInfo info;
195
196
7.88k
  info.data = data;
197
7.88k
  info.data_size = data_size;
198
7.88k
  offset = ReadHeader(&info);
199
7.88k
  if (offset == 0) {
200
1.24k
    fprintf(stderr, "Error parsing PNM header.\n");
201
1.24k
    goto End;
202
1.24k
  }
203
204
6.63k
  if (info.type < 5 || info.type > 7) {
205
9
    fprintf(stderr, "Unsupported P%d PNM format.\n", info.type);
206
9
    goto End;
207
9
  }
208
209
  // Some basic validations.
210
6.63k
  if (pic == NULL) goto End;
211
6.63k
  if (info.width > WEBP_MAX_DIMENSION || info.height > WEBP_MAX_DIMENSION) {
212
53
    fprintf(stderr, "Invalid %dx%d dimension for PNM\n",
213
53
                    info.width, info.height);
214
53
    goto End;
215
53
  }
216
217
6.57k
  pixel_bytes = (uint64_t)info.width * info.height * info.bytes_per_px;
218
6.57k
  if (data_size < offset + pixel_bytes) {
219
158
    fprintf(stderr, "Truncated PNM file (P%d).\n", info.type);
220
158
    goto End;
221
158
  }
222
6.41k
  sample_size = (info.max_value > 255) ? 2 : 1;
223
  // final depth
224
6.41k
  depth = (info.depth == 1 || info.depth == 3 || !keep_alpha) ? 3 : 4;
225
6.41k
  stride = depth * info.width;
226
6.41k
  if (stride != (size_t)stride ||
227
6.41k
      !ImgIoUtilCheckSizeArgumentsOverflow(stride, info.height)) {
228
0
    goto End;
229
0
  }
230
231
6.41k
  rgb = (uint8_t*)malloc((size_t)stride * info.height);
232
6.41k
  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
6.41k
  tmp_rgb = rgb;
237
361k
  for (j = 0; j < info.height; ++j) {
238
355k
    const uint8_t* in = data + offset;
239
355k
    offset += info.bytes_per_px * info.width;
240
355k
    assert(offset <= data_size);
241
355k
    if (info.max_value == 255 && info.depth >= 3) {
242
      // RGB or RGBA
243
3.34k
      if (info.depth == 3 || keep_alpha) {
244
3.34k
        memcpy(tmp_rgb, in, info.depth * info.width * sizeof(*in));
245
3.34k
      } 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
351k
    } 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
351k
      const uint32_t round = info.max_value / 2;
259
351k
      int k = 0;
260
1.17M
      for (i = 0; i < info.width * info.depth; ++i) {
261
826k
        uint32_t v = (sample_size == 2) ? 256u * in[2 * i + 0] + in[2 * i + 1]
262
826k
                   : in[i];
263
826k
        if (info.max_value != 255) v = (v * 255u + round) / info.max_value;
264
826k
        if (v > 255u) v = 255u;
265
826k
        if (info.depth > 2) {
266
71.1k
          if (!keep_alpha && info.depth == 4 && (i % 4) == 3) {
267
            // skip alpha
268
71.1k
          } else {
269
71.1k
            tmp_rgb[k] = v;
270
71.1k
            k += 1;
271
71.1k
          }
272
755k
        } else if (info.depth == 1 || (i % 2) == 0) {
273
755k
          tmp_rgb[k + 0] = tmp_rgb[k + 1] = tmp_rgb[k + 2] = v;
274
755k
          k += 3;
275
755k
        } 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
826k
      }
282
351k
    }
283
355k
    tmp_rgb += stride;
284
355k
  }
285
286
  // WebP conversion.
287
6.41k
  pic->width = info.width;
288
6.41k
  pic->height = info.height;
289
6.41k
  ok = (depth == 4) ? WebPPictureImportRGBA(pic, rgb, (int)stride)
290
6.41k
                    : WebPPictureImportRGB(pic, rgb, (int)stride);
291
6.41k
  if (!ok) goto End;
292
293
6.41k
  ok = 1;
294
7.88k
 End:
295
7.88k
  free((void*)rgb);
296
297
7.88k
  (void)metadata;
298
7.88k
  (void)keep_alpha;
299
7.88k
  return ok;
300
6.41k
}
301
302
// -----------------------------------------------------------------------------