Debian Codegraph @

converter/pbm/escp2topbm.c

raw
1 /* escp2topbm.c - read an Epson ESC/P2 printer file and
2 ** create a pbm file from the raster data,
3 ** ignoring all other data.
4 ** Can be regarded as a simple raster printer emulator
5 ** with a RLE run length decoder.
6 ** This program was made primarily for the test of pbmtoescp2
7 **
8 ** Copyright (C) 2003 by Ulrich Walcher ([email protected])
9 ** and Jef Poskanzer.
10 **
11 ** Permission to use, copy, modify, and distribute this software and its
12 ** documentation for any purpose and without fee is hereby granted, provided
13 ** that the above copyright notice appear in all copies and that both that
14 ** copyright notice and this permission notice appear in supporting
15 ** documentation. This software is provided "as is" without express or
16 ** implied warranty.
17
18 ** Major changes were made in July 2015 by Akira Urushibata.
19 ** Most notably the output functions were rewritten.
20 ** The -plain option is honored as in other programs.
21
22 * Implementation note (July 2015)
23 *
24 * The input file does not have a global header. Image data is divided
25 * into stripes (or data blocks). Each stripe has a header with
26 * local values for width, height, horizontal/vertical resolution
27 * and compression mode.
28 *
29 * We calculate the global height by adding up the local (stripe)
30 * height values, which may vary.
31 *
32 * The width value in the first stripe is used throughout; if any
33 * subsequent stripe reports a different value we abort.
34 *
35 * We ignore the resolution fields. Changes in compression mode
36 * are tolerated; they pose no problem.
37 *
38 * The official manual says resolution changes within an image are
39 * not allowed. It does not mention whether changes in stripe height or
40 * width values should be allowed.
41 *
42 * A different implementation approach would be to write temporary
43 * PBM files for each stripe and concatenate them at the final stage
44 * with a system call to "pnmcat -tb". This method has the advantage
45 * of being capable of handling variations in width.
46 */
47
48
49 #include <stdbool.h>
50 #include <assert.h>
51
52 #include "mallocvar.h"
53 #include "pbm.h"
54
55 static unsigned int widthMax = 127 * 256 + 255;
56 /* Limit in official Epson manual */
57
58 static unsigned int const heightMax = 5120 * 200;
59 /* 5120 rows is sufficient for US legal at 360 DPI */
60
61 #define ESC 033
62
63
64
65 static int
66 huntEsc(FILE * const ifP) {
67 /*-----------------------------------------------------------------------------
68 Hunt for valid start of image stripe in input.
69
70 Return values:
71 ESC: start of image stripe (data block)
72 EOF: end of file
73 0: any other char or sequence
74 -----------------------------------------------------------------------------*/
75 int const ch1 = getc(ifP);
76
77 switch (ch1) {
78 case EOF: return EOF;
79 case ESC: {
80 int const ch2 = getc(ifP);
81
82 switch (ch2) {
83 case EOF: return EOF;
84 case '.': return ESC;
85 default: return 0;
86 }
87 } break;
88 default: return 0;
89 }
90 }
91
92
93
94 static unsigned char
95 readChar(FILE * const ifP) {
96
97 int const ch = getc(ifP);
98
99 if (ch == EOF)
100 pm_error("EOF encountered while reading image data.");
101
102 return (unsigned char) ch;
103 }
104
105
106
107 static void
108 readStripeHeader(unsigned int * const widthThisStripeP,
109 unsigned int * const rowsThisStripeP,
110 unsigned int * const compressionP,
111 FILE * const ifP) {
112
113 unsigned char stripeHeader[6];
114 unsigned int widthThisStripe, rowsThisStripe;
115 unsigned int compression;
116
117 if (fread(stripeHeader, sizeof(stripeHeader), 1, ifP) != 1)
118 pm_error("Error reading image data.");
119
120 compression = stripeHeader[0];
121 /* verticalResolution = stripeHeader[1]; */
122 /* horizontalResolution = stripeHeader[2]; */
123 rowsThisStripe = stripeHeader[3];
124 widthThisStripe = stripeHeader[5] * 256 + stripeHeader[4];
125
126 if (widthThisStripe == 0 || rowsThisStripe == 0)
127 pm_error("Error: Abnormal value in data block header: "
128 "Says stripe has zero width or height");
129
130 if (widthThisStripe > widthMax)
131 pm_error("Error: Abnormal width value in data block header: %u",
132 widthThisStripe);
133
134 if (compression != 0 && compression != 1)
135 pm_error("Error: Unknown compression mode %u", compression);
136
137 *widthThisStripeP = widthThisStripe;
138 *rowsThisStripeP = rowsThisStripe;
139 *compressionP = compression;
140 }
141
142
143
144 /* RLE decoder */
145 static void
146 decEpsonRLE(unsigned int const blockSize,
147 unsigned char * const outBuffer,
148 FILE * const ifP) {
149
150 unsigned int dpos;
151
152 for (dpos = 0; dpos < blockSize; ) {
153 unsigned char const flag = readChar(ifP);
154
155 if (flag < 128) {
156 /* copy through */
157
158 unsigned int const nonrunLength = flag + 1;
159
160 unsigned int i;
161
162 for (i = 0; i < nonrunLength; ++i)
163 outBuffer[dpos+i] = readChar(ifP);
164
165 dpos += nonrunLength;
166 } else if (flag == 128) {
167 pm_message("Code 128 detected in compressed input data: ignored");
168 } else {
169 /* inflate this run */
170
171 unsigned int const runLength = 257 - flag;
172 unsigned char const repeatChar = readChar( ifP );
173
174 unsigned int i;
175
176 for (i = 0; i < runLength; ++i)
177 outBuffer[dpos + i] = repeatChar;
178 dpos += runLength;
179 }
180 }
181 if (dpos != blockSize)
182 pm_error("Corruption detected in compressed input data");
183 }
184
185
186
187 static void
188 processStripeRaster(unsigned char ** const bitarray,
189 unsigned int const rowsThisStripe,
190 unsigned int const width,
191 unsigned int const compression,
192 FILE * const ifP,
193 unsigned int * const rowIdxP) {
194
195 unsigned int const initialRowIdx = *rowIdxP;
196 unsigned int const widthInBytes = pbm_packed_bytes(width);
197 unsigned int const blockSize = rowsThisStripe * widthInBytes;
198 unsigned int const margin = compression==1 ? 256 : 0;
199
200 unsigned char * imageBuffer;
201 unsigned int i;
202 unsigned int rowIdx;
203
204 /* We allocate a new buffer each time this function is called. Add some
205 margin to the buffer for compressed mode to cope with overruns caused
206 by corrupt input data.
207 */
208
209 MALLOCARRAY(imageBuffer, blockSize + margin);
210
211 if (imageBuffer == NULL)
212 pm_error("Failed to allocate buffer for a block of size %u",
213 blockSize);
214
215 if (compression == 0) {
216 if (fread(imageBuffer, blockSize, 1, ifP) != 1)
217 pm_error("Error reading image data");
218 } else /* compression == 1 */
219 decEpsonRLE(blockSize, imageBuffer, ifP);
220
221 /* Hand over image data to output by pointer assignment */
222 for (i = 0, rowIdx = initialRowIdx; i < rowsThisStripe; ++i)
223 bitarray[rowIdx++] = &imageBuffer[i * widthInBytes];
224
225 *rowIdxP = rowIdx;
226 }
227
228
229
230 static void
231 expandBitarray(unsigned char *** const bitarrayP,
232 unsigned int * const bitarraySizeP) {
233
234 unsigned int const heightIncrement = 5120;
235
236 *bitarraySizeP += heightIncrement;
237 if (*bitarraySizeP > heightMax)
238 pm_error("Error: Image too tall");
239 else
240 REALLOCARRAY_NOFAIL(*bitarrayP, *bitarraySizeP);
241 }
242
243
244
245 static void
246 writePbmImage(unsigned char ** const bitarray,
247 unsigned int const width,
248 unsigned int const height) {
249
250 unsigned int row;
251
252 if (height == 0)
253 pm_error("No image");
254
255 pbm_writepbminit(stdout, width, height, 0);
256
257 for (row = 0; row < height; ++row) {
258 pbm_cleanrowend_packed(bitarray[row], width);
259 pbm_writepbmrow_packed(stdout, bitarray[row], width, 0);
260 }
261 }
262
263
264
265 int
266 main(int argc,
267 const char * argv[]) {
268
269 FILE * ifP;
270 unsigned int width;
271 /* Width of the image, or zero to mean width is not yet known.
272 (We get the width from the first stripe in the input; until
273 we've seen that stripe, we don't know the width)
274 */
275 unsigned int height;
276 /* Height of the image as seen so far. (We process a stripe at a
277 time, increasing this value as we go).
278 */
279 unsigned int rowIdx;
280 unsigned char ** bitarray;
281 unsigned int bitarraySize;
282 const char * fileName;
283 bool eof;
284
285 pm_proginit(&argc, argv);
286
287 if (argc-1 > 1)
288 pm_error("Too many arguments (%u). Only argument is filename.",
289 argc-1);
290
291 if (argc == 2)
292 fileName = argv[1];
293 else
294 fileName = "-";
295
296 ifP = pm_openr(fileName);
297
298 /* Initialize bitarray */
299 bitarray = NULL; bitarraySize = 0;
300 expandBitarray(&bitarray, &bitarraySize);
301
302 for (eof = false, width = 0, height = 0, rowIdx = 0; !eof; ) {
303 int const r = huntEsc(ifP);
304
305 if (r == EOF)
306 eof = true;
307 else {
308 if (r == ESC) {
309 unsigned int compression;
310 unsigned int rowsThisStripe;
311 unsigned int widthThisStripe;
312
313 readStripeHeader(&widthThisStripe, &rowsThisStripe,
314 &compression, ifP);
315
316 if (rowsThisStripe == 0)
317 pm_error("Abnormal data block height value: 0");
318 else if (rowsThisStripe != 24 && rowsThisStripe != 8 &&
319 rowsThisStripe != 1) {
320 /* The official Epson manual says valid values are 1, 8,
321 24 but we just print a warning message and continue if
322 other values are detected.
323 */
324 pm_message("Abnormal data block height value: %u "
325 "(ignoring)",
326 rowsThisStripe);
327 }
328 if (width == 0) {
329 /* Get width from 1st stripe header */
330 width = widthThisStripe;
331 } else if (width != widthThisStripe) {
332 /* width change not allowed */
333 pm_error("Error: Width changed in middle of image "
334 "from %u to %u",
335 width, widthThisStripe);
336 }
337 height += rowsThisStripe;
338 assert(height <= INT_MAX - 10);
339 /* Becuse image height is tested in expandBitarray()
340 with a more stringent condition.
341 */
342 if (height > bitarraySize)
343 expandBitarray(&bitarray, &bitarraySize);
344
345 processStripeRaster(bitarray, rowsThisStripe, width,
346 compression, ifP, &rowIdx);
347 } else {
348 /* r != ESC; do nothing */
349 }
350 }
351 }
352
353 writePbmImage(bitarray, width, height);
354
355 fclose(stdout);
356 fclose(ifP);
357
358 return 0;
359 }
360
361
362