ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rcollate.c
(Generate patch)

Comparing ray/src/util/rcollate.c (file contents):
Revision 2.27 by greg, Thu Oct 18 22:59:48 2018 UTC vs.
Revision 2.40 by greg, Wed Mar 16 17:36:45 2022 UTC

# Line 6 | Line 6 | static const char RCSid[] = "$Id$";
6   */
7  
8   #include <stdlib.h>
9 #include <string.h>
9   #include <ctype.h>
10   #include "platform.h"
11   #include "rtio.h"
# Line 20 | Line 19 | static const char RCSid[] = "$Id$";
19    #include <sys/mman.h>
20   #endif
21  
22 + static char     delims[] = " \t\n\r\f";
23 +
24 + #define MAXLEVELS       16      /* max RxC.. block pairs */
25 +
26   typedef struct {
27 +        void    *mapped;        /* memory-mapped pointer */
28          void    *base;          /* pointer to base memory */
29          size_t  len;            /* allocated memory length */
26        int     mapped;         /* memory-mapped file? */
30   } MEMLOAD;              /* file loaded/mapped into memory */
31  
32   typedef struct {
33          int     nw_rec;         /* number of words per record */
34 <        int     nrecs;          /* number of records we found */
34 >        ssize_t nrecs;          /* number of records we found */
35          char    *rec[1];        /* record array (extends struct) */
36   } RECINDEX;
37  
38 < int             warnings = 1;   /* report warnings? */
38 > int             warnings = 1;                   /* report warnings? */
39  
40 + char            *fmtid = NULL;                  /* format id */
41 + int             comp_size = 0;                  /* binary bytes/channel */
42 + int             n_comp = 0;                     /* components/record */
43 + int             ni_columns = 0;                 /* number of input columns */
44 + int             ni_rows = 0;                    /* number of input rows */
45 + int             no_columns = 0;                 /* number of output columns */
46 + int             no_rows = 0;                    /* number of output rows */
47 + int             transpose = 0;                  /* transpose rows & cols? */
48 + int             i_header = 1;                   /* input header? */
49 + int             o_header = 1;                   /* output header? */
50 + int             outArray[MAXLEVELS][2];         /* output block nesting */
51 + int             outLevels = 0;                  /* number of blocking levels */
52 + int             check = 0;                      /* force data check? */
53 +
54   /* free loaded file */
55   static void
56   free_load(MEMLOAD *mp)
# Line 42 | Line 59 | free_load(MEMLOAD *mp)
59                  return;
60   #ifdef MAP_FILE
61          if (mp->mapped)
62 <                munmap(mp->base, mp->len);
62 >                munmap(mp->mapped, mp->len);
63          else
64   #endif
65                  free(mp->base);
66 +        mp->mapped = NULL;
67          mp->base = NULL;
68          mp->len = 0;
69   }
# Line 60 | Line 78 | load_stream(MEMLOAD *mp, FILE *fp)
78  
79          if (mp == NULL)
80                  return(-1);
81 +        mp->mapped = NULL;
82          mp->base = NULL;
83          mp->len = 0;
65        mp->mapped = 0;
84          if (fp == NULL)
85                  return(-1);
86          while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
# Line 85 | Line 103 | load_stream(MEMLOAD *mp, FILE *fp)
103          return(mp->len > 0);
104   }
105  
106 + #if defined(_WIN32) || defined(_WIN64)
107 +                                /* too difficult to fix this */
108 + #define load_file       load_stream
109 + #else
110   /* load a file into memory */
111   static int
112   load_file(MEMLOAD *mp, FILE *fp)
113   {
114          int     fd;
115 <        off_t   skip, flen, skipped;
94 <
95 < #if defined(_WIN32) || defined(_WIN64)
96 <                                /* too difficult to fix this */
97 <        return load_stream(mp, fp);
98 < #endif
115 >        off_t   skip, flen, fpos;
116          if (mp == NULL)
117                  return(-1);
118 +        mp->mapped = NULL;
119          mp->base = NULL;
120          mp->len = 0;
103        mp->mapped = 0;
121          if (fp == NULL)
122                  return(-1);
123          fd = fileno(fp);
# Line 110 | Line 127 | load_file(MEMLOAD *mp, FILE *fp)
127                  return((int)(flen - skip));
128          mp->len = (size_t)(flen - skip);
129   #ifdef MAP_FILE
130 <        if (mp->len > 1L<<20) {         /* map file if > 1 MByte */
131 <                mp->base = mmap(NULL, flen, PROT_READ, MAP_PRIVATE, fd, 0);
132 <                if (mp->base != MAP_FAILED) {
133 <                        mp->base = (char *)mp->base + skip;
117 <                        mp->mapped = 1;
130 >        if (mp->len >= 1L<<20) {        /* map file if >= 1 MByte */
131 >                mp->mapped = mmap(NULL, flen, PROT_READ, MAP_PRIVATE, fd, 0);
132 >                if (mp->mapped != MAP_FAILED) {
133 >                        mp->base = (char *)mp->mapped + skip;
134                          return(1);      /* mmap() success */
135                  }
136 <                mp->base = NULL;        /* fall back to reading it in... */
136 >                mp->mapped = NULL;      /* else fall back to reading it in... */
137          }
138   #endif
139          if (lseek(fd, skip, SEEK_SET) != skip ||
# Line 125 | Line 141 | load_file(MEMLOAD *mp, FILE *fp)
141                  mp->len = 0;
142                  return(-1);
143          }
144 <        skipped = skip;                 /* read() fails on really big buffers */
145 <        while (skipped < flen) {
146 <                ssize_t nread = read(fd, (char *)mp->base+(skipped-skip),
147 <                                (flen-skipped <= 1L<<30) ? flen-skipped : 1L<<30);
144 >        fpos = skip;
145 >        while (fpos < flen) {           /* read() fails if n > 2 GBytes */
146 >                ssize_t nread = read(fd, (char *)mp->base+(fpos-skip),
147 >                                (flen-fpos < 1L<<24) ? flen-fpos : 1L<<24);
148                  if (nread <= 0) {
149                          free_load(mp);
150                          return(-1);
151                  }
152 <                skipped += nread;
152 >                fpos += nread;
153          }
154          return(1);
155   }
156 + #endif
157  
158   /* free a record index */
159   #define free_records(rp)        free(rp)
# Line 182 | Line 199 | index_records(const MEMLOAD *mp, int nw_rec)
199                                          break;  /* got requisite # words */
200                                  do {            /* else find next word */
201                                          if (*cp == '\n') {
202 <                                                fprintf(stderr,
186 <                                                "Unexpected EOL in record!\n");
202 >                                                fputs("Unexpected EOL in record!\n", stderr);
203                                                  free_records(rp);
204                                                  return(NULL);
205                                          }
# Line 217 | Line 233 | count_columns(const RECINDEX *rp)
233  
234   /* copy nth record from index to stdout */
235   static int
236 < print_record(const RECINDEX *rp, int n)
236 > print_record(const RECINDEX *rp, ssize_t n)
237   {
238          int     words2go = rp->nw_rec;
239          char    *scp;
# Line 225 | Line 241 | print_record(const RECINDEX *rp, int n)
241          if ((n < 0) | (n >= rp->nrecs))
242                  return(0);
243          scp = rp->rec[n];
244 +
245 +        if (check && !isfltd(scp, delims))
246 +                goto formerr;
247          do {
248                  putc(*scp++, stdout);
249                  if (!*scp | isspace(*scp)) {
# Line 235 | Line 254 | print_record(const RECINDEX *rp, int n)
254                                  if (++scp >= rp->rec[n+1])
255                                          break;
256                          while (!*scp | isspace(*scp));
257 +
258 +                        if (check && !isfltd(scp, delims))
259 +                                goto formerr;
260                  }
261          } while (scp < rp->rec[n+1]);
262                                                  /* caller adds record sep. */
263          return(1);
264 + formerr:
265 +        fputs("Badly formed number: ", stderr);
266 +        while (*scp && !isspace(*scp))
267 +                fputc(*scp++, stderr);
268 +        fputc('\n', stderr);
269 +        return(0);
270   }
271  
272   /* copy a stream to stdout */
# Line 280 | Line 308 | fget_word(char buf[256], FILE *fp)
308          return(buf);
309   }
310  
311 < char            *fmtid = NULL;                  /* format id */
312 < int             comp_size = 0;                  /* binary bytes/channel */
313 < int             n_comp = 0;                     /* components/record */
314 < int             ni_columns = 0;                 /* number of input columns */
315 < int             ni_rows = 0;                    /* number of input rows */
288 < int             no_columns = 0;                 /* number of output columns */
289 < int             no_rows = 0;                    /* number of output rows */
290 < int             transpose = 0;                  /* transpose rows & cols? */
291 < int             i_header = 1;                   /* input header? */
292 < int             o_header = 1;                   /* output header? */
311 > /* parse RxCx... string */
312 > static int
313 > get_array(const char *spec, int blklvl[][2], int nlvls)
314 > {
315 >        int     n;
316  
317 +        if (nlvls <= 0) {
318 +                fputs("Too many block levels!\n", stderr);
319 +                exit(1);
320 +        }
321 +        if (sscanf(spec, "%dx%d", &blklvl[0][0], &blklvl[0][1]) != 2) {
322 +                fputs("Bad block specification!\n", stderr);
323 +                exit(1);
324 +        }
325 +        while (isdigit(*spec))
326 +                spec++;
327 +        spec++;         /* 'x' */
328 +        while (isdigit(*spec))
329 +                spec++;
330 +        if ((*spec != 'x') & (*spec != 'X')) {
331 +                if (*spec) {
332 +                        fputs("Blocks must be separated by 'x' or 'X'\n", stderr);
333 +                        exit(1);
334 +                }
335 +                return(1);
336 +        }
337 +        spec++;
338 +        n = get_array(spec, blklvl+1, nlvls-1);
339 +        if (!n)
340 +                return(0);
341 +        blklvl[0][0] *= blklvl[1][0];
342 +        blklvl[0][1] *= blklvl[1][1];
343 +        return(n+1);
344 + }
345 +
346   /* check settings and assign defaults */
347   static int
348   check_sizes()
# Line 320 | Line 372 | check_sizes()
372          return(1);
373   }
374  
375 < /* output transposed ASCII or binary data from memory */
375 > /* call to compute block input position */
376 > static ssize_t
377 > get_block_pos(int r, int c, int blklvl[][2], int nlvls)
378 > {
379 >        ssize_t n = 0;
380 >
381 >        while (nlvls > 1) {
382 >                int     sr = r/blklvl[1][0];
383 >                int     sc = c/blklvl[1][1];
384 >                r -= sr*blklvl[1][0];
385 >                c -= sc*blklvl[1][1];
386 >                n += sr*blklvl[1][0]*blklvl[0][1] + sc*blklvl[1][0]*blklvl[1][1];
387 >                blklvl++;
388 >                nlvls--;
389 >        }
390 >        n += r*blklvl[0][1] + c;
391 >        return(n);
392 > }
393 >
394 > /* return input offset based on array ordering and transpose option */
395 > static ssize_t
396 > get_input_pos(int r, int c)
397 > {
398 >        ssize_t n;
399 >
400 >        if (outLevels > 1) {            /* block reordering */
401 >                n = get_block_pos(r, c, outArray, outLevels);
402 >                if (transpose) {
403 >                        r = n/ni_rows;
404 >                        c = n - r*ni_rows;
405 >                        n = (ssize_t)c*ni_columns + r;
406 >                }
407 >        } else if (transpose)           /* transpose only */
408 >                n = (ssize_t)c*ni_columns + r;
409 >        else                            /* XXX should never happen! */
410 >                n = (ssize_t)r*no_columns + c;
411 >        return(n);
412 > }
413 >
414 > /* output reordered ASCII or binary data from memory */
415   static int
416 < do_transpose(const MEMLOAD *mp)
416 > do_reorder(const MEMLOAD *mp)
417   {
418          static const char       tabEOL[2] = {'\t','\n'};
419          RECINDEX                *rp = NULL;
420 <        long                    nrecords;
420 >        ssize_t                 nrecords;
421          int                     i, j;
422                                                  /* propogate sizes */
423          if (ni_rows <= 0)
424 <                ni_rows = no_columns;
424 >                ni_rows = transpose ? no_columns : no_rows;
425          if (ni_columns <= 0)
426 <                ni_columns = no_rows;
426 >                ni_columns = transpose ? no_rows : no_columns;
427                                                  /* get # records (& index) */
428          if (!comp_size) {
429                  if ((rp = index_records(mp, n_comp)) == NULL)
# Line 341 | Line 432 | do_transpose(const MEMLOAD *mp)
432                          ni_columns = count_columns(rp);
433                  nrecords = rp->nrecs;
434          } else if ((ni_rows > 0) & (ni_columns > 0)) {
435 <                nrecords = ni_rows*ni_columns;
435 >                nrecords = (ssize_t)ni_rows*ni_columns;
436                  if (nrecords > mp->len/(n_comp*comp_size)) {
437 <                        fprintf(stderr,
438 <                            "Input too small for specified size and type\n");
437 >                        fputs("Input too small for specified size and type\n",
438 >                                        stderr);
439                          return(0);
440                  }
441          } else
# Line 352 | Line 443 | do_transpose(const MEMLOAD *mp)
443                                                  /* check sizes */
444          if ((ni_rows <= 0) & (ni_columns > 0))
445                  ni_rows = nrecords/ni_columns;
446 <        if ((ni_columns <= 0) & (ni_rows > 0))
446 >        else if ((ni_columns <= 0) & (ni_rows > 0))
447                  ni_columns = nrecords/ni_rows;
448 <        if (nrecords != ni_rows*ni_columns)
448 >        if (nrecords != (ssize_t)ni_rows*ni_columns)
449                  goto badspec;
450 <        if (no_columns <= 0)
451 <                no_columns = ni_rows;
452 <        if (no_rows <= 0)
453 <                no_rows = ni_columns;
454 <        if ((no_rows != ni_columns) | (no_columns != ni_rows))
455 <                goto badspec;
456 <                                                /* transpose records */
450 >        if (transpose) {
451 >                if (no_columns <= 0)
452 >                        no_columns = ni_rows;
453 >                if (no_rows <= 0)
454 >                        no_rows = ni_columns;
455 >                if (outLevels <= 1 &&
456 >                                (no_rows != ni_columns) | (no_columns != ni_rows))
457 >                        goto badspec;
458 >        } else {
459 >                if (no_columns <= 0)
460 >                        no_columns = ni_columns;
461 >                if (no_rows <= 0)
462 >                        no_rows = ni_rows;
463 >        }
464 >        if (ni_rows*ni_columns != no_rows*no_columns) {
465 >                fputs("Number of input and output records do not match\n",
466 >                                stderr);
467 >                return(0);
468 >        }
469 >        if (o_header) {                         /* finish header? */
470 >                printf("NROWS=%d\n", no_rows);
471 >                printf("NCOLS=%d\n", no_columns);
472 >                fputformat(fmtid, stdout);
473 >                fputc('\n', stdout);
474 >        }
475 >                                                /* reorder records */
476          for (i = 0; i < no_rows; i++) {
477 <            for (j = 0; j < no_columns; j++)
477 >            for (j = 0; j < no_columns; j++) {
478 >                ssize_t n = get_input_pos(i, j);
479 >                if (n >= nrecords) {
480 >                        fputs("Index past end-of-file\n", stderr);
481 >                        return(0);
482 >                }
483                  if (rp != NULL) {               /* ASCII output */
484 <                        print_record(rp, j*ni_columns + i);
484 >                        if (!print_record(rp, n))
485 >                                return(0);
486                          putc(tabEOL[j >= no_columns-1], stdout);
487                  } else {                        /* binary output */
488 <                        putbinary((char *)mp->base +
373 <                            (unsigned long)(n_comp*comp_size)*(j*ni_columns + i),
488 >                        putbinary((char *)mp->base + (n_comp*comp_size)*n,
489                                          comp_size, n_comp, stdout);
490                  }
491 +            }
492              if (ferror(stdout)) {
493 <                fprintf(stderr, "Error writing to stdout\n");
493 >                fputs("Error writing to stdout\n", stderr);
494                  return(0);
495              }
496          }
# Line 382 | Line 498 | do_transpose(const MEMLOAD *mp)
498                  free_records(rp);
499          return(1);
500   badspec:
501 <        fprintf(stderr, "Bad transpose specification -- check dimension(s)\n");
501 >        fputs("Bad dimension(s)\n", stderr);
502          return(0);
503   }
504  
# Line 390 | Line 506 | badspec:
506   static int
507   do_resize(FILE *fp)
508   {
509 <        long    records2go = ni_rows*ni_columns;
509 >        ssize_t records2go = ni_rows*ni_columns;
510          int     columns2go = no_columns;
511          char    word[256];
512 +                        
513 +        if (o_header) {                         /* finish header? */
514 +                if (no_rows > 0)
515 +                        printf("NROWS=%d\n", no_rows);
516 +                if (no_columns > 0)
517 +                        printf("NCOLS=%d\n", no_columns);
518 +                fputformat(fmtid, stdout);
519 +                fputc('\n', stdout);
520 +        }
521                                                  /* sanity checks */
522 <        if (comp_size || (no_columns == ni_columns) & (no_rows == ni_rows))
522 >        if (comp_size || !check &
523 >                        (no_columns == ni_columns) & (no_rows == ni_rows))
524                  return(output_stream(fp));      /* no-op -- just copy */
525          if (no_columns <= 0) {
526 <                fprintf(stderr, "Missing -oc specification\n");
526 >                fputs("Missing -oc specification\n", stderr);
527                  return(0);
528          }
529          if ((records2go <= 0) & (no_rows > 0))
530                  records2go = no_rows*no_columns;
531          else if (no_rows*no_columns != records2go) {
532                  fprintf(stderr,
533 <                        "Input and output data sizes disagree (%dx%d != %dx%d)\n",
533 >                        "Number of input and output records disagree (%dx%d != %dx%d)\n",
534                                  ni_rows, ni_columns, no_rows, no_columns);
535                  return(0);
536          }
# Line 417 | Line 543 | do_resize(FILE *fp)
543                                          break;
544                                  goto done;      /* normal EOD */
545                          }
546 +                        if (check && !isfltd(word, delims)) {
547 +                                fputs("Badly formed number: ", stderr);
548 +                                fputs(word, stderr);
549 +                                fputc('\n', stderr);
550 +                                return(0);
551 +                        }
552                          fputs(word, stdout);
553                          if (n) {                /* mid-record? */
554                                  int     c = getc(fp);
# Line 427 | Line 559 | do_resize(FILE *fp)
559                          }
560                  }
561                  if (n >= 0) {
562 <                        fprintf(stderr, "Incomplete record / unexpected EOF\n");
562 >                        fputs("Incomplete record / unexpected EOF\n", stderr);
563                          return(0);
564                  }
565                  if (--columns2go <= 0) {        /* time to end output row? */
# Line 438 | Line 570 | do_resize(FILE *fp)
570          } while (--records2go);                 /* expected EOD? */
571   done:
572          if (warnings && columns2go != no_columns)
573 <                fprintf(stderr, "Warning -- incomplete final row\n");
573 >                fputs("Warning -- incomplete final row\n", stderr);
574          if (warnings && fget_word(word, fp) != NULL)
575 <                fprintf(stderr, "Warning -- characters beyond expected EOD\n");
575 >                fputs("Warning -- characters beyond expected EOD\n", stderr);
576          return(1);
577   }
578  
# Line 514 | Line 646 | main(int argc, char *argv[])
646                                  no_columns = atoi(argv[++a]);
647                          else if (argv[a][2] == 'r')
648                                  no_rows = atoi(argv[++a]);
649 <                        else
649 >                        else if (argv[a][2] ||
650 >                          !(outLevels=get_array(argv[++a], outArray, MAXLEVELS)))
651                                  goto userr;
652                          break;
653                  case 'h':                       /* turn off header */
# Line 570 | Line 703 | main(int argc, char *argv[])
703                  case 'w':                       /* warnings on/off */
704                          warnings = !warnings;
705                          break;
706 +                case 'c':                       /* force check operation */
707 +                        check = 1;
708 +                        break;
709                  default:
710                          goto userr;
711                  }
712          if (a < argc-1)                         /* arg count OK? */
713                  goto userr;
714 +        if (outLevels) {                        /* should check consistency? */
715 +                no_rows = outArray[0][0];
716 +                no_columns = outArray[0][1];
717 +        }
718                                                  /* open input file? */
719          if (a == argc-1 && freopen(argv[a], "r", stdin) == NULL) {
720                  fprintf(stderr, "%s: cannot open for reading\n", argv[a]);
# Line 584 | Line 724 | main(int argc, char *argv[])
724                  SET_FILE_BINARY(stdin);
725                  SET_FILE_BINARY(stdout);
726          }
727 + #ifdef getc_unlocked                            /* avoid stupid semaphores */
728 +        flockfile(stdin);
729 +        flockfile(stdout);
730 + #endif
731                                                  /* check for no-op */
732 <        if (!transpose & (i_header == o_header) &&
732 >        if (!transpose & !check & (outLevels <= 1) & (i_header == o_header) &&
733                          (no_columns == ni_columns) & (no_rows == ni_rows)) {
734                  if (warnings)
735                          fprintf(stderr, "%s: no-op -- copying input verbatim\n",
# Line 605 | Line 749 | main(int argc, char *argv[])
749                  }
750          } else if (!check_sizes())
751                  return(1);
752 <        if (o_header) {                         /* write header */
752 >        if (o_header) {                         /* write/add to header */
753 >                if (!i_header)
754 >                        newheader("RADIANCE", stdout);
755                  printargs(a, argv, stdout);
610                if (no_rows > 0)
611                        printf("NROWS=%d\n", no_rows);
612                if (no_columns > 0)
613                        printf("NCOLS=%d\n", no_columns);
756                  printf("NCOMP=%d\n", n_comp);
615                fputformat(fmtid, stdout);
616                fputc('\n', stdout);            /* finish new header */
757          }
758 <        if (transpose) {                        /* transposing rows & columns? */
758 >        if (transpose | check | (outLevels > 1) || (o_header && no_rows <= 0)) {
759                  MEMLOAD myMem;                  /* need to map into memory */
760                  if (a == argc-1) {
761                          if (load_file(&myMem, stdin) <= 0) {
# Line 628 | Line 768 | main(int argc, char *argv[])
768                                                  argv[0]);
769                          return(1);
770                  }
771 <                if (!do_transpose(&myMem))
771 >                if (!do_reorder(&myMem))
772                          return(1);
773                  /* free_load(&myMem);   about to exit, so don't bother */
774 <        } else if (!do_resize(stdin))           /* reshaping input */
774 >        } else if (!do_resize(stdin))           /* just reshaping input */
775                  return(1);
776          return(0);
777   userr:
778          fprintf(stderr,
779 < "Usage: %s [-h[io]][-w][-f[afdb][N]][-t][-ic in_col][-ir in_row][-oc out_col][-or out_row] [input.dat]\n",
779 > "Usage: %s [-h[io]][-w][-c][-f[afdb][N]][-t][-ic in_col][-ir in_row][-oc out_col][-or out_row][-o RxC[xR1xC1..]] [input.dat]\n",
780                          argv[0]);
781          return(1);
782   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines