]> git.cworth.org Git - apitrace/blob - image/image_pnm.cpp
image: Non-standard PNM format variant for 4-float images.
[apitrace] / image / image_pnm.cpp
1 /**************************************************************************
2  *
3  * Copyright 2011 Jose Fonseca
4  * Copyright 2008-2010 VMware, Inc.
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26
27
28 #include <assert.h>
29 #include <string.h>
30 #include <stdint.h>
31 #include <stdio.h>
32
33 #include <fstream>
34
35 #include "image.hpp"
36
37
38 namespace image {
39
40 /**
41  * http://en.wikipedia.org/wiki/Netpbm_format
42  * http://netpbm.sourceforge.net/doc/ppm.html
43  * http://netpbm.sourceforge.net/doc/pfm.html
44  */
45 void
46 Image::writePNM(std::ostream &os, const char *comment) const
47 {
48     const char *identifier;
49     unsigned outChannels;
50
51     switch (channelType) {
52     case TYPE_UNORM8:
53         if (channels == 1) {
54             identifier = "P5";
55             outChannels = 1;
56         } else {
57             identifier = "P6";
58             outChannels = 3;
59         }
60         break;
61     case TYPE_FLOAT:
62         if (channels == 1) {
63             identifier = "Pf";
64             outChannels = 1;
65         } else if (channels <= 3) {
66             identifier = "PF";
67             outChannels = 4;
68         } else {
69             // Non-standard extension for 4 floats
70             identifier = "PX";
71             outChannels = 4;
72         }
73         break;
74     default:
75         assert(0);
76     }
77
78     os << identifier << "\n";
79
80     if (comment) {
81         os << "#" << comment << "\n";
82     }
83     os << width << " " << height << "\n";
84
85     if (channelType == TYPE_UNORM8) {
86         os << "255" << "\n";
87     } else {
88         os << "1" << "\n";
89     }
90
91     const unsigned char *row;
92
93     if (channels == outChannels) {
94         /*
95          * Write whole pixel spans straight from the image buffer.
96          */
97
98         for (row = start(); row != end(); row += stride()) {
99             os.write((const char *)row, width*bytesPerPixel);
100         }
101     } else {
102         /*
103          * Need to add/remove channels, one pixel at a time.
104          */
105
106         unsigned char *tmp = new unsigned char[width*outChannels*bytesPerChannel];
107
108         if (channelType == TYPE_UNORM8) {
109             /*
110              * Optimized path for 8bit unorms.
111              */
112
113             if (channels == 4) {
114                 for (row = start(); row != end(); row += stride()) {
115                     const uint32_t *src = (const uint32_t *)row;
116                     uint32_t *dst = (uint32_t *)tmp;
117                     unsigned x;
118                     for (x = 0; x + 4 <= width; x += 4) {
119                         /*
120                          * It's much faster to access dwords than bytes.
121                          *
122                          * FIXME: Big-endian version.
123                          */
124
125                         uint32_t rgba0 = *src++ & 0xffffff;
126                         uint32_t rgba1 = *src++ & 0xffffff;
127                         uint32_t rgba2 = *src++ & 0xffffff;
128                         uint32_t rgba3 = *src++ & 0xffffff;
129                         uint32_t rgb0 = rgba0
130                                       | (rgba1 << 24);
131                         uint32_t rgb1 = (rgba1 >> 8)
132                                       | (rgba2 << 16);
133                         uint32_t rgb2 = (rgba2 >> 16)
134                                       | (rgba3 << 8);
135                         *dst++ = rgb0;
136                         *dst++ = rgb1;
137                         *dst++ = rgb2;
138                     }
139                     for (; x < width; ++x) {
140                         tmp[x*3 + 0] = row[x*4 + 0];
141                         tmp[x*3 + 1] = row[x*4 + 1];
142                         tmp[x*3 + 2] = row[x*4 + 2];
143                     }
144                     os.write((const char *)tmp, width*3);
145                 }
146             } else if (channels == 2) {
147                 for (row = start(); row != end(); row += stride()) {
148                     const unsigned char *src = row;
149                     unsigned char *dst = tmp;
150                     for (unsigned x = 0; x < width; ++x) {
151                         *dst++ = *src++;
152                         *dst++ = *src++;
153                         *dst++ = 0;
154                     }
155                     os.write((const char *)tmp, width*3);
156                 }
157             } else {
158                 assert(0);
159             }
160         } else {
161             /*
162              * General path for float images.
163              */
164
165             unsigned copyChannels = std::min(channels, outChannels);
166
167             assert(channelType == TYPE_FLOAT);
168
169             for (row = start(); row != end(); row += stride()) {
170                 const float *src = (const float *)row;
171                 float *dst = (float *)tmp;
172                 for (unsigned x = 0; x < width; ++x) {
173                     unsigned channel = 0;
174                     for (; channel < copyChannels; ++channel) {
175                         *dst++ = *src++;
176                     }
177                     for (; channel < outChannels; ++channel) {
178                         *dst++ = 0;
179                     }
180                 }
181                 os.write((const char *)tmp, width*outChannels*bytesPerChannel);
182             }
183         }
184
185         delete [] tmp;
186     }
187 }
188
189
190 bool
191 Image::writePNM(const char *filename, const char *comment) const
192 {
193     std::ofstream os(filename, std::ofstream::binary);
194     if (!os) {
195         return false;
196     }
197     writePNM(os, comment);
198     return true;
199 }
200
201
202 /**
203  * Parse PNM header.
204  *
205  * Returns pointer to data start, or NULL on failure.
206  */
207 const char *
208 readPNMHeader(const char *buffer, size_t bufferSize, PNMInfo &info)
209 {
210     info.channels = 0;
211     info.width = 0;
212     info.height = 0;
213
214     const char *currentBuffer = buffer;
215     const char *nextBuffer;
216
217     // parse number of channels
218     char c;
219     int scannedChannels = sscanf(currentBuffer, "P%c\n", &c);
220     if (scannedChannels != 1) { // validate scanning of channels
221         // invalid channel line
222         return NULL;
223     }
224     // convert channel token to number of channels
225     switch (c) {
226     case '5':
227         info.channels = 1;
228         info.channelType = TYPE_UNORM8;
229         break;
230     case '6':
231         info.channels = 3;
232         info.channelType = TYPE_UNORM8;
233         break;
234     case 'f':
235         info.channels = 1;
236         info.channelType = TYPE_FLOAT;
237         break;
238     case 'F':
239         info.channels = 3;
240         info.channelType = TYPE_FLOAT;
241         break;
242     case 'X':
243         info.channels = 4;
244         info.channelType = TYPE_FLOAT;
245         break;
246     default:
247         return NULL;
248     }
249
250     // advance past channel line
251     nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
252     bufferSize -= nextBuffer - currentBuffer;
253     currentBuffer = nextBuffer;
254
255     // skip over optional comment
256     if (*currentBuffer == '#') {
257         // advance past comment line
258         nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
259         bufferSize -= nextBuffer - currentBuffer;
260         currentBuffer = nextBuffer;
261     }
262
263     // parse dimensions of image
264     int scannedDimensions = sscanf(currentBuffer, "%u %u\n", &info.width, &info.height);
265     if (scannedDimensions != 2) { // validate scanning of dimensions
266         // invalid dimension line
267         return NULL;
268     }
269
270     // advance past dimension line
271     nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
272     bufferSize -= nextBuffer - currentBuffer;
273     currentBuffer = nextBuffer;
274
275     // skip scale factor / endianness line
276     nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
277
278     // return start of image data
279     return nextBuffer;
280 }
281
282
283 Image *
284 readPNM(const char *buffer, size_t bufferSize)
285 {
286     PNMInfo info;
287
288     const char *headerEnd = readPNMHeader(buffer, bufferSize, info);
289
290     // if invalid PNM header was encountered, ...
291     if (headerEnd == NULL) {
292         std::cerr << "error: invalid PNM header";
293         return NULL;
294     }
295
296     Image *image = new Image(info.width, info.height, info.channels, false, info.channelType);
297
298     size_t rowBytes = info.width * image->bytesPerPixel;
299     for (unsigned char *row = image->start(); row != image->end(); row += image->stride()) {
300         memcpy(row, headerEnd, rowBytes);
301         headerEnd += rowBytes;
302     }
303
304     return image;
305 }
306
307
308
309 } /* namespace image */