Fix CVEs for opencv 2.4
[platform/upstream/opencv.git] / modules / highgui / src / grfmt_pxm.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42
43 #include "precomp.hpp"
44 #include "utils.hpp"
45 #include "grfmt_pxm.hpp"
46 #include <iostream>
47
48 namespace cv
49 {
50
51 ///////////////////////// P?M reader //////////////////////////////
52
53 static int ReadNumber(RLByteStream& strm, int maxdigits = 0)
54 {
55     int code;
56     int64 val = 0;
57     int digits = 0;
58
59     code = strm.getByte();
60
61     while (!isdigit(code))
62     {
63         if (code == '#' )
64         {
65             do
66             {
67                 code = strm.getByte();
68             }
69             while (code != '\n' && code != '\r');
70             code = strm.getByte();
71         }
72         else if (isspace(code))
73         {
74             while (isspace(code))
75                 code = strm.getByte();
76         }
77         else
78         {
79 #if 1
80             CV_Error_(CV_StsError, ("PXM: Unexpected code in ReadNumber(): 0x%x (%d)", code, code));
81 #else
82             code = strm.getByte();
83 #endif
84         }
85     }
86
87     do
88     {
89         val = val*10 + (code - '0');
90         CV_Assert(val <= INT_MAX && "PXM: ReadNumber(): result is too large");
91         digits++;
92         if (maxdigits != 0 && digits >= maxdigits) break;
93         code = strm.getByte();
94     }
95     while (isdigit(code));
96
97     return (int)val;
98 }
99
100
101 PxMDecoder::PxMDecoder()
102 {
103     m_offset = -1;
104     m_buf_supported = true;
105 }
106
107
108 PxMDecoder::~PxMDecoder()
109 {
110     close();
111 }
112
113 size_t PxMDecoder::signatureLength() const
114 {
115     return 3;
116 }
117
118 bool PxMDecoder::checkSignature( const string& signature ) const
119 {
120     return signature.size() >= 3 && signature[0] == 'P' &&
121            '1' <= signature[1] && signature[1] <= '6' &&
122            isspace(signature[2]);
123 }
124
125 ImageDecoder PxMDecoder::newDecoder() const
126 {
127     return new PxMDecoder;
128 }
129
130 void PxMDecoder::close()
131 {
132     m_strm.close();
133 }
134
135
136 bool PxMDecoder::readHeader()
137 {
138     bool result = false;
139
140     if( !m_buf.empty() )
141     {
142         if( !m_strm.open(m_buf) )
143             return false;
144     }
145     else if( !m_strm.open( m_filename ))
146         return false;
147
148     try
149     {
150         int code = m_strm.getByte();
151         if( code != 'P' )
152             throw RBS_BAD_HEADER;
153
154         code = m_strm.getByte();
155         switch( code )
156         {
157         case '1': case '4': m_bpp = 1; break;
158         case '2': case '5': m_bpp = 8; break;
159         case '3': case '6': m_bpp = 24; break;
160         default: throw RBS_BAD_HEADER;
161         }
162
163         m_binary = code >= '4';
164         m_type = m_bpp > 8 ? CV_8UC3 : CV_8UC1;
165
166         m_width = ReadNumber(m_strm);
167         m_height = ReadNumber(m_strm);
168
169         m_maxval = m_bpp == 1 ? 1 : ReadNumber(m_strm);
170         if( m_maxval > 65535 )
171             throw RBS_BAD_HEADER;
172
173         //if( m_maxval > 255 ) m_binary = false; nonsense
174         if( m_maxval > 255 )
175             m_type = CV_MAKETYPE(CV_16U, CV_MAT_CN(m_type));
176
177         if( m_width > 0 && m_height > 0 && m_maxval > 0 && m_maxval < (1 << 16))
178         {
179             m_offset = m_strm.getPos();
180             result = true;
181         }
182     }
183     catch (const cv::Exception&)
184     {
185         throw;
186     }
187     catch (...)
188     {
189         std::cerr << "PXM::readHeader(): unknown C++ exception" << std::endl << std::flush;
190         throw;
191     }
192
193     if( !result )
194     {
195         m_offset = -1;
196         m_width = m_height = -1;
197         m_strm.close();
198     }
199     return result;
200 }
201
202
203 bool  PxMDecoder::readData( Mat& img )
204 {
205     int color = img.channels() > 1;
206     uchar* data = img.data;
207     int step = (int)img.step;
208     PaletteEntry palette[256];
209     bool   result = false;
210     const int bit_depth = CV_ELEM_SIZE1(m_type)*8;
211     const int src_pitch = (m_width*m_bpp*(bit_depth/8) + 7) / 8;
212
213     int  nch = CV_MAT_CN(m_type);
214     int  width3 = m_width*nch;
215
216     if( m_offset < 0 || !m_strm.isOpened())
217         return false;
218
219     uchar gray_palette[256] = {0};
220
221     // create LUT for converting colors
222     if( bit_depth == 8 )
223     {
224         CV_Assert(m_maxval < 256);
225
226         for (int i = 0; i <= m_maxval; i++)
227             gray_palette[i] = (uchar)((i*255/m_maxval)^(m_bpp == 1 ? 255 : 0));
228
229         FillGrayPalette( palette, m_bpp==1 ? 1 : 8 , m_bpp == 1 );
230     }
231
232     try
233     {
234         m_strm.setPos( m_offset );
235
236         switch( m_bpp )
237         {
238         ////////////////////////// 1 BPP /////////////////////////
239         case 1:
240             CV_Assert(CV_MAT_DEPTH(m_type) == CV_8U);
241             if( !m_binary )
242             {
243                 AutoBuffer<uchar> _src(m_width);
244                 uchar* src = _src;
245
246                 for (int y = 0; y < m_height; y++, data += step)
247                 {
248                     for (int x = 0; x < m_width; x++)
249                         src[x] = ReadNumber(m_strm, 1) != 0;
250
251                     if( color )
252                         FillColorRow8( data, src, m_width, palette );
253                     else
254                         FillGrayRow8( data, src, m_width, gray_palette );
255                 }
256             }
257             else
258             {
259                 AutoBuffer<uchar> _src(src_pitch);
260                 uchar* src = _src;
261
262                 for (int y = 0; y < m_height; y++, data += step)
263                 {
264                     m_strm.getBytes( src, src_pitch );
265
266                     if( color )
267                         FillColorRow1( data, src, m_width, palette );
268                     else
269                         FillGrayRow1( data, src, m_width, gray_palette );
270                 }
271             }
272             result = true;
273             break;
274
275         ////////////////////////// 8 BPP /////////////////////////
276         case 8:
277         case 24:
278         {
279             AutoBuffer<uchar> _src(std::max<size_t>(width3*2, src_pitch));
280             uchar* src = _src;
281
282             for (int y = 0; y < m_height; y++, data += step)
283             {
284                 if( !m_binary )
285                 {
286                     for (int x = 0; x < width3; x++)
287                     {
288                         int code = ReadNumber( m_strm, INT_MAX );
289                         if( (unsigned)code > (unsigned)m_maxval ) code = m_maxval;
290                         if( bit_depth == 8 )
291                             src[x] = gray_palette[code];
292                         else
293                             ((ushort *)src)[x] = (ushort)code;
294                     }
295                 }
296                 else
297                 {
298                     m_strm.getBytes( src, src_pitch );
299                     if( bit_depth == 16 && !isBigEndian() )
300                     {
301                         for (int x = 0; x < width3; x++)
302                         {
303                             uchar v = src[x * 2];
304                             src[x * 2] = src[x * 2 + 1];
305                             src[x * 2 + 1] = v;
306                         }
307                     }
308                 }
309
310                 if( img.depth() == CV_8U && bit_depth == 16 )
311                 {
312                     for (int x = 0; x < width3; x++)
313                     {
314                         int v = ((ushort *)src)[x];
315                         src[x] = (uchar)(v >> 8);
316                     }
317                 }
318
319                 if( m_bpp == 8 ) // image has one channel
320                 {
321                     if( color )
322                     {
323                         if( img.depth() == CV_8U ) {
324                             uchar *d = data, *s = src, *end = src + m_width;
325                             for( ; s < end; d += 3, s++)
326                                 d[0] = d[1] = d[2] = *s;
327                         } else {
328                             ushort *d = (ushort *)data, *s = (ushort *)src, *end = ((ushort *)src) + m_width;
329                             for( ; s < end; s++, d += 3)
330                                 d[0] = d[1] = d[2] = *s;
331                         }
332                     }
333                     else
334                         memcpy( data, src, m_width*(bit_depth/8) );
335                 }
336                 else
337                 {
338                     if( color )
339                     {
340                         if( img.depth() == CV_8U )
341                             icvCvt_RGB2BGR_8u_C3R( src, 0, data, 0, cvSize(m_width,1) );
342                         else
343                             icvCvt_RGB2BGR_16u_C3R( (ushort *)src, 0, (ushort *)data, 0, cvSize(m_width,1) );
344                     }
345                     else if( img.depth() == CV_8U )
346                         icvCvt_BGR2Gray_8u_C3C1R( src, 0, data, 0, cvSize(m_width,1), 2 );
347                     else
348                         icvCvt_BGRA2Gray_16u_CnC1R( (ushort *)src, 0, (ushort *)data, 0, cvSize(m_width,1), 3, 2 );
349                 }
350             }
351             result = true;
352             break;
353         }
354         default:
355             CV_Error(CV_StsError, "m_bpp is not supported");
356         }
357     }
358     catch (const cv::Exception&)
359     {
360         throw;
361     }
362     catch (...)
363     {
364         std::cerr << "PXM::readData(): unknown exception" << std::endl << std::flush;
365         throw;
366     }
367
368     return result;
369 }
370
371
372 //////////////////////////////////////////////////////////////////////////////////////////
373
374 PxMEncoder::PxMEncoder()
375 {
376     m_description = "Portable image format (*.pbm;*.pgm;*.ppm;*.pxm;*.pnm)";
377     m_buf_supported = true;
378 }
379
380
381 PxMEncoder::~PxMEncoder()
382 {
383 }
384
385
386 ImageEncoder  PxMEncoder::newEncoder() const
387 {
388     return new PxMEncoder;
389 }
390
391
392 bool  PxMEncoder::isFormatSupported( int depth ) const
393 {
394     return depth == CV_8U || depth == CV_16U;
395 }
396
397
398 bool  PxMEncoder::write( const Mat& img, const vector<int>& params )
399 {
400     bool isBinary = true;
401
402     int  width = img.cols, height = img.rows;
403     int  _channels = img.channels(), depth = (int)img.elemSize1()*8;
404     int  channels = _channels > 1 ? 3 : 1;
405     int  fileStep = width*(int)img.elemSize();
406     int  x, y;
407
408     for( size_t i = 0; i < params.size(); i += 2 )
409         if( params[i] == CV_IMWRITE_PXM_BINARY )
410             isBinary = params[i+1] != 0;
411
412     WLByteStream strm;
413
414     if( m_buf )
415     {
416         if( !strm.open(*m_buf) )
417             return false;
418         int t = CV_MAKETYPE(img.depth(), channels);
419         m_buf->reserve( alignSize(256 + (isBinary ? fileStep*height :
420             ((t == CV_8UC1 ? 4 : t == CV_8UC3 ? 4*3+2 :
421             t == CV_16UC1 ? 6 : 6*3+2)*width+1)*height), 256));
422     }
423     else if( !strm.open(m_filename) )
424         return false;
425
426     int  lineLength;
427     int  bufferSize = 128; // buffer that should fit a header
428
429     if( isBinary )
430         lineLength = width * (int)img.elemSize();
431     else
432         lineLength = (6 * channels + (channels > 1 ? 2 : 0)) * width + 32;
433
434     if( bufferSize < lineLength )
435         bufferSize = lineLength;
436
437     AutoBuffer<char> _buffer(bufferSize);
438     char* buffer = _buffer;
439
440     // write header;
441     sprintf( buffer, "P%c\n# Generated by OpenCV %s\n%d %d\n%d\n",
442              '2' + (channels > 1 ? 1 : 0) + (isBinary ? 3 : 0),
443              CV_VERSION,
444              width, height, (1 << depth) - 1 );
445
446     strm.putBytes( buffer, (int)strlen(buffer) );
447
448     for( y = 0; y < height; y++ )
449     {
450         uchar* data = img.data + img.step*y;
451         if( isBinary )
452         {
453             if( _channels == 3 )
454             {
455                 if( depth == 8 )
456                     icvCvt_BGR2RGB_8u_C3R( (uchar*)data, 0,
457                         (uchar*)buffer, 0, cvSize(width,1) );
458                 else
459                     icvCvt_BGR2RGB_16u_C3R( (ushort*)data, 0,
460                         (ushort*)buffer, 0, cvSize(width,1) );
461             }
462
463             // swap endianness if necessary
464             if( depth == 16 && !isBigEndian() )
465             {
466                 if( _channels == 1 )
467                     memcpy( buffer, data, fileStep );
468                 for( x = 0; x < width*channels*2; x += 2 )
469                 {
470                     uchar v = buffer[x];
471                     buffer[x] = buffer[x + 1];
472                     buffer[x + 1] = v;
473                 }
474             }
475             strm.putBytes( (channels > 1 || depth > 8) ? buffer : (char*)data, fileStep );
476         }
477         else
478         {
479             char* ptr = buffer;
480
481             if( channels > 1 )
482             {
483                 if( depth == 8 )
484                 {
485                     for( x = 0; x < width*channels; x += channels )
486                     {
487                         sprintf( ptr, "% 4d", data[x + 2] );
488                         ptr += 4;
489                         sprintf( ptr, "% 4d", data[x + 1] );
490                         ptr += 4;
491                         sprintf( ptr, "% 4d", data[x] );
492                         ptr += 4;
493                         *ptr++ = ' ';
494                         *ptr++ = ' ';
495                     }
496                 }
497                 else
498                 {
499                     for( x = 0; x < width*channels; x += channels )
500                     {
501                         sprintf( ptr, "% 6d", ((ushort *)data)[x + 2] );
502                         ptr += 6;
503                         sprintf( ptr, "% 6d", ((ushort *)data)[x + 1] );
504                         ptr += 6;
505                         sprintf( ptr, "% 6d", ((ushort *)data)[x] );
506                         ptr += 6;
507                         *ptr++ = ' ';
508                         *ptr++ = ' ';
509                     }
510                 }
511             }
512             else
513             {
514                 if( depth == 8 )
515                 {
516                     for( x = 0; x < width; x++ )
517                     {
518                         sprintf( ptr, "% 4d", data[x] );
519                         ptr += 4;
520                     }
521                 }
522                 else
523                 {
524                     for( x = 0; x < width; x++ )
525                     {
526                         sprintf( ptr, "% 6d", ((ushort *)data)[x] );
527                         ptr += 6;
528                     }
529                 }
530             }
531
532             *ptr++ = '\n';
533
534             strm.putBytes( buffer, (int)(ptr - buffer) );
535         }
536     }
537
538     strm.close();
539     return true;
540 }
541
542 }