forked from kisakata/rawtoaces
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacesrender.cpp
executable file
·1732 lines (1468 loc) · 54.7 KB
/
acesrender.cpp
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2013 Academy of Motion Picture Arts and Sciences
// ("A.M.P.A.S."). Portions contributed by others as indicated.
// All rights reserved.
//
// A worldwide, royalty-free, non-exclusive right to copy, modify, create
// derivatives, and use, in source and binary forms, is hereby granted,
// subject to acceptance of this license. Performance of any of the
// aforementioned acts indicates acceptance to be bound by the following
// terms and conditions:
//
// * Copies of source code, in whole or in part, must retain the
// above copyright notice, this list of conditions and the
// Disclaimer of Warranty.
//
// * Use in binary form must retain the above copyright notice,
// this list of conditions and the Disclaimer of Warranty in the
// documentation and/or other materials provided with the distribution.
//
// * Nothing in this license shall be deemed to grant any rights to
// trademarks, copyrights, patents, trade secrets or any other
// intellectual property of A.M.P.A.S. or any contributors, except
// as expressly stated herein.
//
// * Neither the name "A.M.P.A.S." nor the name of any other
// contributors to this software may be used to endorse or promote
// products derivative of or based on this software without express
// prior written permission of A.M.P.A.S. or the contributors, as
// appropriate.
//
// This license shall be construed pursuant to the laws of the State of
// California, and any disputes related thereto shall be subject to the
// jurisdiction of the courts therein.
//
// Disclaimer of Warranty: THIS SOFTWARE IS PROVIDED BY A.M.P.A.S. AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO
// EVENT SHALL A.M.P.A.S., OR ANY CONTRIBUTORS OR DISTRIBUTORS, BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, RESITUTIONARY,
// 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.
//
// WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE ACADEMY
// SPECIFICALLY DISCLAIMS ANY REPRESENTATIONS OR WARRANTIES WHATSOEVER
// RELATED TO PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS IN THE ACADEMY
// COLOR ENCODING SYSTEM, OR APPLICATIONS THEREOF, HELD BY PARTIES OTHER
// THAN A.M.P.A.S., WHETHER DISCLOSED OR UNDISCLOSED.
///////////////////////////////////////////////////////////////////////////
#include "acesrender.h"
// =====================================================================
// Prepare the matching between string flags and single character flag
//
// inputs:
// N/A
//
// outputs:
// N/A : keys should be prepared and loaded
void create_key ( unordered_map < string, char >& keys ) {
keys["--help"] = 'I';
keys["--version"] = 'V';
keys["--cameras"] = 'T';
keys["--wb-method"] = 'R';
keys["--mat-method"] = 'p';
keys["--headroom"] = 'M';
keys["--valid-illums"] = 'z';
keys["--valid-cameras"] = 'Q';
keys["-c"] = 'c';
keys["-C"] = 'C';
keys["-P"] = 'P';
keys["-K"] = 'K';
keys["-k"] = 'k';
keys["-S"] = 'S';
keys["-n"] = 'n';
keys["-H"] = 'H';
keys["-t"] = 't';
keys["-j"] = 'j';
keys["-W"] = 'W';
keys["-b"] = 'b';
keys["-q"] = 'q';
keys["-h"] = 'h';
keys["-f"] = 'f';
keys["-m"] = 'm';
keys["-s"] = 's';
keys["-G"] = 'G';
keys["-B"] = 'B';
keys["-v"] = 'v';
keys["-F"] = 'F';
keys["-d"] = 'd';
keys["-E"] = 'E';
keys["-I"] = 'I';
keys["-V"] = 'V';
};
// =====================================================================
// Print usage / help message
//
// inputs:
// const char * : name of the program (i.e., rawtoaces)
//
// outputs:
// N/A
void usage ( const char *prog ) {
printf ( "%s - convert RAW digital camera files to ACES\n", prog);
printf ( "\n");
printf ( "Usage:\n");
printf ( " %s file ...\n", prog );
printf ( " %s [options] file\n", prog );
printf ( " %s --help\n", prog );
printf ( " %s --version\n", prog );
printf ( "\n");
printf ("IDT options:\n"
" --help Show this screen\n"
" --version Show version\n"
" --wb-method [0-4] White balance factor calculation method\n"
" 0=white balance using file metadata \n"
" 1=white balance using user specified illuminant [str] \n"
" 2=Average the whole image for white balance\n"
" 3=Average a grey box for white balance <x y w h>\n"
" 4=Use custom white balance <r g b g>\n"
" (default = 0)\n"
" --mat-method [0-2] IDT matrix calculation method\n"
" 0=Calculate matrix from camera spec sens\n"
" 1=Use file metadata color matrix\n"
" 2=Use adobe coeffs included in libraw\n"
// Future feature ? " 3=Use custom matrix <m1r m1g m1b m2r m2g m2b m3r m3g m3b>\n"
" (default = 0)\n"
" (default = /usr/local/include/rawtoaces/data/camera)\n"
" --headroom float Set highlight headroom factor (default = 6.0)\n"
" --cameras Show a list of supported cameras/models by LibRaw\n"
" --valid-illums Show a list of illuminants\n"
" --valid-cameras Show a list of cameras/models with available\n"
" spectral sensitivity datasets\n"
"\n"
"Raw conversion options:\n"
" -c float Set adjust maximum threshold (default = 0.75)\n"
" -C <r b> Correct chromatic aberration\n"
" -P <file> Fix the dead pixels listed in this file\n"
" -K <file> Subtract dark frame (16-bit raw PGM)\n"
" -k <num> Set the darkness level\n"
" -S <num> Set the saturation level\n"
" -n <num> Set threshold for wavelet denoising\n"
" -H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild) (default = 0)\n"
" -t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)\n"
" -j Don't stretch or rotate raw pixels\n"
" -W Don't automatically brighten the image\n"
" -b <num> Adjust brightness (default = 1.0)\n"
" -q [0-3] Set the interpolation quality\n"
" -h Half-size color image (twice as fast as \"-q 0\")\n"
" -f Interpolate RGGB as four colors\n"
" -m <num> Apply a 3x3 median filter to R-G and B-G\n"
" -s [0..N-1] Select one raw image from input file\n"
" -G Use green_matching() filter\n"
" -B <x y w h> Use cropbox\n"
"\n"
"Benchmarking options:\n"
" -v Verbose: print progress messages (repeated -v will add verbosity)\n"
" -F Use FILE I/O instead of streambuf API\n"
" -d Detailed timing report\n"
#ifndef WIN32
" -E Use mmap()-ed buffer instead of plain FILE I/O\n"
#endif
);
exit(-1);
};
// =====================================================================
// Defaul Constructor
AcesRender::AcesRender() {
_idt = new Idt();
_image = new libraw_processed_image_t();
_rawProcessor = new LibRawAces();
_idtm.resize(3);
_wbv.resize(3);
_catm.resize(3);
FORI(3) {
_idtm[i].resize(3);
_catm[i].resize(3);
_wbv[i] = 1.0;
FORJ(3) _idtm[i][j] = neutral3[i][j];
FORJ(3) _catm[i][j] = neutral3[i][j];
}
}
// =====================================================================
// Defaul Destructor
AcesRender::~AcesRender() {
if (_pathToRaw) {
delete _pathToRaw;
_pathToRaw = nullptr;
}
if (_idt) {
delete _idt;
_idt = nullptr;
}
if (_image) {
delete _image;
_image = nullptr;
}
if (_rawProcessor) {
delete _rawProcessor;
_rawProcessor = nullptr;
}
vector < vector < double > >().swap(_idtm);
vector < vector < double > >().swap(_catm);
vector < double >().swap(_wbv);
vector < string >().swap(_illuminants);
vector < string >().swap(_cameras);
}
// =====================================================================
// Get the only instance of the "AcesRender" class
//
// inputs:
// N/A
//
// outputs:
// static AcesRender & : the referece to the only instance by calling
// the private getPrivateInstance() function
AcesRender & AcesRender::getInstance(){
return getPrivateInstance();
}
// =====================================================================
// Initialize the single instance of the "AcesRender" class privately
//
// inputs:
// N/A
//
// outputs:
// static AcesRender & : the referece to the only instance
// of "AcesRender" class
AcesRender & AcesRender::getPrivateInstance(){
mutex mtx;
mtx.lock();
static AcesRender acesrender;
mtx.unlock();
return acesrender;
}
// =====================================================================
// Operator = overloading in "AcesRender" class
//
// inputs:
// const AcesRender & : acesrender
//
// outputs:
// const AcesRender & : current instance filled with data from
// acesrender
const AcesRender & AcesRender::operator=( const AcesRender & acesrender ) {
if ( this != &acesrender ) {
clearVM(_idtm);
clearVM(_catm);
clearVM(_wbv);
clearVM(_illuminants);
clearVM(_cameras);
if ( _idt != nullptr )
delete _idt;
_idt = (Idt *) malloc(sizeof(Idt));
memcpy(_idt, acesrender._idt, sizeof(Idt));
if ( _rawProcessor != nullptr )
delete _rawProcessor;
_rawProcessor = (LibRawAces *) malloc(sizeof(LibRawAces));
memcpy((void*)_rawProcessor, (void*)acesrender._rawProcessor, sizeof(LibRawAces));
if ( _image != nullptr )
delete _image;
_image = (libraw_processed_image_t *) malloc(sizeof(libraw_processed_image_t));
memcpy(_image, acesrender._image, sizeof(libraw_processed_image_t));
_idtm = acesrender._idtm;
_catm = acesrender._catm;
_wbv = acesrender._wbv;
_illuminants = acesrender._illuminants;
_cameras = acesrender._cameras;
_opts = acesrender._opts;
}
return *this;
}
// =====================================================================
// Initialize the process by first setting up default values for "_opts"
// and some flags for "_rawProcessor"
//
// inputs:
// struct dataPath : data path of the processed environment variable
//
// outputs:
// N/A : _opts will be set up by the default values;
// A few parameters of "_rawProcessor" (imgdata.params)
// will be given a set of initial values
void AcesRender::initialize ( const dataPath & dp ) {
_opts.use_bigfile = 0;
_opts.use_timing = 0;
_opts.use_illum = 0;
_opts.use_mul = 0;
_opts.verbosity = 0;
_opts.mat_method = matMethod0;
_opts.wb_method = wbMethod0;
_opts.highlight = 0;
_opts.scale = 6.0;
_opts.highlight = 0;
_opts.get_illums = 0;
_opts.get_cameras = 0;
_opts.get_libraw_cameras = 0;
#ifndef WIN32
_opts.iobuffer = 0;
#endif
struct stat st;
FORI ( dp.paths.size() ) {
if ( !stat( (dp.paths)[i].c_str(), &st ) )
_opts.envPaths.push_back((dp.paths)[i]);
}
#ifndef WIN32
_opts.msize = 0;
_opts.use_mmap=0;
#endif
#ifdef OUT
#undef OUT
#endif
#define OUT _rawProcessor->imgdata.params
// General set-up for _rawProcessor->imgdata.params
OUT.output_color = 5;
OUT.output_bps = 16;
OUT.highlight = 0;
// OUT.use_camera_matrix = 0;
OUT.gamm[0] = 1.0;
OUT.gamm[1] = 1.0;
OUT.no_auto_bright = 1;
OUT.use_camera_wb = 0;
OUT.use_auto_wb = 0;
}
// =====================================================================
// Configure settings by taking in user specified options
//
// inputs:
// int argc : number of user input
// char * argv[] : an array of user input
//
// outputs:
// N/A : _opts will be ready by digesting the user input;
// _rawProcessor (imgdata.params) will take initial
// set of values from user inputs
int AcesRender::configureSettings ( int argc, char * argv[] )
{
#ifdef OUT
#undef OUT
#endif
#define OUT _rawProcessor->imgdata.params
char *cp, *sp;
int arg;
argv[argc] = (char *)"";
for ( arg = 1; arg < argc; )
{
string key(argv[arg]);
if ( key[0] != '-' ) {
break;
}
arg++;
static unordered_map < string, char > keys;
create_key ( keys );
char opt = keys[key];
if (!opt) {
fprintf (stderr,"\nNon-recognizable flag - \"%s\"\n", key.c_str());
exit(-1);
}
if (( cp = strchr ( sp = (char*)"HcnbksStqmBC", opt )) != 0 ) {
for (int i=0; i < "111111111142"[cp-sp]-'0'; i++) {
if (!isdigit(argv[arg+i][0]))
{
fprintf ( stderr, "\nError: Non-numeric argument to "
"\"%s\"\n", key.c_str() );
exit(-1);
}
}
}
switch ( opt )
{
case 'I': usage( argv[0] ); break;
case 'V': printf ( "%s\n", VERSION ); break;
case 'v': _opts.verbosity++; break;
case 'G': OUT.green_matching = 1; break;
case 'c': OUT.adjust_maximum_thr = (float)atof(argv[arg++]); break;
case 'n': OUT.threshold = (float)atof(argv[arg++]); break;
case 'b': OUT.bright = (float)atof(argv[arg++]); break;
case 'P': OUT.bad_pixels = argv[arg++]; break;
case 'K': OUT.dark_frame = argv[arg++]; break;
case 'C': {
OUT.aber[0] = 1.0 / atof(argv[arg++]);
OUT.aber[2] = 1.0 / atof(argv[arg++]);
break;
}
case 'k': OUT.user_black = atoi(argv[arg++]); break;
case 'S': OUT.user_sat = atoi(argv[arg++]); break;
case 't': OUT.user_flip = atoi(argv[arg++]); break;
case 'q': OUT.user_qual = atoi(argv[arg++]); break;
case 'm': OUT.med_passes = atoi(argv[arg++]); break;
case 'h': OUT.half_size = 1;
// no break: "-h" implies "-f"
case 'f': OUT.four_color_rgb = 1; break;
case 'B': FORI(4) OUT.cropbox[i] = atoi(argv[arg++]); break;
case 'j': OUT.use_fuji_rotate = 0; break;
case 'W': OUT.no_auto_bright = 1; break;
case 'F': _opts.use_bigfile = 1; break;
case 'd': _opts.use_timing = 1; break;
case 'Q': _opts.get_cameras = 1; {
// gather a list of cameras supported
gatherSupportedCameras();
vector < string > clist = getSupportedCameras();
printf("\nThe following cameras' sensitivity data is available:\n\n");
FORI(clist.size()) printf("%s \n", clist[i].c_str());
break;
}
case 'z': _opts.get_illums = 1; {
// gather a list of illuminants supported
gatherSupportedIllums();
vector < string > ilist = getSupportedIllums();
printf("\nThe following illuminants are available:\n\n");
FORI(ilist.size()) printf("%s \n", ilist[i].c_str());
break;
}
case 'T': _opts.get_libraw_cameras = 1; {
// print a list of cameras supported by LibRaw
printLibRawCameras();
break;
}
case 'M': _opts.scale = atof(argv[arg++]); break;
case 'H': {
OUT.highlight = atoi(argv[arg++]);
_opts.highlight = OUT.highlight;
break;
}
case 'p': {
_opts.mat_method = matMethods_t(atoi(argv[arg++]));
if ( _opts.mat_method > 2
|| _opts.mat_method < 0 ) {
fprintf (stderr, "\nError: Invalid argument to "
"\"%s\" \n", key.c_str());
exit(-1);
}
break;
}
case 'R': {
std::string flag = std::string(argv[arg]);
FORI ( flag.size() ) {
if ( !isdigit (flag[i]) ) {
fprintf (stderr, "\nNon-recognizable argument to "
"\"--wb-method\".\n");
exit(-1);
}
}
_opts.wb_method = wbMethods_t(atoi(argv[arg++]));
// 1
if ( _opts.wb_method == wbMethod1 ) {
_opts.use_illum = 1;
_opts.illumType = static_cast<char * >(argv[arg++]);
lowerCase ( _opts.illumType );
if ( !isValidCT ( string ( _opts.illumType )) ) {
fprintf( stderr, "\nError: white balance method 1 requires a valid "
"illuminant (e.g., D60, 3200K) to be specified\n" );
exit(-1);
}
}
// 3
if ( _opts.wb_method == wbMethod3 ) {
FORI(4) {
if ( !isdigit(argv[arg][0]) )
{
fprintf ( stderr, "\nError: Non-numeric argument to "
"\"%s %i\" \n",
key.c_str(),
_opts.wb_method );
exit(-1);
}
OUT.greybox[i] = static_cast<float>(atof(argv[arg++]));
}
}
// 4
else if ( _opts.wb_method == wbMethod4 ) {
_opts.use_mul = 1;
FORI(4) {
if ( !isdigit(argv[arg][0]) )
{
fprintf (stderr, "\nError: Non-numeric argument to "
"\"%s %i\" \n",
key.c_str(),
_opts.wb_method );
exit(-1);
}
OUT.user_mul[i] = static_cast<float> (atof(argv[arg++]));
}
}
else if ( _opts.wb_method > 4 || _opts.wb_method < 0 ) {
fprintf ( stderr, "\nError: Invalid argument to \"%s\" \n",
key.c_str());
exit(-1);
}
break;
}
#ifndef WIN32
case 'E': _opts.use_mmap = 1; break;
#endif
default:
fprintf ( stderr, "\nError: Unknown option \"%s\".\n",
key.c_str() );
exit(-1);
}
}
return arg;
}
// =====================================================================
// Set processed image buffer from libraw
//
// inputs:
// libraw_processed_image_t : processed RAW through libraw
//
// outputs:
// N/A : _image will point to the address of image
void AcesRender::setPixels ( libraw_processed_image_t * image ) {
assert(image);
if ( _image != nullptr ) delete _image;
_image = image;
//// Strange because memcpying on libraw_processed_image_t
// will generate an error
// if (_image != nullptr ) delete _image;
// _image = (libraw_processed_image_t *) malloc(sizeof(libraw_processed_image_t));
// memcpy(_image, image, sizeof(libraw_processed_image_t));
}
// =====================================================================
// Gather supported Illuminants by reading from JSON files
//
// inputs:
// N/A
//
// outputs:
// N/A : _illuminants be filled
void AcesRender::gatherSupportedIllums ( ) {
if (_illuminants.size() != 0)
_illuminants.clear();
_illuminants.push_back( "Day-light (e.g., D60, D6025)" );
_illuminants.push_back( "Blackbody (e.g., 3200K)" );
std::unordered_map < string, int > record;
FORI (_opts.envPaths.size()) {
vector<string> iFiles = openDir ( static_cast< string >( (_opts.envPaths)[i] )
+"/illuminant" );
for ( vector<string>::iterator file = iFiles.begin(); file != iFiles.end(); ++file ) {
string path( *file );
try
{
ptree pt;
read_json (path, pt);
string tmp = pt.get<string>( "header.illuminant" );
if ( record.find(tmp) != record.end() )
continue;
else {
_illuminants.push_back (tmp);
record[tmp] = 1;
}
}
catch( std::exception const & e )
{
std::cerr << e.what() << std::endl;
}
}
}
}
// =====================================================================
// Gather supported cameras by reading from JSON files
//
// inputs:
// N/A
//
// outputs:
// N/A : _cameras be filled
void AcesRender::gatherSupportedCameras ( ) {
if (_cameras.size() != 0)
_cameras.clear();
std::unordered_map < string, int > record;
FORI (_opts.envPaths.size()) {
vector<string> iFiles = openDir ( static_cast< string >( (_opts.envPaths)[i] )
+"/camera" );
for ( vector<string>::iterator file = iFiles.begin(); file != iFiles.end(); ++file ) {
string path( *file );
try
{
ptree pt;
read_json (path, pt);
string tmp = pt.get<string>( "header.manufacturer" );
tmp += ( " / " + pt.get<string>( "header.model" ) );
if ( record.find(tmp) != record.end() )
continue;
else {
_cameras.push_back (tmp);
record[tmp] = 1;
}
}
catch( std::exception const & e )
{
std::cerr << e.what() << std::endl;
}
}
}
}
// =====================================================================
// Open the RAW file from the path to the file
//
// inputs:
// const char * : path to the raw file
//
// outputs:
// int : "1" means raw file successfully opened;
// "0" means error when opening the file
int AcesRender::openRawPath ( const char * pathToRaw ) {
assert ( pathToRaw != nullptr );
#ifndef WIN32
// void *iobuffer=0;
struct stat st;
if ( _opts.use_mmap )
{
int file = open ( pathToRaw, O_RDONLY );
if( file < 0 )
{
fprintf ( stderr, "\nError: Cannot open %s: %s\n\n",
pathToRaw, strerror(errno) );
_opts.ret = 0;
return 0;
}
if( fstat ( file, &st ) )
{
fprintf ( stderr, "\nError: Cannot stat %s: %s\n\n",
pathToRaw, strerror(errno) );
close( file );
_opts.ret = 0;
return 0;
}
int pgsz = getpagesize();
_opts.msize = (( st.st_size+pgsz-1 ) / pgsz ) * pgsz;
_opts.iobuffer = mmap ( NULL, size_t(_opts.msize), PROT_READ, MAP_PRIVATE, file, 0 );
if( !_opts.iobuffer )
{
fprintf ( stderr, "\nError: Cannot mmap %s: %s\n\n",
pathToRaw, strerror(errno) );
close( file );
_opts.ret = 0;
return 0;
}
close( file );
if (( _opts.ret = _rawProcessor->open_buffer( _opts.iobuffer,st.st_size ) != LIBRAW_SUCCESS ))
{
fprintf ( stderr, "\nError: Cannot open_buffer %s: %s\n\n",
pathToRaw, libraw_strerror(_opts.ret) );
}
}
else
#endif
{
if ( _opts.use_bigfile )
_opts.ret = _rawProcessor->open_file ( pathToRaw, 1 );
else
_opts.ret = _rawProcessor->open_file ( pathToRaw );
}
unpack ( pathToRaw );
return _opts.ret;
}
// =====================================================================
// Unpack the RAW file based on the path to the file (after openRawPath)
//
// inputs:
// const char * : path to the raw file
//
// outputs:
// int : "1" means raw file successfully unpacked;
// "0" means error when unpacking the file
int AcesRender::unpack ( const char * pathToRaw ) {
assert ( _opts.ret == LIBRAW_SUCCESS && pathToRaw != nullptr );
if (( _opts.ret = _rawProcessor->unpack() ) != LIBRAW_SUCCESS )
{
fprintf ( stderr, "\nError: Cannot unpack %s: %s\n\n",
pathToRaw, libraw_strerror (_opts.ret) );
}
return _opts.ret;
}
// =====================================================================
// Read camera spectral sensitivity data from path
//
// inputs:
// const char * : camera spectral sensitivity path
// (either in the environment variable of
// "AMPAS_CAMERA_SENSITIVITIES_PATH"
// such as "/usr/local/include/rawtoaces/data/camera"
// or specified by users)
// libraw_iparams_t : main parameters read from RAW
//
// outputs:
// int : "1" means loading/injecting camera spectral
// sensitivity data successfully;
// "0" means error in reading/injecting data
int AcesRender::fetchCameraSenPath( const libraw_iparams_t & P )
{
int readC = 0;
FORI ( _opts.envPaths.size() ) {
vector<string> cFiles = openDir ( static_cast< string >( (_opts.envPaths)[i] )
+"/camera" );
for ( vector<string>::iterator file = cFiles.begin( ); file != cFiles.end( ); ++file ) {
string fn( *file );
if ( fn.find(".json") == std::string::npos )
continue;
readC = _idt->loadCameraSpst( fn, P.make, P.model );
if ( readC ) return 1;
}
}
return readC;
}
// =====================================================================
// Fetch light source data to calcuate white balance coefficients
//
// inputs:
// const char * : type of light source ("unknown" if not specified)
// (in the environment variable of "AMPAS_ILLUMINANT_PATH"
// such as "/usr/local/include/rawtoaces/data/Illuminant")
//
// outputs:
// int : "1" means loading/injecting light source datasets successfully,
// "0" means error / no illumiant data has been loaded
int AcesRender::fetchIlluminant ( const char * illumType )
{
vector <string> paths;
FORI ( _opts.envPaths.size() ) {
vector <string> iFiles = openDir ( (_opts.envPaths)[i] + "/illuminant" );
for ( vector<string>::iterator file = iFiles.begin(); file != iFiles.end(); ++file ) {
string fn( *file );
if ( fn.find(".json") == std::string::npos )
continue;
paths.push_back(fn);
}
}
return _idt->loadIlluminant( paths, static_cast<string >(illumType) );
}
// =====================================================================
// Calculate IDT matrix from camera spectral sensitivity data and the
// selected or specified light source data. THe best White balance
// coefficients will be generated in the process of obtaining IDT.
//
// inputs:
// libraw_iparams_t : main parameters read from RAW
// libraw_colordata_t : color information from RAW
//
// outputs:
// int : "1" means IDT matrix generated;
// "0" means error in calculation.
int AcesRender::prepareIDT ( const libraw_iparams_t & P, float * M )
{
// _rawProcessor->imgdata.idata
int read = fetchCameraSenPath( P );
if ( !read ) {
fprintf( stderr, "\nError: No matching cameras found. "
"Please use other options for "
"\"--mat-method\" and/or \"--wb-method\".\n");
exit (-1);
}
// loading training data (190 patches)
_idt->loadTrainingData ( static_cast < string > ( FILEPATH )
+"training/training_spectral.json" );
// loading color matching function
_idt->loadCMF ( static_cast < string > ( FILEPATH ) \
+"cmf/cmf_1931.json" );
_idt->setVerbosity(_opts.verbosity);
if ( _opts.illumType )
_idt->chooseIllumType( _opts.illumType, _opts.highlight );
else {
vector < double > mulV (M, M+3);
_idt->chooseIllumSrc ( mulV, _opts.highlight );
}
if ( _opts.verbosity > 1 )
printf ( "Regressing IDT matrix coefficients ...\n" );
if ( _idt->calIDT() ) {
_idtm = _idt->getIDT();
_wbv = _idt->getWB();
return 1;
}
return 0;
}
// =====================================================================
// Calculate just white balance coefficients from camera spectral
// sensitivity data and the best or specified light source data.
// IDT matrix will not be calculated here, as curve-fitting may
// take more time
//
// inputs:
// libraw_iparams_t : main parameters read from RAW
// libraw_colordata_t : color information from RAW
//
// outputs:
// int : "1" means white balance coefficients generated;
// "0" means error during calculation
int AcesRender::prepareWB ( const libraw_iparams_t & P )
{
int read = fetchCameraSenPath ( P );
if ( !read ) {
fprintf( stderr, "\nError: No matching cameras found. "
"Please use other options for "
"\"--wb-method\".\n");
exit (-1);
}
assert(_opts.illumType);
read = fetchIlluminant( _opts.illumType );
if( !read ) {
fprintf( stderr, "\nError: No matching light source. "
"Please find available options by "
"\"rawtoaces --valid-illum\".\n");
exit (-1);
}
else
{
// loading training data (190 patches)
_idt->loadTrainingData ( static_cast < string > ( FILEPATH )
+"/training/training_spectral.json" );
// loading color matching function
_idt->loadCMF ( static_cast < string > ( FILEPATH )
+"/cmf/cmf_1931.json" );
// choose the best light source based on
// as-shot white balance coefficients
_idt->chooseIllumType ( _opts.illumType, _opts.highlight );
if ( _opts.verbosity > 1 ) {
printf ( "Calculating White Balance Coefficients "
"from Spectral Sensitivity ...\n" );
printf ( "Applying Calculated White Balance "
"Coefficients ...\n" );
}
_wbv = _idt->getWB();
return 1;
}
return 0;
}
// =====================================================================
// Conduct dcraw process on the RAW
//
// inputs:
// const char * : path to the raw file
//
// outputs:
// int : "1" means raw file successfully pre-processed;
// "0" means error when pre-processing the file
int AcesRender::dcraw ( ) {
assert ( _opts.ret == LIBRAW_SUCCESS );
if ( LIBRAW_SUCCESS != ( _opts.ret = _rawProcessor->dcraw_process() ) ) {
fprintf ( stderr, "Error: Cannot do postpocessing: %s\n\n",
libraw_strerror(_opts.ret) );
_opts.ret = errno;
if ( LIBRAW_FATAL_ERROR( _opts.ret ) )
exit(1);
}
return _opts.ret;
}
// =====================================================================
// Preprocess the RAW file based on the path to the file
//
// inputs:
// const char * : path to the raw file
//
// outputs:
// int : "1" means raw file successfully pre-processed;
// "0" means error when pre-processing the file
int AcesRender::preprocessRaw ( const char * path ) {
assert ( path != nullptr );
size_t len = strlen(path);
_pathToRaw = (char *) malloc(len+1);
memset(_pathToRaw, 0x0, len);
memcpy(_pathToRaw, path, len);
_pathToRaw[len] = '\0';