]> git.cworth.org Git - apitrace/blob - image/image_pnm.cpp
image: Support reading PFM 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 {
66             identifier = "PF";
67             outChannels = 3;
68         }
69         break;
70     default:
71         assert(0);
72     }
73
74     os << identifier << "\n";
75
76     if (comment) {
77         os << "#" << comment << "\n";
78     }
79     os << width << " " << height << "\n";
80
81     if (channelType == TYPE_UNORM8) {
82         os << "255" << "\n";
83     }
84
85     const unsigned char *row;
86
87     if (channels == outChannels) {
88         /*
89          * Write whole pixel spans straight from the image buffer.
90          */
91
92         for (row = start(); row != end(); row += stride()) {
93             os.write((const char *)row, width*bytesPerPixel);
94         }
95     } else {
96         /*
97          * Need to add/remove channels, one pixel at a time.
98          */
99
100         unsigned char *tmp = new unsigned char[width*bytesPerPixel];
101
102         if (channelType == TYPE_UNORM8) {
103             /*
104              * Optimized path for 8bit unorms.
105              */
106
107             if (channels == 4) {
108                 for (row = start(); row != end(); row += stride()) {
109                     const uint32_t *src = (const uint32_t *)row;
110                     uint32_t *dst = (uint32_t *)tmp;
111                     unsigned x;
112                     for (x = 0; x + 4 <= width; x += 4) {
113                         /*
114                          * It's much faster to access dwords than bytes.
115                          *
116                          * FIXME: Big-endian version.
117                          */
118
119                         uint32_t rgba0 = *src++ & 0xffffff;
120                         uint32_t rgba1 = *src++ & 0xffffff;
121                         uint32_t rgba2 = *src++ & 0xffffff;
122                         uint32_t rgba3 = *src++ & 0xffffff;
123                         uint32_t rgb0 = rgba0
124                                       | (rgba1 << 24);
125                         uint32_t rgb1 = (rgba1 >> 8)
126                                       | (rgba2 << 16);
127                         uint32_t rgb2 = (rgba2 >> 16)
128                                       | (rgba3 << 8);
129                         *dst++ = rgb0;
130                         *dst++ = rgb1;
131                         *dst++ = rgb2;
132                     }
133                     for (; x < width; ++x) {
134                         tmp[x*3 + 0] = row[x*4 + 0];
135                         tmp[x*3 + 1] = row[x*4 + 1];
136                         tmp[x*3 + 2] = row[x*4 + 2];
137                     }
138                     os.write((const char *)tmp, width*3);
139                 }
140             } else if (channels == 2) {
141                 for (row = start(); row != end(); row += stride()) {
142                     const unsigned char *src = row;
143                     unsigned char *dst = tmp;
144                     for (unsigned x = 0; x < width; ++x) {
145                         *dst++ = *src++;
146                         *dst++ = *src++;
147                         *dst++ = 0;
148                     }
149                     os.write((const char *)tmp, width*3);
150                 }
151             } else {
152                 assert(0);
153             }
154         } else {
155             /*
156              * General path for float images.
157              */
158
159             assert(channelType == TYPE_FLOAT);
160
161             for (row = start(); row != end(); row += stride()) {
162                 const float *src = (const float *)row;
163                 float *dst = (float *)tmp;
164                 for (unsigned x = 0; x < width; ++x) {
165                     unsigned channel = 0;
166                     for (; channel < channels; ++channel) {
167                         *dst++ = *src++;
168                     }
169                     for (; channel < channels; ++channel) {
170                         *dst++ = 0;
171                     }
172                 }
173                 os.write((const char *)tmp, width*bytesPerPixel);
174             }
175         }
176
177         delete [] tmp;
178     }
179 }
180
181
182 bool
183 Image::writePNM(const char *filename, const char *comment) const
184 {
185     std::ofstream os(filename, std::ofstream::binary);
186     if (!os) {
187         return false;
188     }
189     writePNM(os, comment);
190     return true;
191 }
192
193
194 /**
195  * Parse PNM header.
196  *
197  * Returns pointer to data start, or NULL on failure.
198  */
199 const char *
200 readPNMHeader(const char *buffer, size_t bufferSize, PNMInfo &info)
201 {
202     info.channels = 0;
203     info.width = 0;
204     info.height = 0;
205
206     const char *currentBuffer = buffer;
207     const char *nextBuffer;
208
209     // parse number of channels
210     char c;
211     int scannedChannels = sscanf(currentBuffer, "P%c\n", &c);
212     if (scannedChannels != 1) { // validate scanning of channels
213         // invalid channel line
214         return NULL;
215     }
216     // convert channel token to number of channels
217     switch (c) {
218     case '5':
219         info.channels = 1;
220         info.channelType = TYPE_UNORM8;
221         break;
222     case '6':
223         info.channels = 3;
224         info.channelType = TYPE_UNORM8;
225         break;
226     case 'f':
227         info.channels = 1;
228         info.channelType = TYPE_FLOAT;
229         break;
230     case 'F':
231         info.channels = 3;
232         info.channelType = TYPE_FLOAT;
233         break;
234     default:
235         return NULL;
236     }
237
238     // advance past channel line
239     nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
240     bufferSize -= nextBuffer - currentBuffer;
241     currentBuffer = nextBuffer;
242
243     // skip over optional comment
244     if (*currentBuffer == '#') {
245         // advance past comment line
246         nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
247         bufferSize -= nextBuffer - currentBuffer;
248         currentBuffer = nextBuffer;
249     }
250
251     // parse dimensions of image
252     int scannedDimensions = sscanf(currentBuffer, "%u %u\n", &info.width, &info.height);
253     if (scannedDimensions != 2) { // validate scanning of dimensions
254         // invalid dimension line
255         return NULL;
256     }
257
258     // advance past dimension line
259     nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
260     bufferSize -= nextBuffer - currentBuffer;
261     currentBuffer = nextBuffer;
262
263     if (info.channelType == TYPE_UNORM8) {
264         // skip over "255\n" at end of header
265         nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1;
266     }
267
268     // return start of image data
269     return nextBuffer;
270 }
271
272
273 Image *
274 readPNM(const char *buffer, size_t bufferSize)
275 {
276     PNMInfo info;
277
278     const char *headerEnd = readPNMHeader(buffer, bufferSize, info);
279
280     // if invalid PNM header was encountered, ...
281     if (headerEnd == NULL) {
282         std::cerr << "error: invalid PNM header";
283         return NULL;
284     }
285
286     Image *image = new Image(info.width, info.height, info.channels, false, info.channelType);
287
288     size_t rowBytes = info.width * image->bytesPerPixel;
289     for (unsigned char *row = image->start(); row != image->end(); row += image->stride()) {
290         memcpy(row, headerEnd, rowBytes);
291         headerEnd += rowBytes;
292     }
293
294     return image;
295 }
296
297
298
299 } /* namespace image */