Determine image stack format and filename by loading _files.xml
[bookreader.git] / BookReaderIA / datanode / BookReaderImages.php
1 <?php
2
3 /*
4 Copyright(c)2008 Internet Archive. Software license AGPL version 3.
5
6 This file is part of BookReader.
7
8     BookReader is free software: you can redistribute it and/or modify
9     it under the terms of the GNU Affero General Public License as published by
10     the Free Software Foundation, either version 3 of the License, or
11     (at your option) any later version.
12
13     BookReader is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU Affero General Public License for more details.
17
18     You should have received a copy of the GNU Affero General Public License
19     along with BookReader.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 $MIMES = array('jpg' => 'image/jpeg',
23                'png' => 'image/png');
24                
25 $exiftool = '/petabox/sw/books/exiftool/exiftool';
26
27 $zipPath  = $_REQUEST['zip'];
28 $file     = $_REQUEST['file'];
29
30 /*
31  * Approach:
32  * 
33  * Get info about requested image (input)
34  * Get info about requested output format
35  * Determine processing parameters
36  * Process image
37  * Return image data
38  * Clean up temporary files
39  */
40  
41 function getUnzipCommand($zipPath, $file)
42 {
43     return 'unzip -p ' . 
44         escapeshellarg($zipPath) .
45         ' ' . escapeshellarg($file);
46 }
47  
48 /*
49  * Get the image width, height and depth from a jp2 file in zip.
50  */
51 function getImageSizeAndDepth($zipPath, $file)
52 {
53     global $exiftool;
54     
55     # $$$ will exiftool work for *all* of our images?
56     $cmd = getUnzipCommand($zipPath, $file)
57         . ' | '. $exiftool . ' -s -s -s -ImageWidth -ImageHeight -BitsPerComponent -';
58     exec($cmd, $output);
59     
60     preg_match('/^(\d+)/', $output[2], $groups);
61     $bits = intval($groups[1]);
62     
63     $retval = Array('width' => intval($output[0]), 'height' => intval($output[1]),
64         'bits' => $bits);    
65     return $retval;
66 }
67
68 // Unfortunately kakadu requires us to know a priori if the
69 // output file should be .ppm or .pgm.  By decompressing to
70 // .bmp kakadu will write a file we can consistently turn into
71 // .pnm.  Really kakadu should support .pnm as the file output
72 // extension and automatically write ppm or pgm format as
73 // appropriate.
74 $decompressToBmp = true;
75 if ($decompressToBmp) {
76   $stdoutLink = '/tmp/stdout.bmp';
77 } else {
78   $stdoutLink = '/tmp/stdout.ppm';
79 }
80
81 if (isset($_REQUEST['ext'])) {
82   $ext = $_REQUEST['ext'];
83 } else {
84   // Default to jpg
85   $ext = 'jpg';
86 }
87
88 $fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION));
89
90 // Rotate is currently only supported for jp2 since it does not add server load
91 $allowedRotations = array("0", "90", "180", "270");
92 $rotate = $_REQUEST['rotate'];
93 if ( !in_array($rotate, $allowedRotations) ) {
94     $rotate = "0";
95 }
96
97 // Image conversion options
98 $pngOptions = '';
99 $jpegOptions = '-quality 75';
100
101 // The pbmreduce reduction factor produces an image with dimension 1/n
102 // The kakadu reduction factor produceds an image with dimension 1/(2^n)
103
104 if (isset($_REQUEST['height'])) {
105     $ratio = floatval($_REQUEST['origHeight']) / floatval($_REQUEST['height']);
106     if ($ratio <= 2) {
107         $scale = 2;
108         $powReduce = 1;    
109     } else if ($ratio <= 4) {
110         $scale = 4;
111         $powReduce = 2;
112     } else {
113         //$powReduce = 3; //too blurry!
114         $scale = 2;
115         $powReduce = 1;
116     }
117
118 } else {
119     $scale = $_REQUEST['scale'];
120     if (1 >= $scale) {
121         $scale = 1;
122         $powReduce = 0;
123     } else if (2 == $scale) {
124         $powReduce = 1;
125     } else if (4 == $scale) {
126         $powReduce = 2;
127     } else if (8 == $scale) {
128         $powReduce = 3;
129     } else if (16 == $scale) {
130         $powReduce = 4;
131     } else if (32 == $scale) {
132         $powReduce = 5;
133     } else {
134         // $$$ Leaving this in as default though I'm not sure why it is...
135         $scale = 8;
136         $powReduce = 3;
137     }
138 }
139
140 if (!file_exists($stdoutLink)) 
141 {  
142   system('ln -s /dev/stdout ' . $stdoutLink);  
143 }
144
145
146 putenv('LD_LIBRARY_PATH=/petabox/sw/lib/kakadu');
147
148 $unzipCmd  = getUnzipCommand($zipPath, $file);
149         
150 if ('jp2' == $fileExt) {
151     $decompressCmd = 
152         " | /petabox/sw/bin/kdu_expand -no_seek -quiet -reduce $powReduce -rotate $rotate -i /dev/stdin -o " . $stdoutLink;
153     if ($decompressToBmp) {
154         $decompressCmd .= ' | bmptopnm ';
155     }
156     
157 } else if ('tif' == $fileExt) {
158     // We need to create a temporary file for tifftopnm since it cannot
159     // work on a pipe (the file must be seekable).
160     // We use the BookReaderTiff prefix to give a hint in case things don't
161     // get cleaned up.
162     $tempFile = tempnam("/tmp", "BookReaderTiff");
163     
164     if (1 != $scale) {
165         if (onPowerNode()) {
166             $pbmReduce = ' | pnmscale -reduce ' . $scale;
167         } else {
168             $pbmReduce = ' | pnmscale -nomix -reduce ' . $scale;
169         }
170     } else {
171         $pbmReduce = '';
172     }
173     
174     $decompressCmd = 
175         ' > ' . $tempFile . ' ; tifftopnm ' . $tempFile . ' 2>/dev/null' . $pbmReduce;
176
177 } else {
178     BRfatal('Unknown source file extension: ' . $fileExt);
179 }
180        
181 // Non-integer scaling is currently disabled on the cluster
182 // if (isset($_REQUEST['height'])) {
183 //     $cmd .= " | pnmscale -height {$_REQUEST['height']} ";
184 // }
185
186 if ('jpg' == $ext) {
187     $compressCmd = ' | pnmtojpeg ' . $jpegOptions;
188 } else if ('png' == $ext) {
189     $compressCmd = ' | pnmtopng ' . $pngOptions;
190 }
191
192 $cmd = $unzipCmd . $decompressCmd . $compressCmd;
193
194 //print $cmd;
195
196
197 header('Content-type: ' . $MIMES[$ext]);
198 header('Cache-Control: max-age=15552000');
199 passthru ($cmd); # cmd returns image data
200
201 if (isset($tempFile)) {
202   unlink($tempFile);
203 }
204
205 function BRFatal($string) {
206     echo "alert('$string')\n";
207     die(-1);
208 }
209
210 // Returns true if using a power node
211 function onPowerNode() {
212     exec("lspci | fgrep -c Realtek", $output, $return);
213     if ("0" != $output[0]) {
214         return true;
215     } else {
216         exec("egrep -q AMD /proc/cpuinfo", $output, $return);
217         if ($return == 0) {
218             return true;
219         }
220     }
221     return false;
222 }
223
224
225 ?>
226