Debian Codegraph @

editor/pamflip/pamflip.c

raw
1 /* pamflip.c - perform one or more flip operations on a Netpbm image
2 **
3 ** Copyright (C) 1989 by Jef Poskanzer.
4 **
5 ** Permission to use, copy, modify, and distribute this software and its
6 ** documentation for any purpose and without fee is hereby granted, provided
7 ** that the above copyright notice appear in all copies and that both that
8 ** copyright notice and this permission notice appear in supporting
9 ** documentation. This software is provided "as is" without express or
10 ** implied warranty.
11 */
12
13 /*
14 transformNonPbmChunk() is the general transformation function.
15 It can transform anything, albeit slowly and expensively.
16
17 The following are enhancements for specific cases:
18
19 transformRowByRowPbm():
20 PBM image with left-right or null transformation
21 transformRowsBottomTopPbm()
22 PBM image with bottom-top transformation
23 transformRowByRowNonPbm()
24 non-PBM image with left-right or null transformation
25 (also works for PBM, but we don't use it)
26 transformRowsBottomTopNonPbm()
27 non-PBM image with bottom-top transformation
28 (also works for PBM, but we don't use it)
29 transformRowsToColumnsPbmSse()
30 PBM image with column-for-row transformation
31 requires Intel/AMD x86 SSE2
32 (can only do 90 degree/xy flips)
33 transformPbm()
34 PBM image with column-for-row transformation
35 (also works for all other transformations, but we don't use it)
36 transformNonPbmWhole()
37 non-PBM column-for-row transformation
38 (also works for PBM, but we don't use it)
39
40 Except we don't use any of the above if we can't fit the entire image
41 into the amount of memory the user gave us to work with. In that
42 case, we fall back to transformNonPbmChunk().
43
44 Note that while virtual memory can be limited (e.g. sometimes the
45 machine's 32 bit address space itself is a limit), real memory is
46 also a concern. With a row-for-column transformation
47 (e.g. -transpose), if we can't fit the entire image into _real_
48 memory, we will page thrash within an inch our lives. So we count
49 on the user to tell us how much real memory we should expect to
50 get -- his -memsize option is the lesser of the available virtual
51 and real memory.
52
53 Before Netpbm 10.42 (March 2008), we had a different method for
54 dealing with memory shortage. We didn't worry about virtual memory
55 at all, and always kept the whole target image in memory. We did
56 not use temporary files. But to avoid page thrashing in a
57 column-for-row transformation, we transformed in column stripes of
58 the source image, reading the input image through multiple times.
59 */
60
61 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
62 #define _BSD_SOURCE 1 /* Make sure strdup() is in string.h */
63 #define _XOPEN_SOURCE 500 /* Make sure strdup() is in string.h */
64
65 #include <assert.h>
66 #include <limits.h>
67 #include <string.h>
68
69 #include "pm_c_util.h"
70 #include "pam.h"
71 #include "shhopt.h"
72 #include "mallocvar.h"
73 #include "nstring.h"
74 #include "bitreverse.h"
75
76 #include "config.h" /* Defines SSE_PBM_XY_FLIP */
77 #include "flip.h"
78 #include "pamflip_sse.h"
79
80 enum XformType {LEFTRIGHT, TOPBOTTOM, TRANSPOSE};
81
82 static void
83 parseXformOpt(const char * const xformOpt,
84 unsigned int * const xformCountP,
85 enum XformType * const xformList) {
86 /*----------------------------------------------------------------------------
87 Translate the -xform option string into an array of transform types.
88
89 Return the array as xformList[], which is preallocated for at least
90 10 elements.
91 -----------------------------------------------------------------------------*/
92 unsigned int xformCount;
93 char * xformOptWork;
94 char * cursor;
95 bool eol;
96
97 xformOptWork = strdup(xformOpt);
98 cursor = &xformOptWork[0];
99
100 eol = FALSE; /* initial value */
101 xformCount = 0; /* initial value */
102 while (!eol && xformCount < 10) {
103 const char * token;
104 token = pm_strsep(&cursor, ",");
105 if (token) {
106 if (streq(token, "leftright"))
107 xformList[xformCount++] = LEFTRIGHT;
108 else if (streq(token, "topbottom"))
109 xformList[xformCount++] = TOPBOTTOM;
110 else if (streq(token, "transpose"))
111 xformList[xformCount++] = TRANSPOSE;
112 else if (streq(token, ""))
113 { /* ignore it */}
114 else
115 pm_error("Invalid transform type in -xform option: '%s'. "
116 "We recognize only 'leftright', 'topbottom', and "
117 "transpose",
118 token );
119 } else
120 eol = TRUE;
121 }
122 free(xformOptWork);
123
124 *xformCountP = xformCount;
125 }
126
127
128
129 /* See transformPoint() for an explanation of the transform matrix types. The
130 difference between XformCore and XformMatrix is that 'XformMatrix' is
131 particular to the source image dimensions and can be used to do the
132 transformation, while 'XformCore' is independent of the source image and
133 just tells what kind of transformation.
134 */
135
136 struct XformMatrix {
137 /* a b 0
138 c d 0
139 e f 1
140 */
141 int a; /* -1, 0, or 1 */
142 int b; /* -1, 0, or 1 */
143 int c; /* -1, 0, or 1 */
144 int d; /* -1, 0, or 1 */
145 int e; /* 0 or maximum column number in target image */
146 int f; /* 0 or maximum row number in target image */
147 };
148
149
150
151 static void
152 leftright(struct XformCore * const xformP) {
153 xformP->a = - xformP->a;
154 xformP->c = - xformP->c;
155 }
156
157
158
159 static void
160 topbottom(struct XformCore * const xformP) {
161 xformP->b = - xformP->b;
162 xformP->d = - xformP->d;
163 }
164
165
166
167 static void
168 swap(int * const xP, int * const yP) {
169
170 int const t = *xP;
171
172 *xP = *yP;
173 *yP = t;
174 }
175
176
177
178 static void
179 transpose(struct XformCore * const xformP) {
180 swap(&xformP->a, &xformP->b);
181 swap(&xformP->c, &xformP->d);
182 }
183
184
185
186 static void
187 invert(struct XformCore * const xformP) {
188 /*----------------------------------------------------------------------------
189 Invert the current transformation (e.g. turn a clockwise rotation into a
190 counterclockwise rotation).
191 -----------------------------------------------------------------------------*/
192 swap(&xformP->b, &xformP->c);
193 }
194
195
196
197 static void
198 computeXformCore(unsigned int const xformCount,
199 enum XformType const XformType[],
200 bool const wantInverse,
201 struct XformCore * const xformP) {
202 /*----------------------------------------------------------------------------
203 Determine the aggregate transformation that results from applying the list
204 of serial transformations xformType[] (of size 'xformCount'). Return that
205 in the form of an XformCore (a 2x2 matrix of -1, 0, and 1) as *xformP.
206
207 Iff 'wantinverse', return the inverse of the transformation described
208 above (the transformation that would undo that transformation).
209 -----------------------------------------------------------------------------*/
210 struct XformCore const nullTransform = {1, 0, 0, 1};
211
212 unsigned int i;
213
214 *xformP = nullTransform; /* initial value */
215
216 for (i = 0; i < xformCount; ++i) {
217 switch (XformType[i]) {
218 case LEFTRIGHT:
219 leftright(xformP);
220 break;
221 case TOPBOTTOM:
222 topbottom(xformP);
223 break;
224 case TRANSPOSE:
225 transpose(xformP);
226 break;
227 }
228 }
229 if (wantInverse)
230 invert(xformP);
231 }
232
233
234
235 static void
236 xformDimensions(struct XformCore const xform,
237 unsigned int const inCols,
238 unsigned int const inRows,
239 unsigned int * const outColsP,
240 unsigned int * const outRowsP) {
241 /*----------------------------------------------------------------------------
242 Compute the output dimensions from the input dimensions given a
243 matrix that describes a transformation.
244
245 E.g. if it's a 90 degree rotation of a 10 x 20 image, the output is
246 a 20 x 10 image.
247 -----------------------------------------------------------------------------*/
248 *outColsP = abs(xform.a * (int)inCols + xform.c * (int)inRows);
249 *outRowsP = abs(xform.b * (int)inCols + xform.d * (int)inRows);
250 }
251
252
253
254 static void
255 computeXformMatrix(struct XformMatrix * const xformP,
256 unsigned int const sourceCols,
257 unsigned int const sourceRows,
258 struct XformCore const xformCore) {
259
260 int const x = xformCore.a * (sourceCols-1) + xformCore.c * (sourceRows-1);
261 int const y = xformCore.b * (sourceCols-1) + xformCore.d * (sourceRows-1);
262
263 xformP->a = xformCore.a;
264 xformP->b = xformCore.b;
265 xformP->c = xformCore.c;
266 xformP->d = xformCore.d;
267 xformP->e = x < 0 ? -x : 0;
268 xformP->f = y < 0 ? -y : 0;
269 }
270
271
272
273 struct cmdlineInfo {
274 /* All the information the user supplied in the command line,
275 in a form easy for the program to use.
276 */
277 const char * inputFilespec; /* Filespec of input file */
278 struct XformCore xform;
279 /* Handy mathematical representation of all of transform options */
280 size_t availableMemory;
281 unsigned int pageSize;
282 unsigned int verbose;
283 };
284
285
286
287 static void
288 interpretMemorySize(unsigned int const memsizeSpec,
289 unsigned int const memsizeOpt,
290 size_t * const availableMemoryP) {
291
292 size_t const sizeMax = (size_t)(-1);
293 unsigned int const Meg = 1024 * 1024;
294
295 if (memsizeSpec) {
296 if (memsizeOpt == 0)
297 pm_error("-memsize value must be positive");
298 else if (memsizeOpt > sizeMax / Meg)
299 pm_error("-memsize value too large: %u MiB. Maximum this program "
300 "can handle is %u MiB",
301 memsizeOpt, (unsigned)sizeMax / Meg);
302 *availableMemoryP = memsizeOpt * Meg;
303 } else
304 *availableMemoryP = sizeMax;
305 }
306
307
308
309 static void
310 parseCommandLine(int argc, char ** const argv,
311 struct cmdlineInfo * const cmdlineP) {
312 /*----------------------------------------------------------------------------
313 Note that the file spec array we return is stored in the storage that
314 was passed to us as the argv array.
315 -----------------------------------------------------------------------------*/
316 optEntry * option_def;
317 /* Instructions to OptParseOptions3 on how to parse our options.
318 */
319 optStruct3 opt;
320
321 unsigned int option_def_index;
322
323 unsigned int lr, tb, xy, reflect, r90, r270, r180, null, inverse;
324 unsigned int memsizeSpec, pagesizeSpec, xformSpec;
325 unsigned int memsizeOpt;
326 const char * xformOpt;
327 unsigned int xformCount;
328 /* Number of transforms in the 'XformType' array */
329 enum XformType xformList[10];
330 /* Array of transforms to be applied, in order */
331
332 MALLOCARRAY(option_def, 100);
333
334 option_def_index = 0; /* incremented by OPTENTRY */
335 OPTENT3(0, "lr", OPT_FLAG, NULL, &lr, 0);
336 OPTENT3(0, "leftright", OPT_FLAG, NULL, &lr, 0);
337 OPTENT3(0, "tb", OPT_FLAG, NULL, &tb, 0);
338 OPTENT3(0, "topbottom", OPT_FLAG, NULL, &tb, 0);
339 OPTENT3(0, "xy", OPT_FLAG, NULL, &xy, 0);
340 OPTENT3(0, "transpose", OPT_FLAG, NULL, &xy, 0);
341 OPTENT3(0, "reflect", OPT_FLAG, NULL, &reflect, 0);
342 OPTENT3(0, "r90", OPT_FLAG, NULL, &r90, 0);
343 OPTENT3(0, "rotate90", OPT_FLAG, NULL, &r90, 0);
344 OPTENT3(0, "ccw", OPT_FLAG, NULL, &r90, 0);
345 OPTENT3(0, "r180", OPT_FLAG, NULL, &r180, 0);
346 OPTENT3(0, "rotate180", OPT_FLAG, NULL, &r180, 0);
347 OPTENT3(0, "r270", OPT_FLAG, NULL, &r270, 0);
348 OPTENT3(0, "rotate270", OPT_FLAG, NULL, &r270, 0);
349 OPTENT3(0, "cw", OPT_FLAG, NULL, &r270, 0);
350 OPTENT3(0, "null", OPT_FLAG, NULL, &null, 0);
351 OPTENT3(0, "inverse", OPT_FLAG, NULL, &inverse, 0);
352 OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0);
353 OPTENT3(0, "memsize", OPT_UINT, &memsizeOpt,
354 &memsizeSpec, 0);
355 OPTENT3(0, "pagesize", OPT_UINT, &cmdlineP->pageSize,
356 &pagesizeSpec, 0);
357 OPTENT3(0, "xform", OPT_STRING, &xformOpt,
358 &xformSpec, 0);
359
360 opt.opt_table = option_def;
361 opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
362 opt.allowNegNum = FALSE; /* We don't parms that are negative numbers */
363
364 pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
365 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
366
367 if (lr + tb + xy + reflect + r90 + r180 + r270 + null + xformSpec > 1)
368 pm_error("You may specify only one type of flip.");
369 if (lr + tb + xy + reflect + r90 + r180 + r270 + null == 1) {
370 if (lr) {
371 xformCount = 1;
372 xformList[0] = LEFTRIGHT;
373 } else if (tb) {
374 xformCount = 1;
375 xformList[0] = TOPBOTTOM;
376 } else if (xy) {
377 xformCount = 1;
378 xformList[0] = TRANSPOSE;
379 } else if (reflect) {
380 xformCount = 3;
381 xformList[0] = TRANSPOSE;
382 xformList[1] = LEFTRIGHT;
383 xformList[2] = TOPBOTTOM;
384 } else if (r90) {
385 xformCount = 2;
386 xformList[0] = TRANSPOSE;
387 xformList[1] = TOPBOTTOM;
388 } else if (r180) {
389 xformCount = 2;
390 xformList[0] = LEFTRIGHT;
391 xformList[1] = TOPBOTTOM;
392 } else if (r270) {
393 xformCount = 2;
394 xformList[0] = TRANSPOSE;
395 xformList[1] = LEFTRIGHT;
396 } else if (null) {
397 xformCount = 0;
398 }
399 } else if (xformSpec)
400 parseXformOpt(xformOpt, &xformCount, xformList);
401 else
402 pm_error("You must specify an option such as -topbottom to indicate "
403 "what kind of flip you want.");
404
405 computeXformCore(xformCount, xformList, inverse, &cmdlineP->xform);
406
407 interpretMemorySize(memsizeSpec, memsizeOpt, &cmdlineP->availableMemory);
408
409 if (!pagesizeSpec)
410 cmdlineP->pageSize = 4*1024;
411
412 if (pagesizeSpec && cmdlineP->verbose)
413 pm_message("-pagesize value has no effect.");
414
415 if (argc-1 == 0)
416 cmdlineP->inputFilespec = "-";
417 else if (argc-1 != 1)
418 pm_error("Program takes zero or one argument (filename). You "
419 "specified %d", argc-1);
420 else
421 cmdlineP->inputFilespec = argv[1];
422
423 free(option_def);
424 }
425
426
427
428 static void
429 bitOrderReverse(unsigned char * const bitrow,
430 unsigned int const cols) {
431 /*----------------------------------------------------------------------------
432 Reverse the bits in a packed pbm row (1 bit per pixel). I.e. the leftmost
433 bit becomes the rightmost, etc.
434
435 Exchange pixels in units of eight. If both are zero, skip instead of
436 exchanging zeros.
437 -----------------------------------------------------------------------------*/
438 unsigned int const lastfullByteIdx = cols/8 - 1;
439
440 if (cols == 0 || bitrow == NULL )
441 pm_error("Invalid arguments passed to bitOrderReverse");
442
443 if (cols <= 8)
444 bitrow[0] = bitreverse[bitrow[0]] << (8-cols);
445 else if (cols % 8 == 0) {
446 unsigned int i, j;
447 for (i = 0, j = lastfullByteIdx; i <= j; ++i, --j)
448 if ((bitrow[j] | bitrow[i]) == 0) {
449 /* Both are 0x00 - skip */
450 } else {
451 unsigned char const t = bitreverse[bitrow[j]];
452 bitrow[j] = bitreverse[bitrow[i]];
453 bitrow[i] = t;
454 }
455 } else {
456 unsigned int const m = cols % 8;
457
458 unsigned int i, j;
459 /* Cursors into bitrow[]. i moves from left to center;
460 j moves from right to center as bits of bitrow[] are exchanged.
461 */
462 unsigned char th, tl; /* 16 bit temp ( th << 8 | tl ) */
463 tl = 0;
464 for (i = 0, j = lastfullByteIdx+1; i <= lastfullByteIdx/2; ++i, --j) {
465 if( (tl | bitrow[i] | bitrow[j] | bitrow[j-1]) != 0) {
466 /* Skip if both are 0x00 */
467 th = bitreverse[bitrow[i]];
468 bitrow[i] =
469 bitreverse[0xff & ((bitrow[j-1] << 8
470 | bitrow[j]) >> (8-m))];
471 bitrow[j] = 0xff & ((th << 8 | tl) >> m);
472 tl = th;
473 }
474 }
475 if (i == j && (bitrow[i] | tl) != 0) {
476 /* bitrow[] has an odd number of bytes (an even number of
477 full bytes; lastfullByteIdx is odd), so we did all but
478 the center byte above. We do the center byte now.
479 */
480 bitrow[j] = 0xff & ((bitreverse[bitrow[i]] << 8 | tl) >> m);
481 }
482 }
483 }
484
485
486
487 static void
488 transformRowByRowPbm(struct pam * const inpamP,
489 struct pam * const outpamP,
490 bool const reverse) {
491 /*----------------------------------------------------------------------------
492 Transform a PBM raster either by flipping it left for right, or just
493 leaving it alone, as indicated by 'reverse'. Read the raster from
494 *inpamP; write the transformed raster to *outpamP.
495
496 Process the image one row at a time and use fast packed PBM bit
497 reverse algorithm (where required).
498 -----------------------------------------------------------------------------*/
499 unsigned char * bitrow;
500 unsigned int row;
501
502 bitrow = pbm_allocrow_packed(outpamP->width);
503
504 for (row = 0; row < inpamP->height; ++row) {
505 pbm_readpbmrow_packed(inpamP->file, bitrow, inpamP->width,
506 inpamP->format);
507
508 if (reverse)
509 bitOrderReverse(bitrow, inpamP->width);
510
511 pbm_writepbmrow_packed(outpamP->file, bitrow, outpamP->width, 0);
512 }
513 pbm_freerow_packed(bitrow);
514 }
515
516
517
518 static void
519 transformRowByRowNonPbm(struct pam * const inpamP,
520 struct pam * const outpamP,
521 bool const reverse) {
522 /*----------------------------------------------------------------------------
523 Flip a raster left for right or leave it alone. Read the raster
524 from *inpamP; write the transformed raster to *outpamP.
525
526 Process one row at a time.
527
528 This works on any image, but is slower and uses more memory than the
529 PBM-only transformRowByRowPbm().
530 -----------------------------------------------------------------------------*/
531 tuple * tuplerow;
532 tuple * newtuplerow;
533 /* This is not a full tuple row. It is either an array of pointers
534 to the tuples in 'tuplerow' (in reverse order) or just 'tuplerow'
535 itself.
536 */
537 tuple * scratchTuplerow;
538
539 unsigned int row;
540
541 tuplerow = pnm_allocpamrow(inpamP);
542
543 if (reverse) {
544 /* Set up newtuplerow[] to point to the tuples of tuplerow[] in
545 reverse order.
546 */
547 unsigned int col;
548
549 MALLOCARRAY_NOFAIL(scratchTuplerow, inpamP->width);
550
551 for (col = 0; col < inpamP->width; ++col)
552 scratchTuplerow[col] = tuplerow[inpamP->width - col - 1];
553 newtuplerow = scratchTuplerow;
554 } else {
555 scratchTuplerow = NULL;
556 newtuplerow = tuplerow;
557 }
558 for (row = 0; row < inpamP->height ; ++row) {
559 pnm_readpamrow(inpamP, tuplerow);
560 pnm_writepamrow(outpamP, newtuplerow);
561 }
562
563 if (scratchTuplerow)
564 free(scratchTuplerow);
565 pnm_freepamrow(tuplerow);
566 }
567
568
569
570 static void
571 transformRowsBottomTopPbm(struct pam * const inpamP,
572 struct pam * const outpamP,
573 bool const reverse) {
574 /*----------------------------------------------------------------------------
575 Flip a PBM raster top for bottom; read the raster from *inpamP;
576 write the flipped raster to *outpamP.
577
578 Read complete image into memory in packed PBM format; Use fast
579 packed PBM bit reverse algorithm (where required).
580 -----------------------------------------------------------------------------*/
581 unsigned int const rows=inpamP->height;
582
583 unsigned char ** bitrow;
584 unsigned int row;
585
586 bitrow = pbm_allocarray_packed(outpamP->width, outpamP->height);
587
588 for (row = 0; row < rows; ++row)
589 pbm_readpbmrow_packed(inpamP->file, bitrow[row],
590 inpamP->width, inpamP->format);
591
592 for (row = 0; row < rows; ++row) {
593 if (reverse)
594 bitOrderReverse(bitrow[rows-row-1], inpamP->width);
595
596 pbm_writepbmrow_packed(outpamP->file, bitrow[rows - row - 1],
597 outpamP->width, 0);
598 }
599 pbm_freearray_packed(bitrow, outpamP->height);
600 }
601
602
603
604 static void
605 transformRowsBottomTopNonPbm(struct pam * const inpamP,
606 struct pam * const outpamP) {
607 /*----------------------------------------------------------------------------
608 Do a simple vertical flip. Read the raster from *inpamP; write the
609 flipped raster to *outpamP.
610
611 We do this faster than the more general subroutines because we just
612 move the row pointers.
613
614 But we must fit the entire image into memory at once.
615
616 This works on PBM, but the PBM-specific subroutine is faster.
617 -----------------------------------------------------------------------------*/
618 tuple ** tuplerows;
619 unsigned int row;
620
621 tuplerows = pnm_allocpamarray(outpamP);
622
623 for (row = 0; row < inpamP->height ; ++row)
624 pnm_readpamrow(inpamP, tuplerows[row]);
625
626 for (row = 0; row < inpamP->height; ++row) {
627 tuple * const tuplerow = tuplerows[inpamP->height - row - 1];
628
629 pnm_writepamrow(outpamP, tuplerow);
630 }
631
632 pnm_freepamarray(tuplerows, outpamP);
633 }
634
635
636
637 static void __inline__
638 transformPoint(int const col,
639 int const row,
640 struct XformMatrix const xform,
641 unsigned int * const newcolP,
642 unsigned int * const newrowP ) {
643 /*----------------------------------------------------------------------------
644 Compute the location in the output of a pixel that is at row 'row',
645 column 'col' in the input. Assume the output image is 'newcols' by
646 'newrows' and the transformation is as described by 'xform'.
647
648 Return the output image location of the pixel as *newcolP and *newrowP.
649 -----------------------------------------------------------------------------*/
650 /* The transformation is:
651
652 [ a b 0 ]
653 [ x y 1 ] [ c d 0 ] = [ x2 y2 1 ]
654 [ e f 1 ]
655
656 where (x, y) is the source pixel location and (x2, y2) is the target
657 pixel location. The 3x3 matrix is the transform matrix 'xform'.
658
659 'a', 'b', 'c', and 'd' are 0, 1, or -1. 'e' and 'f' are the height and
660 width of the image or 0. The target row number is, depending on the
661 flip, the source row number, the source column number, the image height
662 minus the source row number, or the image width minus the source column
663 number. The target column number is similar.
664
665 An easy way to break down the operation of the transform matrix is as
666 follows: The upper left square of the transform matrix is the transform
667 core matrix (type XformCore). The simpler computation
668
669 [ x y ] [ a b ] = [ x2 y2 ]
670 [ c d ]
671
672 effects the desired flip, but in a larger 4-quadrant space with
673 negative column and row numbers. Flipping a 10-row image top-bottom,
674 for example, gives you a properly upside down image, but the row
675 numbers are 0 through -9 (imagine an image in the first Cartesian
676 quadrant flipping about the x axis). To get this back into the
677 positive row number space, you have to translate it up 10 rows.
678
679 The additional 'e' and 'f' elements therefore add the height or
680 width to negative row and column numbers.
681
682 This is an affine transformation. See
683 http://leptonica.org/affine.html .
684 */
685 *newcolP = xform.a * col + xform.c * row + xform.e * 1;
686 *newrowP = xform.b * col + xform.d * row + xform.f * 1;
687
688 assert(*newcolP >= 0);
689 assert(*newrowP >= 0);
690 }
691
692
693
694 static void
695 writeRaster(struct pam * const pamP,
696 tuple * const * const tuples) {
697
698 unsigned int outRow;
699
700 for (outRow = 0; outRow < pamP->height; ++ outRow)
701 pnm_writepamrow(pamP, tuples[outRow]);
702 }
703
704
705
706 static void
707 transformPbmGen(struct pam * const inpamP,
708 struct pam * const outpamP,
709 struct XformCore const xformCore) {
710 /*----------------------------------------------------------------------------
711 This is the same as transformGen, except that it uses less
712 memory, since the PBM buffer format uses one bit per pixel instead
713 of twelve bytes + pointer space
714
715 This can do any PBM transformation, but is slower and uses more
716 memory than the more restricted transformRowByRowPbm() and
717 transformRowsBottomTopPbm().
718 -----------------------------------------------------------------------------*/
719 bit * bitrow;
720 bit ** newbits;
721 struct XformMatrix xform;
722 unsigned int row;
723
724 computeXformMatrix(&xform, inpamP->width, inpamP->height, xformCore);
725
726 bitrow = pbm_allocrow_packed(inpamP->width);
727 newbits = pbm_allocarray_packed( outpamP->width, outpamP->height );
728
729 /* Initialize entire array to zeroes. One bits will be or'ed in later */
730 for (row = 0; row < outpamP->height; ++row) {
731 unsigned int col;
732 for (col = 0; col < pbm_packed_bytes(outpamP->width); ++col)
733 newbits[row][col] = 0;
734 }
735
736 for (row = 0; row < inpamP->height; ++row) {
737 unsigned int col;
738
739 pbm_readpbmrow_packed(inpamP->file, bitrow,
740 inpamP->width, inpamP->format);
741 for (col = 0; col < inpamP->width; ) {
742 if (bitrow[col/8] == 0x00)
743 col += 8; /* Blank. Skip to next byte. */
744 else { /* Examine each pixel. */
745 unsigned int const colLimit = MIN(col+8, inpamP->width);
746 unsigned int i;
747
748 for (i = 0; col < colLimit; ++i, ++col) {
749 bool const bitIsOne = (bitrow[col/8] >> (7-i)) & 0x01;
750 if (bitIsOne) {
751 /* Write in only the one bits. */
752 unsigned int newcol, newrow;
753 transformPoint(col, row, xform, &newcol, &newrow);
754 newbits[newrow][newcol/8] |= 0x01 << (7 - newcol % 8);
755 /* Use of "|=" patterned after
756 pbm_readpbmrow_packed().
757 */
758 }
759 }
760 }
761 }
762 }
763
764 for (row = 0; row < outpamP->height; ++row)
765 pbm_writepbmrow_packed(outpamP->file, newbits[row], outpamP->width, 0);
766
767 pbm_freearray(newbits, outpamP->height);
768 pbm_freerow(bitrow);
769 }
770
771
772
773 static void
774 transformNonPbmWhole(struct pam * const inpamP,
775 struct pam * const outpamP,
776 struct XformCore const xformCore,
777 bool const verbose) {
778 /*----------------------------------------------------------------------------
779 Do the transform using "pam" library functions, as opposed to "pbm"
780 ones.
781
782 Read the raster from *inpamP; write the transformed raster to *outpamP.
783
784 Assume input file is positioned to the raster (just after the
785 header).
786
787 This can do any transformation, but is slower and uses more memory
788 than some of the alternatives which are usable only for certain
789 cases. But we do require a certain amount of virtual and real memory;
790 transformNonPbmChunk() is even more general in that it doesn't.
791 -----------------------------------------------------------------------------*/
792 tuple ** newtuples;
793 /* output buffer */
794 tuple * tuplerow;
795 /* malloc'ed array of pointers to tuples in the output buffer,
796 'newtuples'
797 */
798 struct XformMatrix xform;
799 unsigned int row;
800
801 computeXformMatrix(&xform, inpamP->width, inpamP->height, xformCore);
802
803 MALLOCARRAY(tuplerow, inpamP->width);
804 if (!tuplerow)
805 pm_error("Unable to allocate memory for %u-column input buffer",
806 inpamP->width);
807
808 newtuples = pnm_allocpamarray(outpamP);
809
810 for (row = 0; row < inpamP->height; ++row) {
811 unsigned int col;
812
813 for (col = 0; col < inpamP->width; ++col) {
814 unsigned int newcol, newrow;
815
816 transformPoint(col, row, xform, &newcol, &newrow);
817
818 assert(newcol < outpamP->width);
819 assert(newrow < outpamP->height);
820
821 tuplerow[col] = newtuples[newrow][newcol];
822 }
823 pnm_readpamrow(inpamP, tuplerow);
824 /* Note that this reads directly into the output buffer,
825 'newtuples'.
826 */
827 }
828
829 writeRaster(outpamP, newtuples);
830
831 pnm_freepamarray(newtuples, outpamP);
832 free(tuplerow);
833 }
834
835
836
837 typedef struct {
838 /*----------------------------------------------------------------------------
839 A description of the quilt of cells that make up the output image.
840 -----------------------------------------------------------------------------*/
841 unsigned int rankCt, fileCt;
842 /* Dimensions of the output image in cells */
843 struct pam ** pam;
844 /* pam[y][x] is the pam structure for the cell at rank y, file x
845 in the output.
846 */
847
848 /* Each of the cells corresponds to a temporary file; the 'file'
849 member of its pam structure identifies it. But it is not a normal
850 Netpbm file; it contains only the raster portion. The program
851 writes the raster to the file, starting at offset zero, then rewinds
852 and reads it out later. The header is unnecessary because the pam
853 structure is still available at readback time.
854 */
855 } outputMap;
856
857
858
859 static void
860 initOutCell(struct pam * const outCellPamP,
861 unsigned int const inCellWidth,
862 unsigned int const inCellHeight,
863 struct pam * const inpamP,
864 struct XformCore const xformCore) {
865 /*----------------------------------------------------------------------------
866 Set up an output cell. Create and open a temporary file to hold its
867 raster. Figure out the dimensions of the cell. Return a PAM structure
868 that describes the cell (including identifying that temporary file).
869 -----------------------------------------------------------------------------*/
870 unsigned int outCellFileCt, outCellRankCt;
871
872 *outCellPamP = *inpamP; /* initial value */
873
874 outCellPamP->len = PAM_STRUCT_SIZE(tuple_type);
875
876 outCellPamP->file = pm_tmpfile();
877
878 xformDimensions(xformCore, inCellWidth, inCellHeight,
879 &outCellFileCt, &outCellRankCt);
880
881 outCellPamP->width = outCellFileCt;
882 outCellPamP->height = outCellRankCt;
883 }
884
885
886
887 static outputMap *
888 createOutputMap(struct pam * const inpamP,
889 unsigned int const maxRows,
890 struct XformMatrix const cellXform,
891 struct XformCore const xformCore) {
892 /*----------------------------------------------------------------------------
893 Create and return the output map. That's a map of all the output cells
894 (from which the output image can be assembled, once those cells are filled
895 in).
896
897 The map contains the dimensions of each output cell as well as file
898 stream handles for the temporary files containing the pixels of each
899 cell. We create and open those files.
900
901 Note that a complexity of determining cell dimensions (which we handle)
902 is that the input image isn't necessarily a whole multiple of the input
903 cell size, so the last cell may be short.
904
905 The map does not contain the mapping from input cells to output cells
906 (e.g. in a top-bottom transformation of a 10-cell image, input cell
907 0 maps to output cell 9); caller can compute that when needed from
908 'cellXform'.
909 -----------------------------------------------------------------------------*/
910 unsigned int const inCellFileCt = 1;
911 unsigned int const inCellRankCt = (inpamP->height + maxRows - 1) / maxRows;
912
913 outputMap * mapP;
914 unsigned int outCellRank;
915 unsigned int inCellRank;
916
917 MALLOCVAR_NOFAIL(mapP);
918
919 xformDimensions(xformCore, inCellFileCt, inCellRankCt,
920 &mapP->fileCt, &mapP->rankCt);
921
922 MALLOCARRAY(mapP->pam, mapP->rankCt);
923 if (mapP->pam == NULL)
924 pm_error("Could not allocate a cell array for %u ranks of cells.",
925 mapP->rankCt);
926
927 for (outCellRank = 0; outCellRank < mapP->rankCt; ++outCellRank) {
928
929 MALLOCARRAY(mapP->pam[outCellRank], mapP->fileCt);
930
931 if (mapP->pam[outCellRank] == NULL)
932 pm_error("Failed to allocate rank %u of the cell array, "
933 "%u cells wide", outCellRank, mapP->fileCt);
934 }
935
936 for (inCellRank = 0; inCellRank < inCellRankCt; ++inCellRank) {
937 unsigned int const inCellFile = 0;
938 unsigned int const inCellStartRow = inCellRank * maxRows;
939 unsigned int const inCellRowCt =
940 MIN(inpamP->height - inCellStartRow, maxRows);
941
942 unsigned int outCellFile, outCellRank;
943 transformPoint(inCellFile, inCellRank, cellXform,
944 &outCellFile, &outCellRank);
945
946 initOutCell(&mapP->pam[outCellRank][outCellFile],
947 inpamP->width, inCellRowCt,
948 inpamP, xformCore);
949 }
950 return mapP;
951 }
952
953
954
955 static void
956 destroyOutputMap(outputMap * const mapP) {
957
958 unsigned int outCellRank;
959
960 for (outCellRank = 0; outCellRank < mapP->rankCt; ++outCellRank)
961 free(mapP->pam[outCellRank]);
962
963 free(mapP->pam);
964
965 free(mapP);
966 }
967
968
969
970 static void
971 rewindCellFiles(outputMap * const outputMapP) {
972
973 unsigned int outCellRank;
974
975 for (outCellRank = 0; outCellRank < outputMapP->rankCt; ++outCellRank) {
976 unsigned int outCellFile;
977 for (outCellFile = 0; outCellFile < outputMapP->fileCt; ++outCellFile)
978 pm_seek(outputMapP->pam[outCellRank][outCellFile].file, 0);
979 }
980 }
981
982
983
984 static void
985 closeCellFiles(outputMap * const outputMapP) {
986
987 unsigned int outCellRank;
988
989 for (outCellRank = 0; outCellRank < outputMapP->rankCt; ++outCellRank) {
990 unsigned int outCellFile;
991 for (outCellFile = 0; outCellFile < outputMapP->fileCt; ++outCellFile)
992 pm_close(outputMapP->pam[outCellRank][outCellFile].file);
993 }
994 }
995
996
997
998 static void
999 transformCell(struct pam * const inpamP,
1000 struct pam * const outpamP,
1001 struct XformCore const xformCore) {
1002
1003 struct XformMatrix xform;
1004 tuple * inTupleRow;
1005 tuple ** outTuples;
1006 unsigned int inRow;
1007
1008 computeXformMatrix(&xform, inpamP->width, inpamP->height, xformCore);
1009
1010 inTupleRow = pnm_allocpamrow(inpamP);
1011
1012 outTuples = pnm_allocpamarray(outpamP);
1013
1014 for (inRow = 0; inRow < inpamP->height; ++inRow) {
1015 unsigned int inCol;
1016
1017 pnm_readpamrow(inpamP, inTupleRow);
1018
1019 for (inCol = 0; inCol < inpamP->width; ++inCol) {
1020 unsigned int outCol, outRow;
1021
1022 transformPoint(inCol, inRow, xform, &outCol, &outRow);
1023
1024 assert(outCol < outpamP->width);
1025 assert(outRow < outpamP->height);
1026
1027 pnm_assigntuple(inpamP,
1028 outTuples[outRow][outCol], inTupleRow[inCol]);
1029 }
1030 }
1031 pnm_freepamrow(inTupleRow);
1032
1033 writeRaster(outpamP, outTuples);
1034
1035 pnm_freepamarray(outTuples, outpamP);
1036 }
1037
1038
1039
1040 static void
1041 stitchCellsToOutput(outputMap * const outputMapP,
1042 struct pam * const outpamP) {
1043
1044 unsigned int outRank;
1045 tuple * tupleRow;
1046
1047 tupleRow = pnm_allocpamrow(outpamP);
1048
1049 for (outRank = 0; outRank < outputMapP->rankCt; ++outRank) {
1050 unsigned int const cellRows = outputMapP->pam[outRank][0].height;
1051 /* Number of rows in every cell in this rank */
1052
1053 unsigned int cellRow;
1054
1055 for (cellRow = 0; cellRow < cellRows; ++cellRow) {
1056 unsigned int outFile;
1057 unsigned int outCol;
1058
1059 outCol = 0;
1060
1061 for (outFile = 0; outFile < outputMapP->fileCt; ++outFile) {
1062 struct pam * const outCellPamP =
1063 &outputMapP->pam[outRank][outFile];
1064
1065 assert(outCellPamP->height == cellRows);
1066
1067 assert(outCol < outpamP->width);
1068 pnm_readpamrow(outCellPamP, &tupleRow[outCol]);
1069
1070 outCol += outCellPamP->width;
1071 }
1072
1073 assert(outCol == outpamP->width);
1074
1075 pnm_writepamrow(outpamP, tupleRow);
1076 }
1077 }
1078 pnm_freepamrow(tupleRow);
1079 }
1080
1081
1082
1083 static void
1084 transformNonPbmChunk(struct pam * const inpamP,
1085 struct pam * const outpamP,
1086 struct XformCore const xformCore,
1087 unsigned int const maxRows,
1088 bool const verbose) {
1089 /*----------------------------------------------------------------------------
1090 Same as transformNonPbmWhole(), except we read 'maxRows' rows of the
1091 input into memory at a time, storing intermediate results in temporary
1092 files, to limit our use of virtual and real memory.
1093
1094 Assume input file is positioned to the raster (just after the
1095 header).
1096
1097 We call the strip of 'maxRows' rows that we read a source cell. We
1098 transform that cell according to 'xformCore' to create a
1099 target cell. We store all the target cells in temporary files.
1100 We consider the target cells to be arranged in a column matrix the
1101 same as the source cells within the source image; we transform that
1102 matrix according to 'xformCore'. The resulting cell matrix is the
1103 target image.
1104 -----------------------------------------------------------------------------*/
1105 /* The cells of the source image ("inCell") are in a 1-column matrix.
1106 "rank" is the vertical position of a cell in that matrix; "file" is
1107 the horizontal position (always 0, of course).
1108 */
1109 unsigned int const inCellFileCt = 1;
1110 unsigned int const inCellRankCt = (inpamP->height + maxRows - 1) / maxRows;
1111
1112 struct XformMatrix cellXform;
1113 unsigned int inCellRank;
1114 outputMap * outputMapP;
1115
1116 if (verbose)
1117 pm_message("Transforming in %u chunks, using temp files",
1118 inCellRankCt);
1119
1120 computeXformMatrix(&cellXform, inCellFileCt, inCellRankCt, xformCore);
1121
1122 outputMapP = createOutputMap(inpamP, maxRows, cellXform, xformCore);
1123
1124 for (inCellRank = 0; inCellRank < inCellRankCt; ++inCellRank) {
1125 unsigned int const inCellFile = 0;
1126 unsigned int const inCellStartRow = inCellRank * maxRows;
1127 unsigned int const inCellRows =
1128 MIN(inpamP->height - inCellStartRow, maxRows);
1129
1130 struct pam inCellPam;
1131 struct pam * outCellPamP;
1132 unsigned int outCellFile, outCellRank;
1133
1134 transformPoint(inCellFile, inCellRank, cellXform,
1135 &outCellFile, &outCellRank);
1136
1137 outCellPamP = &outputMapP->pam[outCellRank][outCellFile];
1138
1139 /* Input cell is just the next 'inCellRows' rows of input image */
1140 inCellPam = *inpamP;
1141 inCellPam.height = inCellRows;
1142
1143 transformCell(&inCellPam, outCellPamP, xformCore);
1144 }
1145
1146 rewindCellFiles(outputMapP);
1147
1148 stitchCellsToOutput(outputMapP, outpamP);
1149
1150 closeCellFiles(outputMapP);
1151
1152 destroyOutputMap(outputMapP);
1153 }
1154
1155
1156
1157 static unsigned int
1158 maxRowsThatFit(struct pam * const pamP,
1159 size_t const availableMemory) {
1160
1161 unsigned long const otherNeeds = 100*1024;
1162 /* A wild guess at how much memory (from the same pool as the
1163 input rows) is needed for things other than the input rows
1164 */
1165 unsigned long const availForRows =
1166 availableMemory > otherNeeds ? availableMemory - otherNeeds : 0;
1167 unsigned int const bytesPerTuple =
1168 pamP->depth * sizeof(sample) + sizeof(tuple *);
1169 unsigned int const bytesPerRow =
1170 pamP->width * bytesPerTuple + sizeof(tuple **);
1171
1172 unsigned long const maxRows = availForRows / bytesPerRow;
1173
1174 if (maxRows < 1)
1175 pm_error("You haven't allowed enough memory to fit even one row "
1176 "of the source image in memory. The minimum chunk size "
1177 "is one row; we need at least %lu bytes.",
1178 otherNeeds + bytesPerRow);
1179
1180 return (unsigned int)MIN(maxRows, UINT_MAX);
1181 }
1182
1183
1184
1185 static void
1186 transformPbm(struct pam * const inpamP,
1187 struct pam * const outpamP,
1188 struct XformCore const xform,
1189 bool const verbose) {
1190
1191 if (xform.b == 0 && xform.c == 0) {
1192 /* Rows of input map to rows of target; no column-for-row */
1193 if (xform.d == 1)
1194 /* Row N of the output is based only on Row N of the
1195 input, so we can transform row by row and avoid
1196 in-memory buffering altogether.
1197 */
1198 transformRowByRowPbm(inpamP, outpamP, xform.a == -1);
1199 else
1200 /* Row N of the output is based only on Row ~N of the
1201 input. We need all the rows in memory, but have to pass
1202 through them only twice, so there is no page thrashing concern.
1203 */
1204 transformRowsBottomTopPbm(inpamP, outpamP, xform.a == -1);
1205 } else {
1206 /* This is a column-for-row type of transformation, which requires
1207 complex traversal of an in-memory image.
1208 */
1209 if (SSE_PBM_XY_FLIP)
1210 pamflip_transformRowsToColumnsPbmSse(inpamP, outpamP, xform);
1211 else
1212 transformPbmGen(inpamP, outpamP, xform);
1213 }
1214 }
1215
1216
1217
1218 static void
1219 transformNonPbm(struct pam * const inpamP,
1220 struct pam * const outpamP,
1221 struct XformCore const xform,
1222 unsigned int const availableMemory,
1223 bool const verbose) {
1224
1225 if (xform.b == 0 && xform.c == 0 && xform.d == 1) {
1226 /* Row N of the output is based only on Row N of the
1227 input, so we can transform row by row and avoid
1228 in-memory buffering altogether.
1229 */
1230 if (verbose)
1231 pm_message("Transforming row by row");
1232 transformRowByRowNonPbm(inpamP, outpamP, xform.a == -1);
1233 } else {
1234 unsigned int const maxRows = maxRowsThatFit(inpamP, availableMemory);
1235 if (maxRows >= inpamP->height) {
1236 /* We can fit the whole image in memory at once and avoid
1237 temporary files.
1238 */
1239 if (xform.b == 0 && xform.c == 0 && xform.d == -1 &&
1240 xform.a == 1) {
1241 /* This is just a vertical flip; We can move whole rows
1242 instead of individual pixels and save time.
1243 */
1244 if (verbose)
1245 pm_message("Transforming whole rows, all in memory");
1246
1247 transformRowsBottomTopNonPbm(inpamP, outpamP);
1248 } else {
1249 if (verbose)
1250 pm_message("Transforming whole image at once, "
1251 "pixel by pixel");
1252 transformNonPbmWhole(inpamP, outpamP, xform, verbose);
1253 }
1254 } else
1255 /* No optimizations possible */
1256 transformNonPbmChunk(inpamP, outpamP, xform, maxRows, verbose);
1257 }
1258 }
1259
1260
1261
1262 int
1263 main(int argc, char * argv[]) {
1264 struct cmdlineInfo cmdline;
1265 struct pam inpam;
1266 struct pam outpam;
1267 unsigned int cols, rows;
1268 FILE * ifP;
1269
1270 pnm_init(&argc, argv);
1271
1272 parseCommandLine(argc, argv, &cmdline);
1273
1274 if (cmdline.availableMemory < UINT_MAX)
1275 ifP = pm_openr_seekable(cmdline.inputFilespec);
1276 else
1277 ifP = pm_openr(cmdline.inputFilespec);
1278
1279 pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
1280
1281 outpam = inpam; /* initial value */
1282
1283 outpam.file = stdout;
1284 xformDimensions(cmdline.xform, inpam.width, inpam.height, &cols, &rows);
1285 outpam.width = cols; outpam.height = rows;
1286
1287 pnm_writepaminit(&outpam);
1288
1289 switch (PNM_FORMAT_TYPE(inpam.format)) {
1290 case PBM_TYPE:
1291 transformPbm(&inpam, &outpam, cmdline.xform, cmdline.verbose);
1292 break;
1293 default:
1294 transformNonPbm(&inpam, &outpam, cmdline.xform,
1295 cmdline.availableMemory, cmdline.verbose);
1296 }
1297 pm_close(inpam.file);
1298 pm_close(outpam.file);
1299
1300 return 0;
1301 }