forked from NVIDIA/CUDALibrarySamples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nvJPEGROIDecode.h
703 lines (608 loc) · 23.7 KB
/
nvJPEGROIDecode.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/*
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <string.h> // strcmpi
#ifndef _WIN64
#include <sys/time.h> // timings
#include <unistd.h>
#endif
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <cuda_runtime_api.h>
#include <nvjpeg.h>
#define CHECK_CUDA(call) \
{ \
cudaError_t _e = (call); \
if (_e != cudaSuccess) \
{ \
std::cout << "CUDA Runtime failure: '#" << _e << "' at " << __FILE__ << ":" << __LINE__ << std::endl;\
return EXIT_FAILURE; \
} \
}
#define CHECK_NVJPEG(call) \
{ \
nvjpegStatus_t _e = (call); \
if (_e != NVJPEG_STATUS_SUCCESS) \
{ \
std::cout << "NVJPEG failure: '#" << _e << "' at " << __FILE__ << ":" << __LINE__ << std::endl;\
return EXIT_FAILURE; \
} \
}
int dev_malloc(void **p, size_t s) { return (int)cudaMalloc(p, s); }
int dev_free(void *p) { return (int)cudaFree(p); }
int host_malloc(void** p, size_t s, unsigned int f) { return (int)cudaHostAlloc(p, s, f); }
int host_free(void* p) { return (int)cudaFreeHost(p); }
typedef std::vector<std::string> FileNames;
typedef std::vector<std::vector<char> > FileData;
constexpr int pipeline_stages = 2;
struct decode_per_thread_params {
cudaStream_t stream;
nvjpegJpegState_t dec_state_cpu;
nvjpegJpegState_t dec_state_gpu;
nvjpegBufferPinned_t pinned_buffers[pipeline_stages];
nvjpegBufferDevice_t device_buffer;
nvjpegJpegStream_t jpeg_streams[pipeline_stages];
nvjpegDecodeParams_t nvjpeg_decode_params;
nvjpegJpegDecoder_t nvjpeg_dec_cpu;
nvjpegJpegDecoder_t nvjpeg_dec_gpu;
};
struct decode_params_t {
std::string input_dir;
int batch_size;
int total_images;
int dev;
int warmup;
int num_threads;
int offset_x;
int offset_y;
int roi_width;
int roi_height;
bool roi_on;
int backend_enum;
cudaStream_t global_stream;
nvjpegHandle_t nvjpeg_handle;
std::vector<decode_per_thread_params> nvjpeg_per_thread_data;
nvjpegOutputFormat_t fmt;
bool write_decoded;
std::string output_dir;
};
int create_nvjpeg_data(nvjpegHandle_t& nvjpeg_handle, decode_per_thread_params& params){
static_assert(pipeline_stages >=2, "We need at least two stages in the pipeline to allow buffering of the states, "
"so the re-allocations won't interfere with asynchronous execution.");
// stream for decoding
CHECK_CUDA( cudaStreamCreateWithFlags(¶ms.stream, cudaStreamNonBlocking));
CHECK_NVJPEG(nvjpegDecoderCreate(nvjpeg_handle, NVJPEG_BACKEND_HYBRID, ¶ms.nvjpeg_dec_cpu));
CHECK_NVJPEG(nvjpegDecoderCreate(nvjpeg_handle, NVJPEG_BACKEND_GPU_HYBRID, ¶ms.nvjpeg_dec_gpu));
CHECK_NVJPEG(nvjpegDecoderStateCreate(nvjpeg_handle, params.nvjpeg_dec_cpu, ¶ms.dec_state_cpu));
CHECK_NVJPEG(nvjpegDecoderStateCreate(nvjpeg_handle, params.nvjpeg_dec_gpu, ¶ms.dec_state_gpu));
CHECK_NVJPEG(nvjpegBufferDeviceCreate(nvjpeg_handle, NULL, ¶ms.device_buffer));
for(int i = 0; i < pipeline_stages; i++) {
CHECK_NVJPEG(nvjpegBufferPinnedCreate(nvjpeg_handle, NULL, ¶ms.pinned_buffers[i]));
CHECK_NVJPEG(nvjpegJpegStreamCreate(nvjpeg_handle, ¶ms.jpeg_streams[i]));
}
CHECK_NVJPEG(nvjpegStateAttachDeviceBuffer(params.dec_state_cpu, params.device_buffer));
CHECK_NVJPEG(nvjpegStateAttachDeviceBuffer(params.dec_state_gpu, params.device_buffer));
return EXIT_SUCCESS;
}
int destroy_nvjpeg_data(decode_per_thread_params& params) {
for(int i = 0; i < pipeline_stages; i++) {
CHECK_NVJPEG(nvjpegJpegStreamDestroy(params.jpeg_streams[i]));
CHECK_NVJPEG(nvjpegBufferPinnedDestroy(params.pinned_buffers[i]));
}
CHECK_NVJPEG(nvjpegBufferDeviceDestroy(params.device_buffer));
CHECK_NVJPEG(nvjpegJpegStateDestroy(params.dec_state_cpu));
CHECK_NVJPEG(nvjpegJpegStateDestroy(params.dec_state_gpu));
CHECK_NVJPEG(nvjpegDecoderDestroy(params.nvjpeg_dec_cpu));
CHECK_NVJPEG(nvjpegDecoderDestroy(params.nvjpeg_dec_gpu));
CHECK_CUDA(cudaStreamDestroy(params.stream));
return EXIT_SUCCESS;
}
int read_next_batch(FileNames &image_names, int batch_size,
FileNames::iterator &cur_iter, FileData &raw_data,
std::vector<size_t> &raw_len, FileNames ¤t_names) {
int counter = 0;
while (counter < batch_size) {
if (cur_iter == image_names.end()) {
std::cerr << "Image list is too short to fill the batch, adding files "
"from the beginning of the image list"
<< std::endl;
cur_iter = image_names.begin();
}
if (image_names.size() == 0) {
std::cerr << "No valid images left in the input list, exit" << std::endl;
return EXIT_FAILURE;
}
// Read an image from disk.
std::ifstream input(cur_iter->c_str(),
std::ios::in | std::ios::binary | std::ios::ate);
if (!(input.is_open())) {
std::cerr << "Cannot open image: " << *cur_iter
<< ", removing it from image list" << std::endl;
image_names.erase(cur_iter);
continue;
}
// Get the size
std::streamsize file_size = input.tellg();
input.seekg(0, std::ios::beg);
// resize if buffer is too small
if (raw_data[counter].size() < file_size) {
raw_data[counter].resize(file_size);
}
if (!input.read(raw_data[counter].data(), file_size)) {
std::cerr << "Cannot read from file: " << *cur_iter
<< ", removing it from image list" << std::endl;
image_names.erase(cur_iter);
continue;
}
raw_len[counter] = file_size;
current_names[counter] = *cur_iter;
counter++;
cur_iter++;
}
return EXIT_SUCCESS;
}
// prepare buffers for RGBi output format
int prepare_buffers(FileData &file_data, std::vector<size_t> &file_len,
std::vector<int> &img_width, std::vector<int> &img_height,
std::vector<nvjpegImage_t> &ibuf,
std::vector<nvjpegImage_t> &isz, FileNames ¤t_names,
decode_params_t ¶ms) {
int widths[NVJPEG_MAX_COMPONENT];
int heights[NVJPEG_MAX_COMPONENT];
int channels;
nvjpegChromaSubsampling_t subsampling;
for (int i = 0; i < file_data.size(); i++) {
CHECK_NVJPEG(nvjpegGetImageInfo(
params.nvjpeg_handle, (unsigned char *)file_data[i].data(), file_len[i],
&channels, &subsampling, widths, heights));
img_width[i] = widths[0];
img_height[i] = heights[0];
// check if the ROI exceeds the image boundaries
// If within ROI, set the buffer size to match the ROI
if (params.roi_on && (widths[0] > params.offset_x + params.roi_width && heights[0] > params.offset_y + params.roi_height)){
widths[0] = params.roi_width;
heights[0] = params.roi_height;
}
std::cout << "Processing: " << current_names[i] << std::endl;
std::cout << "Image is " << channels << " channels." << std::endl;
for (int c = 0; c < channels; c++) {
std::cout << "Channel #" << c << " size: " << widths[c] << " x "
<< heights[c] << std::endl;
}
switch (subsampling) {
case NVJPEG_CSS_444:
std::cout << "YUV 4:4:4 chroma subsampling" << std::endl;
break;
case NVJPEG_CSS_440:
std::cout << "YUV 4:4:0 chroma subsampling" << std::endl;
break;
case NVJPEG_CSS_422:
std::cout << "YUV 4:2:2 chroma subsampling" << std::endl;
break;
case NVJPEG_CSS_420:
std::cout << "YUV 4:2:0 chroma subsampling" << std::endl;
break;
case NVJPEG_CSS_411:
std::cout << "YUV 4:1:1 chroma subsampling" << std::endl;
break;
case NVJPEG_CSS_410:
std::cout << "YUV 4:1:0 chroma subsampling" << std::endl;
break;
case NVJPEG_CSS_GRAY:
std::cout << "Grayscale JPEG " << std::endl;
break;
case NVJPEG_CSS_UNKNOWN:
std::cout << "Unknown chroma subsampling" << std::endl;
return EXIT_FAILURE;
}
int mul = 1;
// in the case of interleaved RGB output, write only to single channel, but
// 3 samples at once
if (params.fmt == NVJPEG_OUTPUT_RGBI || params.fmt == NVJPEG_OUTPUT_BGRI) {
channels = 1;
mul = 3;
}
// in the case of rgb create 3 buffers with sizes of original image
else if (params.fmt == NVJPEG_OUTPUT_RGB ||
params.fmt == NVJPEG_OUTPUT_BGR) {
channels = 3;
widths[1] = widths[2] = widths[0];
heights[1] = heights[2] = heights[0];
}
// realloc output buffer if required
for (int c = 0; c < channels; c++) {
int aw = mul * widths[c];
int ah = heights[c];
int sz = aw * ah;
ibuf[i].pitch[c] = aw;
if (sz > isz[i].pitch[c]) {
if (ibuf[i].channel[c]) {
CHECK_CUDA(cudaFree(ibuf[i].channel[c]));
}
CHECK_CUDA(cudaMalloc((void**)&ibuf[i].channel[c], sz));
isz[i].pitch[c] = sz;
}
}
}
return EXIT_SUCCESS;
}
int release_buffers(std::vector<nvjpegImage_t> &ibuf) {
for (int i = 0; i < ibuf.size(); i++) {
for (int c = 0; c < NVJPEG_MAX_COMPONENT; c++)
if (ibuf[i].channel[c]) CHECK_CUDA(cudaFree(ibuf[i].channel[c]));
}
return EXIT_SUCCESS;
}
// *****************************************************************************
// reading input directory to file list
// -----------------------------------------------------------------------------
int readInput(const std::string &sInputPath, std::vector<std::string> &filelist)
{
int error_code = 1;
struct stat s;
if( stat(sInputPath.c_str(), &s) == 0 )
{
if( s.st_mode & S_IFREG )
{
filelist.push_back(sInputPath);
}
else if( s.st_mode & S_IFDIR )
{
// processing each file in directory
DIR *dir_handle;
struct dirent *dir;
dir_handle = opendir(sInputPath.c_str());
std::vector<std::string> filenames;
if (dir_handle)
{
error_code = 0;
while ((dir = readdir(dir_handle)) != NULL)
{
if (dir->d_type == DT_REG)
{
std::string sFileName = sInputPath + dir->d_name;
filelist.push_back(sFileName);
}
else if (dir->d_type == DT_DIR)
{
std::string sname = dir->d_name;
if (sname != "." && sname != "..")
{
readInput(sInputPath + sname + "/", filelist);
}
}
}
closedir(dir_handle);
}
else
{
std::cout << "Cannot open input directory: " << sInputPath << std::endl;
return error_code;
}
}
else
{
std::cout << "Cannot open input: " << sInputPath << std::endl;
return error_code;
}
}
else
{
std::cout << "Cannot find input path " << sInputPath << std::endl;
return error_code;
}
return 0;
}
// *****************************************************************************
// check for inputDirExists
// -----------------------------------------------------------------------------
int inputDirExists(const char *pathname) {
struct stat info;
if (stat(pathname, &info) != 0) {
return 0; // Directory does not exists
} else if (info.st_mode & S_IFDIR) {
// is a directory
return 1;
} else {
// is not a directory
return 0;
}
}
// *****************************************************************************
// check for getInputDir
// -----------------------------------------------------------------------------
int getInputDir(std::string &input_dir, const char *executable_path) {
int found = 0;
if (executable_path != 0) {
std::string executable_name = std::string(executable_path);
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
// Windows path delimiter
size_t delimiter_pos = executable_name.find_last_of('\\');
executable_name.erase(0, delimiter_pos + 1);
if (executable_name.rfind(".exe") != std::string::npos) {
// we strip .exe, only if the .exe is found
executable_name.resize(executable_name.size() - 4);
}
#else
// Linux & OSX path delimiter
size_t delimiter_pos = executable_name.find_last_of('/');
executable_name.erase(0, delimiter_pos + 1);
#endif
// Search in default paths for input images.
std::string pathname = "";
const char *searchPath[] = {
"./images"};
for (unsigned int i = 0; i < sizeof(searchPath) / sizeof(char *); ++i) {
std::string pathname(searchPath[i]);
size_t executable_name_pos = pathname.find("<executable_name>");
// If there is executable_name variable in the searchPath
// replace it with the value
if (executable_name_pos != std::string::npos) {
pathname.replace(executable_name_pos, strlen("<executable_name>"),
executable_name);
}
if (inputDirExists(pathname.c_str())) {
input_dir = pathname + "/";
found = 1;
break;
}
}
}
return found;
}
// write bmp, input - RGB, device
int writeBMP(const char *filename, const unsigned char *d_chanR, int pitchR,
const unsigned char *d_chanG, int pitchG,
const unsigned char *d_chanB, int pitchB, int width, int height) {
unsigned int headers[13];
FILE *outfile;
int extrabytes;
int paddedsize;
int x;
int y;
int n;
int red, green, blue;
std::vector<unsigned char> vchanR(height * width);
std::vector<unsigned char> vchanG(height * width);
std::vector<unsigned char> vchanB(height * width);
unsigned char *chanR = vchanR.data();
unsigned char *chanG = vchanG.data();
unsigned char *chanB = vchanB.data();
CHECK_CUDA(cudaMemcpy2D(chanR, (size_t)width, d_chanR, (size_t)pitchR,
width, height, cudaMemcpyDeviceToHost));
CHECK_CUDA(cudaMemcpy2D(chanG, (size_t)width, d_chanG, (size_t)pitchR,
width, height, cudaMemcpyDeviceToHost));
CHECK_CUDA(cudaMemcpy2D(chanB, (size_t)width, d_chanB, (size_t)pitchR,
width, height, cudaMemcpyDeviceToHost));
extrabytes =
4 - ((width * 3) % 4); // How many bytes of padding to add to each
// horizontal line - the size of which must
// be a multiple of 4 bytes.
if (extrabytes == 4) extrabytes = 0;
paddedsize = ((width * 3) + extrabytes) * height;
// Headers...
// Note that the "BM" identifier in bytes 0 and 1 is NOT included in these
// "headers".
headers[0] = paddedsize + 54; // bfSize (whole file size)
headers[1] = 0; // bfReserved (both)
headers[2] = 54; // bfOffbits
headers[3] = 40; // biSize
headers[4] = width; // biWidth
headers[5] = height; // biHeight
// Would have biPlanes and biBitCount in position 6, but they're shorts.
// It's easier to write them out separately (see below) than pretend
// they're a single int, especially with endian issues...
headers[7] = 0; // biCompression
headers[8] = paddedsize; // biSizeImage
headers[9] = 0; // biXPelsPerMeter
headers[10] = 0; // biYPelsPerMeter
headers[11] = 0; // biClrUsed
headers[12] = 0; // biClrImportant
if (!(outfile = fopen(filename, "wb"))) {
std::cerr << "Cannot open file: " << filename << std::endl;
return 1;
}
//
// Headers begin...
// When printing ints and shorts, we write out 1 character at a time to avoid
// endian issues.
//
fprintf(outfile, "BM");
for (n = 0; n <= 5; n++) {
fprintf(outfile, "%c", headers[n] & 0x000000FF);
fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
fprintf(outfile, "%c", (headers[n] & (unsigned int)0xFF000000) >> 24);
}
// These next 4 characters are for the biPlanes and biBitCount fields.
fprintf(outfile, "%c", 1);
fprintf(outfile, "%c", 0);
fprintf(outfile, "%c", 24);
fprintf(outfile, "%c", 0);
for (n = 7; n <= 12; n++) {
fprintf(outfile, "%c", headers[n] & 0x000000FF);
fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
fprintf(outfile, "%c", (headers[n] & (unsigned int)0xFF000000) >> 24);
}
//
// Headers done, now write the data...
//
for (y = height - 1; y >= 0;
y--) // BMP image format is written from bottom to top...
{
for (x = 0; x <= width - 1; x++) {
red = chanR[y * width + x];
green = chanG[y * width + x];
blue = chanB[y * width + x];
if (red > 255) red = 255;
if (red < 0) red = 0;
if (green > 255) green = 255;
if (green < 0) green = 0;
if (blue > 255) blue = 255;
if (blue < 0) blue = 0;
// Also, it's written in (b,g,r) format...
fprintf(outfile, "%c", blue);
fprintf(outfile, "%c", green);
fprintf(outfile, "%c", red);
}
if (extrabytes) // See above - BMP lines must be of lengths divisible by 4.
{
for (n = 1; n <= extrabytes; n++) {
fprintf(outfile, "%c", 0);
}
}
}
fclose(outfile);
return 0;
}
// write bmp, input - RGB, device
int writeBMPi(const char *filename, const unsigned char *d_RGB, int pitch,
int width, int height) {
unsigned int headers[13];
FILE *outfile;
int extrabytes;
int paddedsize;
int x;
int y;
int n;
int red, green, blue;
std::vector<unsigned char> vchanRGB(height * width * 3);
unsigned char *chanRGB = vchanRGB.data();
CHECK_CUDA(cudaMemcpy2D(chanRGB, (size_t)width * 3, d_RGB, (size_t)pitch,
width * 3, height, cudaMemcpyDeviceToHost));
extrabytes =
4 - ((width * 3) % 4); // How many bytes of padding to add to each
// horizontal line - the size of which must
// be a multiple of 4 bytes.
if (extrabytes == 4) extrabytes = 0;
paddedsize = ((width * 3) + extrabytes) * height;
// Headers...
// Note that the "BM" identifier in bytes 0 and 1 is NOT included in these
// "headers".
headers[0] = paddedsize + 54; // bfSize (whole file size)
headers[1] = 0; // bfReserved (both)
headers[2] = 54; // bfOffbits
headers[3] = 40; // biSize
headers[4] = width; // biWidth
headers[5] = height; // biHeight
// Would have biPlanes and biBitCount in position 6, but they're shorts.
// It's easier to write them out separately (see below) than pretend
// they're a single int, especially with endian issues...
headers[7] = 0; // biCompression
headers[8] = paddedsize; // biSizeImage
headers[9] = 0; // biXPelsPerMeter
headers[10] = 0; // biYPelsPerMeter
headers[11] = 0; // biClrUsed
headers[12] = 0; // biClrImportant
if (!(outfile = fopen(filename, "wb"))) {
std::cerr << "Cannot open file: " << filename << std::endl;
return 1;
}
//
// Headers begin...
// When printing ints and shorts, we write out 1 character at a time to avoid
// endian issues.
//
fprintf(outfile, "BM");
for (n = 0; n <= 5; n++) {
fprintf(outfile, "%c", headers[n] & 0x000000FF);
fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
fprintf(outfile, "%c", (headers[n] & (unsigned int)0xFF000000) >> 24);
}
// These next 4 characters are for the biPlanes and biBitCount fields.
fprintf(outfile, "%c", 1);
fprintf(outfile, "%c", 0);
fprintf(outfile, "%c", 24);
fprintf(outfile, "%c", 0);
for (n = 7; n <= 12; n++) {
fprintf(outfile, "%c", headers[n] & 0x000000FF);
fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
fprintf(outfile, "%c", (headers[n] & (unsigned int)0xFF000000) >> 24);
}
//
// Headers done, now write the data...
//
for (y = height - 1; y >= 0;
y--) // BMP image format is written from bottom to top...
{
for (x = 0; x <= width - 1; x++) {
red = chanRGB[(y * width + x) * 3];
green = chanRGB[(y * width + x) * 3 + 1];
blue = chanRGB[(y * width + x) * 3 + 2];
if (red > 255) red = 255;
if (red < 0) red = 0;
if (green > 255) green = 255;
if (green < 0) green = 0;
if (blue > 255) blue = 255;
if (blue < 0) blue = 0;
// Also, it's written in (b,g,r) format...
fprintf(outfile, "%c", blue);
fprintf(outfile, "%c", green);
fprintf(outfile, "%c", red);
}
if (extrabytes) // See above - BMP lines must be of lengths divisible by 4.
{
for (n = 1; n <= extrabytes; n++) {
fprintf(outfile, "%c", 0);
}
}
}
fclose(outfile);
return 0;
}
// *****************************************************************************
// parse parameters
// -----------------------------------------------------------------------------
int findParamIndex(const char **argv, int argc, const char *parm) {
int count = 0;
int index = -1;
for (int i = 0; i < argc; i++) {
if (strncmp(argv[i], parm, 100) == 0) {
index = i;
count++;
}
}
if (count == 0 || count == 1) {
return index;
} else {
std::cout << "Error, parameter " << parm
<< " has been specified more than once, exiting\n"
<< std::endl;
return -1;
}
return -1;
}