Coverage Report

Created: 2026-01-10 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/imageio/pnmdec.c
Line
Count
Source
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
9.45M
#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
5.48k
                       char out[MAX_LINE_SIZE + 1], size_t* const out_size) {
56
5.48k
  size_t i = 0;
57
5.48k
  *out_size = 0;
58
15.9k
redo:
59
4.72M
  for (i = 0; i < MAX_LINE_SIZE && off < data_size; ++i) {
60
4.71M
    out[i] = data[off++];
61
4.71M
    if (out[i] == '\n') break;
62
4.71M
  }
63
15.9k
  if (off < data_size) {
64
14.1k
    if (i == 0) goto redo;         // empty line
65
8.94k
    if (out[0] == '#') goto redo;  // skip comment
66
8.94k
  }
67
5.48k
  out[i] = 0;  // safety sentinel
68
5.48k
  *out_size = i;
69
5.48k
  return off;
70
15.9k
}
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
597
static size_t ReadPAMFields(PNMInfo* const info, size_t off) {
79
597
  char out[MAX_LINE_SIZE + 1];
80
597
  size_t out_size;
81
597
  int tmp;
82
597
  int expected_depth = -1;
83
597
  assert(info != NULL);
84
603
  while (1) {
85
603
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
86
603
    if (off == 0) return 0;
87
603
    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
603
    } 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
603
    } 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
603
    } 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
603
    } else if (!strcmp(out, "TUPLTYPE RGB_ALPHA")) {
104
0
      expected_depth = 4;
105
0
      info->seen_flags |= TUPLE_FLAG;
106
603
    } else if (!strcmp(out, "TUPLTYPE RGB")) {
107
4
      expected_depth = 3;
108
4
      info->seen_flags |= TUPLE_FLAG;
109
599
    } else if (!strcmp(out, "TUPLTYPE GRAYSCALE_ALPHA")) {
110
0
      expected_depth = 2;
111
0
      info->seen_flags |= TUPLE_FLAG;
112
599
    } else if (!strcmp(out, "TUPLTYPE GRAYSCALE")) {
113
2
      expected_depth = 1;
114
2
      info->seen_flags |= TUPLE_FLAG;
115
597
    } else if (!strcmp(out, "ENDHDR")) {
116
2
      break;
117
595
    } else {
118
595
      static const char kEllipsis[] = " ...";
119
595
      const size_t kLen = strlen(kEllipsis) + 1;  // +1 = trailing \0
120
595
      int i;
121
595
      if (out_size > 20) snprintf(out + 20 - kLen, kLen, kEllipsis);
122
5.42k
      for (i = 0; i < (int)strlen(out); ++i) {
123
        // isprint() might trigger a "char-subscripts" warning if given a char.
124
4.82k
        if (!isprint((int)out[i])) out[i] = ' ';
125
4.82k
      }
126
595
      fprintf(stderr, "PAM header error: unrecognized entry [%s]\n", out);
127
595
      return 0;
128
595
    }
129
603
  }
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
2.27k
static size_t ReadHeader(PNMInfo* const info) {
147
2.27k
  size_t off = 0;
148
2.27k
  char out[MAX_LINE_SIZE + 1];
149
2.27k
  size_t out_size;
150
2.27k
  if (info == NULL) return 0;
151
2.27k
  if (info->data == NULL || info->data_size < kMinPNMHeaderSize) return 0;
152
153
2.26k
  info->width = info->height = 0;
154
2.26k
  info->type = -1;
155
2.26k
  info->seen_flags = 0;
156
2.26k
  info->bytes_per_px = 0;
157
2.26k
  info->depth = 0;
158
2.26k
  info->max_value = 0;
159
160
2.26k
  off = ReadLine(info->data, off, info->data_size, out, &out_size);
161
2.26k
  if (off == 0 || sscanf(out, "P%d", &info->type) != 1) return 0;
162
2.03k
  if (info->type == 7) {
163
597
    off = ReadPAMFields(info, off);
164
1.43k
  } else {
165
1.43k
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
166
1.43k
    if (off == 0 || sscanf(out, "%d %d", &info->width, &info->height) != 2) {
167
252
      return 0;
168
252
    }
169
1.18k
    off = ReadLine(info->data, off, info->data_size, out, &out_size);
170
1.18k
    if (off == 0 || sscanf(out, "%d", &info->max_value) != 1) return 0;
171
172
    // finish initializing missing fields
173
1.03k
    info->depth = (info->type == 5) ? 1 : 3;
174
1.03k
  }
175
  // perform some basic numerical validation
176
1.63k
  if (info->width <= 0 || info->height <= 0 || info->type <= 0 ||
177
798
      info->type >= 9 || info->depth <= 0 || info->depth > 4 ||
178
1.00k
      info->max_value <= 0 || info->max_value >= 65536) {
179
1.00k
    return 0;
180
1.00k
  }
181
632
  info->bytes_per_px = info->depth * (info->max_value > 255 ? 2 : 1);
182
632
  return off;
183
1.63k
}
184
185
int ReadPNM(const uint8_t* const data, size_t data_size, WebPPicture* const pic,
186
2.27k
            int keep_alpha, struct Metadata* const metadata) {
187
2.27k
  int ok = 0;
188
2.27k
  int i, j;
189
2.27k
  uint64_t stride, pixel_bytes, sample_size, depth;
190
2.27k
  uint8_t *rgb = NULL, *tmp_rgb;
191
2.27k
  size_t offset;
192
2.27k
  PNMInfo info;
193
194
2.27k
  info.data = data;
195
2.27k
  info.data_size = data_size;
196
2.27k
  offset = ReadHeader(&info);
197
2.27k
  if (offset == 0) {
198
1.64k
    fprintf(stderr, "Error parsing PNM header.\n");
199
1.64k
    goto End;
200
1.64k
  }
201
202
632
  if (info.type < 5 || info.type > 7) {
203
25
    fprintf(stderr, "Unsupported P%d PNM format.\n", info.type);
204
25
    goto End;
205
25
  }
206
207
  // Some basic validations.
208
607
  if (pic == NULL) goto End;
209
607
  if (info.width > WEBP_MAX_DIMENSION || info.height > WEBP_MAX_DIMENSION) {
210
33
    fprintf(stderr, "Invalid %dx%d dimension for PNM\n", info.width,
211
33
            info.height);
212
33
    goto End;
213
33
  }
214
215
574
  pixel_bytes = (uint64_t)info.width * info.height * info.bytes_per_px;
216
574
  if (data_size < offset + pixel_bytes) {
217
184
    fprintf(stderr, "Truncated PNM file (P%d).\n", info.type);
218
184
    goto End;
219
184
  }
220
390
  sample_size = (info.max_value > 255) ? 2 : 1;
221
  // final depth
222
390
  depth = (info.depth == 1 || info.depth == 3 || !keep_alpha) ? 3 : 4;
223
390
  stride = depth * info.width;
224
390
  if (stride != (size_t)stride ||
225
390
      !ImgIoUtilCheckSizeArgumentsOverflow(stride, info.height)) {
226
0
    goto End;
227
0
  }
228
229
390
  rgb = (uint8_t*)malloc((size_t)stride * info.height);
230
390
  if (rgb == NULL) goto End;
231
232
  // Convert input.
233
  // We only optimize for the sample_size=1, max_value=255, depth=1 case.
234
355
  tmp_rgb = rgb;
235
5.21k
  for (j = 0; j < info.height; ++j) {
236
4.85k
    const uint8_t* in = data + offset;
237
4.85k
    offset += info.bytes_per_px * info.width;
238
4.85k
    assert(offset <= data_size);
239
4.85k
    if (info.max_value == 255 && info.depth >= 3) {
240
      // RGB or RGBA
241
206
      if (info.depth == 3 || keep_alpha) {
242
206
        memcpy(tmp_rgb, in, info.depth * info.width * sizeof(*in));
243
206
      } else {
244
0
        assert(info.depth == 4 && !keep_alpha);
245
0
        for (i = 0; i < info.width; ++i) {
246
0
          tmp_rgb[3 * i + 0] = in[4 * i + 0];
247
0
          tmp_rgb[3 * i + 1] = in[4 * i + 1];
248
0
          tmp_rgb[3 * i + 2] = in[4 * i + 2];
249
0
        }
250
0
      }
251
4.65k
    } else {
252
      // Unoptimized case, we need to handle non-trivial operations:
253
      //   * convert 16b to 8b (if max_value > 255)
254
      //   * rescale to [0..255] range (if max_value != 255)
255
      //   * drop the alpha channel (if keep_alpha is false)
256
4.65k
      const uint32_t round = info.max_value / 2;
257
4.65k
      int k = 0;
258
56.5k
      for (i = 0; i < info.width * info.depth; ++i) {
259
51.9k
        uint32_t v =
260
51.9k
            (sample_size == 2) ? 256u * in[2 * i + 0] + in[2 * i + 1] : in[i];
261
51.9k
        if (info.max_value != 255) v = (v * 255u + round) / info.max_value;
262
51.9k
        if (v > 255u) v = 255u;
263
51.9k
        if (info.depth > 2) {
264
11.6k
          if (!keep_alpha && info.depth == 4 && (i % 4) == 3) {
265
            // skip alpha
266
11.6k
          } else {
267
11.6k
            tmp_rgb[k] = v;
268
11.6k
            k += 1;
269
11.6k
          }
270
40.2k
        } else if (info.depth == 1 || (i % 2) == 0) {
271
40.2k
          tmp_rgb[k + 0] = tmp_rgb[k + 1] = tmp_rgb[k + 2] = v;
272
40.2k
          k += 3;
273
40.2k
        } else if (keep_alpha && info.depth == 2) {
274
0
          tmp_rgb[k] = v;
275
0
          k += 1;
276
0
        } else {
277
          // skip alpha
278
0
        }
279
51.9k
      }
280
4.65k
    }
281
4.85k
    tmp_rgb += stride;
282
4.85k
  }
283
284
  // WebP conversion.
285
355
  pic->width = info.width;
286
355
  pic->height = info.height;
287
355
  ok = (depth == 4) ? WebPPictureImportRGBA(pic, rgb, (int)stride)
288
355
                    : WebPPictureImportRGB(pic, rgb, (int)stride);
289
355
  if (!ok) goto End;
290
291
315
  ok = 1;
292
2.27k
End:
293
2.27k
  free((void*)rgb);
294
295
2.27k
  (void)metadata;
296
2.27k
  (void)keep_alpha;
297
2.27k
  return ok;
298
315
}
299
300
// -----------------------------------------------------------------------------