2 ## -----------------------------------------------------------------------
4 ## Copyright 2004-2008 H. Peter Anvin - All Rights Reserved
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation, Inc., 53 Temple Place Ste 330,
9 ## Boston MA 02111-1307, USA; either version 2 of the License, or
10 ## (at your option) any later version; incorporated herein by reference.
12 ## -----------------------------------------------------------------------
17 ## Convert a PNM file with max 16 colors to a simple RLE-based format:
19 ## uint32 0x1413f33d ; magic (littleendian)
20 ## uint16 xsize ; littleendian
21 ## uint16 ysize ; littleendian
22 ## 16 x uint8 r,g,b ; color map, in 6-bit format (each byte is 0..63)
24 ## Then, a sequence of nybbles:
26 ## N ... if N is != previous pixel, one pixel of color N
27 ## ... otherwise run sequence follows ...
28 ## M ... if M > 0 then run length is M
29 ## ... otherwise run sequence is encoded in two nybbles,
32 ## The nybble sequences are on a per-row basis; runs may not extend
33 ## across rows and odd-nybble rows are zero-padded.
35 ## At the start of row, the "previous pixel" is assumed to be zero.
39 ## ppmtolss16 [#rrggbb=i ...] < input.ppm > output.rle
41 ## Command line options of the form #rrggbb=i indicate that
42 ## the color #rrggbb (hex) should be assigned index i (decimal)
46 eval { binmode STDIN
; };
47 eval { binmode STDOUT
; };
51 # Get a token from the PPM header. Ignore comments and leading
52 # and trailing whitespace, as is required by the spec.
53 # This routine eats exactly one character of trailing whitespace,
54 # unless it is a comment (in which case it eats the comment up
55 # to and including the end of line.)
62 return undef if ( !defined($ch) ); # EOF
66 return undef if ( !defined($ch) );
67 } while ( $ch ne "\n" );
69 } while ( $ch =~ /^[ \t\n\v\f\r]$/ );
74 last if ( $ch =~ /^[ \t\n\v\f\r\#]$/ );
80 } while ( defined($ch) && $ch ne "\n" );
85 # Get a token, and make sure it is numeric (and exists)
86 sub get_numeric_token
() {
87 my($token) = get_token
();
89 if ( $token !~ /^[0-9]+$/ ) {
90 print STDERR
"Format error on input\n";
97 # Must be called before each pixel row is read
99 $getrgb_leftover_bit_cnt = 0;
100 $getrgb_leftover_bit_val = 0;
103 # Get a single RGB token depending on the PNM type
109 # Raw PPM, most common
110 return undef unless ( read(STDIN
,$rgb,3) == 3 );
111 return unpack("CCC", $rgb);
112 } elsif ( $form == 3 ) {
114 $r = get_numeric_token
();
115 $g = get_numeric_token
();
116 $b = get_numeric_token
();
118 } elsif ( $form == 5 ) {
120 return undef unless ( read(STDIN
,$rgb,1) == 1 );
121 $r = unpack("C", $rgb);
123 } elsif ( $form == 2 ) {
125 $r = get_numeric_token
();
127 } elsif ( $form == 4 ) {
129 if ( !$getrgb_leftover_bit_cnt ) {
130 return undef unless ( read(STDIN
,$rgb,1) == 1 );
131 $getrgb_leftover_bit_val = unpack("C", $rgb);
132 $getrgb_leftover_bit_cnt = 8;
134 $r = ( $getrgb_leftover_bit_val & 0x80 ) ?
0x00 : 0xff;
135 $getrgb_leftover_bit_val <<= 1;
136 $getrgb_leftover_bit_cnt--;
139 } elsif ( $form == 1 ) {
145 return undef if ( !defined($ch) );
146 return (255,255,255) if ( $ch eq '0' ); # White
147 return (0,0,0) if ( $ch eq '1'); # Black
151 return undef if ( !defined($ch) );
152 } while ( $ch ne "\n" );
154 } while ( $ch =~ /^[ \t\n\v\f\r]$/ );
157 die "Internal error: unknown format: $form\n";
161 sub rgbconvert
($$$$) {
162 my($r,$g,$b,$maxmult) = @_;
165 $r = int($r*$maxmult);
166 $g = int($g*$maxmult);
167 $b = int($b*$maxmult);
168 $rgb = pack("CCC", $r, $g, $b);
172 foreach $arg ( @ARGV ) {
173 if ( $arg =~ /^\#([0-9a-f])([0-9a-f])([0-9a-f])=([0-9]+)$/i ) {
178 } elsif ( $arg =~ /^\#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})=([0-9]+)$/i ) {
183 } elsif ( $arg =~ /^\#([0-9a-f]{3})([0-9a-f]{3})([0-9a-f]{3})=([0-9]+)$/i ) {
188 } elsif ( $arg =~ /^\#([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})=([0-9]+)$/i ) {
194 print STDERR
"$0: Unknown argument: $arg\n";
199 print STDERR
"$0: Color index out of range: $arg\n";
203 $rgb = rgbconvert
($r, $g, $b, 64/256);
205 if ( defined($index_forced{$i}) ) {
206 print STDERR
"$0: More than one color index $i\n";
209 $index_forced{$i} = $rgb;
210 $force_index{$rgb} = $i;
214 die "$0: stdin is not a PNM file" if ( $form !~ /^P([1-6])$/ );
217 $xsize = get_numeric_token
();
218 $ysize = get_numeric_token
();
219 if ( $form == 1 || $form == 4 ) {
220 $maxcol = 255; # Internal convention
222 $maxcol = get_numeric_token
();
224 $maxmult = 64/($maxcol+1); # Equal buckets conversion
228 for ( $y = 0 ; $y < $ysize ; $y++ ) {
230 for ( $x = 0 ; $x < $xsize ; $x++ ) {
231 die "$0: Premature EOF at ($x,$y) of ($xsize,$ysize)\n"
232 if ( !scalar(@pnmrgb = getrgb
($form)) );
233 # Convert to 6-bit representation
234 $rgb = rgbconvert
($pnmrgb[0], $pnmrgb[1], $pnmrgb[2], $maxmult);
235 $color_count{$rgb}++;
240 # Sort list of colors according to freqency
241 @colors = sort { $color_count{$b} <=> $color_count{$a} } keys(%color_count);
243 # Now we have our pick of colors. Sort according to intensity;
244 # this is more or less an ugly hack to cover for the fact that
245 # using PPM as input doesn't let the user set the color map,
246 # which the user really needs to be able to do.
249 my($ra,$ga,$ba) = unpack("CCC", $a);
250 my($rb,$gb,$bb) = unpack("CCC", $b);
252 my($ia) = $ra*0.299 + $ga*0.587 + $ba*0.114;
253 my($ib) = $rb*0.299 + $gb*0.587 + $bb*0.114;
255 return ( $ia <=> $ib ) if ( $ia != $ib );
257 # If same, sort based on RGB components,
258 # with highest priority given to G, then R, then B.
260 return ( $ga <=> $gb ) if ( $ga != $gb );
261 return ( $ra <=> $rb ) if ( $ra != $rb );
262 return ( $ba <=> $bb );
265 @icolors = sort by_intensity
@colors;
267 # Insert forced colors into "final" array
268 @colors = (undef) x
16;
269 foreach $rgb ( keys(%force_index) ) {
270 $i = $force_index{$rgb};
272 $color_index{$rgb} = $i;
277 # Insert remaining colors in the remaining slots,
278 # in luminosity-sorted order
280 while ( scalar(@icolors) ) {
281 # Advance to the next free slot
282 $nix++ while ( defined($colors[$nix]) && $nix < 16 );
283 last if ( $nix >= 16 );
284 $rgb = shift @icolors;
285 if ( !defined($color_index{$rgb}) ) {
286 $colors[$nix] = $rgb;
287 $color_index{$rgb} = $nix;
291 while ( scalar(@icolors) ) {
292 $rgb = shift @icolors;
293 $lost++ if ( !defined($color_index{$rgb}) );
298 "$0: Warning: color palette truncated (%d colors ignored)\n", $lost;
304 print pack("Vvv", $magic, $xsize, $ysize);
307 for ( $i = 0 ; $i < 16 ; $i++ ) {
308 if ( defined($colors[$i]) ) {
311 # Padding for unused color entries
312 print pack("CCC", 63*$i/15, 63*$i/15, 63*$i/15);
316 sub output_nybble
($) {
319 if ( !defined($ny) ) {
320 if ( defined($nybble_tmp) ) {
321 $ny = 0; # Force the last byte out
329 if ( defined($nybble_tmp) ) {
330 $ny = ($ny << 4) | $nybble_tmp;
339 sub output_run
($$$) {
340 my($last,$this,$run) = @_;
342 if ( $this != $last ) {
343 output_nybble
($this);
348 output_nybble
($this);
357 output_nybble
($erun);
358 output_nybble
($erun >> 4);
360 output_nybble
($this);
370 for ( $y = 0 ; $y < $ysize ; $y++ ) {
373 for ( $x = 0 ; $x < $xsize ; $x++ ) {
375 $i = $color_index{$rgb} + 0;
379 output_run
($prev, $last, $run);
385 # Output final datum for row; we're always at least one pixel behind
386 output_run
($prev, $last, $run);
387 output_nybble
(undef); # Flush row
390 $pixels = $xsize * $ysize;
391 $size = ($pixels+1)/2;
392 printf STDERR
"%d pixels, %d bytes, (%2.2f%% compression)\n",
393 $pixels, $bytes, 100*($size-$bytes)/$size;