-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcr2hdr.c
3684 lines (3163 loc) · 129 KB
/
cr2hdr.c
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
/**
* Post-process CR2 images obtained with the Dual ISO module
* (deinterlace, blend the two exposures, output a 16-bit DNG with much cleaner shadows)
*
* Technical details: https://dl.dropboxusercontent.com/u/4124919/bleeding-edge/isoless/dual_iso.pdf
*/
/*
* Copyright (C) 2013 Magic Lantern Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#define EV_RESOLUTION 65536
static int is_bright[4];
#define BRIGHT_ROW (is_bright[y % 4])
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
// #include "../../src/raw.h"
// #include "../../src/chdk-dng.h"
#include "raw.h"
#include "imageio_dng.h"
#include "qsort.h" /* much faster than standard C qsort */
#include "wirth.h" /* fast median, generic implementation (also kth_smallest) */
#include "optmed.h" /* fast median for small common array sizes (3, 7, 9...) */
#include "dcraw-bridge.h"
#include "exiftool-bridge.h"
#include "adobedng-bridge.h"
#include "dither.h"
#include "timing.h"
#include "kelvin.h"
// #include "../../src/module.h"
// #undef MODULE_STRINGS_SECTION
// #define MODULE_STRINGS_SECTION
// #include "module_strings.h"
/** Command-line interface */
int interp_method = 0; /* 0:amaze-edge, 1:mean23 */
int chroma_smooth_method = 2;
int fix_pink_dots = 0;
int fix_bad_pixels = 1;
int use_fullres = 1;
int use_alias_map = 1;
int use_stripe_fix = 1;
float soft_film_ev = 0;
int exif_wb = 0;
float custom_wb[3] = {0, 0, 0};
int debug_wb = 0;
#define WB_GRAY_MED 1
#define WB_GRAY_MAX 2
int gray_wb = WB_GRAY_MAX;
int debug_black = 0;
int debug_blend = 0;
int debug_amaze = 0;
int debug_edge = 0;
int debug_alias = 0;
int debug_bad_pixels = 0;
int debug_rggb = 0;
int debug_bddb = 0;
int plot_iso_curve = 0;
int plot_mix_curve = 0;
int plot_fullres_curve = 0;
int compress = 0;
int same_levels = 0;
int skip_existing = 0;
int embed_original = 0;
int shortcut_fast = 0;
void check_shortcuts()
{
if (shortcut_fast)
{
interp_method = 1;
chroma_smooth_method = 0;
use_alias_map = 0;
use_fullres = 0;
use_stripe_fix = 0;
shortcut_fast = 0;
fix_bad_pixels = 0;
}
}
struct cmd_option
{
int* variable; /* can be float */
int value_to_assign; /* if the option field contains %d or %f, set this to number of %'s */
char* option; /* can contain %d or %f for options with values */
char* help;
int force_show;
};
#define OPTION_EOL { 0, 0, 0, 0 }
struct cmd_group
{
char* name;
struct cmd_option * options;
};
#define OPTION_GROUP_EOL { 0, 0 }
struct cmd_group options[] = {
{
"Shortcuts", (struct cmd_option []) {
{ &shortcut_fast, 1, "--fast", "disable most postprocessing steps (fast, but low quality)\n"
" (--mean23, --no-cs, --no-fullres, --no-alias-map, --no-stripe-fix, --no-bad-pix)" },
OPTION_EOL,
},
},
{
"Interpolation methods", (struct cmd_option[]) {
{ &interp_method, 0, "--amaze-edge", "use a temporary demosaic step (AMaZE) followed by edge-directed interpolation (default)" },
{ &interp_method, 1, "--mean23", "average the nearest 2 or 3 pixels of the same color from the Bayer grid (faster)" },
OPTION_EOL
},
},
{
"Chroma smoothing", (struct cmd_option[]) {
{ &chroma_smooth_method, 2, "--cs2x2", "apply 2x2 chroma smoothing in noisy and aliased areas (default)" },
{ &chroma_smooth_method, 3, "--cs3x3", "apply 3x3 chroma smoothing in noisy and aliased areas" },
{ &chroma_smooth_method, 5, "--cs5x5", "apply 5x5 chroma smoothing in noisy and aliased areas" },
{ &chroma_smooth_method, 0, "--no-cs", "disable chroma smoothing" },
OPTION_EOL
},
},
{
"Bad pixel handling", (struct cmd_option[]) {
//{ &fix_pink_dots, 1, "--pink-dots", "fix pink dots with a early chroma smoothing step" },
{ &fix_bad_pixels, 1, "--bad-pix", NULL },
{ &fix_bad_pixels, 2, "--really-bad-pix", "aggressive bad pixel fix, at the expense of detail and aliasing" },
{ &fix_bad_pixels, 0, "--no-bad-pix", "disable bad pixel fixing (try it if you shoot stars)" },
{ &debug_bad_pixels,1,"--black-bad-pix", "mark all bad pixels as black (for troubleshooting)" },
OPTION_EOL
},
},
{
"Highlight/shadow handling", (struct cmd_option[]) {
{ (int*)&soft_film_ev, 1, "--soft-film=%f", "bake a soft-film curve to compress highlights and raise shadows by X EV\n"
" (if you use this option, you should also specify the white balance)"},
OPTION_EOL
},
},
{
"White balance", (struct cmd_option[]) {
{ &gray_wb, WB_GRAY_MAX, "--wb=graymax", "set AsShotNeutral by maximizing the number of gray pixels (default)" },
{ &gray_wb, WB_GRAY_MED, "--wb=graymed", "set AsShotNeutral from the median of R-G and B-G" },
{ &exif_wb, 1, "--wb=exif", "set AsShotNeutral from EXIF WB (not exactly working)" },
{ (int*)&custom_wb[0], 3, "--wb=%f,%f,%f", "use custom RGB multipliers" },
OPTION_EOL
},
},
{
"Other postprocessing steps", (struct cmd_option[]) {
{ &use_fullres, 0, "--no-fullres", "disable full-resolution blending" },
{ &use_fullres, 1, "--fullres", NULL},
{ &use_alias_map, 0, "--no-alias-map", "disable alias map, used to fix aliasing in deep shadows" },
{ &use_alias_map, 1, "--alias-map", NULL},
{ &use_stripe_fix, 0, "--no-stripe-fix", "disable horizontal stripe fix" },
{ &use_stripe_fix, 1, "--stripe-fix", NULL},
OPTION_EOL
},
},
{
"Flicker handling", (struct cmd_option[]) {
{ (int*)&same_levels, 1, "--same-levels", "Adjust output white levels to keep the same overall exposure\n"
" for all frames passed in a single command line\n"
" (useful to avoid flicker - for video or panoramas)" },
/* todo: deflicker, percentiles... */
OPTION_EOL
},
},
{
"DNG compression (requires Adobe DNG Converter)", (struct cmd_option[]) {
{ &compress, 1, "--compress", "Lossless DNG compression" },
{ &compress, 2, "--compress-lossy", "Lossy DNG compression (be careful, may destroy shadow detail)" },
OPTION_EOL
},
},
{
"Misc settings", (struct cmd_option[]) {
{ &skip_existing, 1, "--skip-existing", "Skip the conversion if the output file already exists" },
{ &embed_original, 1, "--embed-original", "Embed (move) the original CR2 file in the output DNG. The original will be deleted.\n"
" You will be able to re-process the DNG with a different version or different conversion settings.\n"
" To recover the original: exiftool IMG_1234.DNG -OriginalRawFileData -b > IMG_1234.CR2" },
{ &embed_original, 2, "--embed-original-copy", "\n"
" Similar to --embed-original, but without deleting the original.\n" },
OPTION_EOL
},
},
{
"Troubleshooting options", (struct cmd_option[]) {
{ &debug_blend, 1, "--debug-blend", "save intermediate images used for blending:\n"
" dark.dng the low-ISO exposure, interpolated\n"
" bright.dng the high-ISO exposure, interpolated and darkened\n"
" halfres.dng half-resolution blending (low noise, high aliasing)\n"
" fullres.dng full-resolution blending (minimal aliasing, high noise)\n"
" *_smooth.dng images after chroma smoothing"
},
{ &debug_black, 1, "--debug-black", "save intermediate images used for black level subtraction" },
{ &debug_amaze, 1, "--debug-amaze", "save AMaZE input and output" },
{ &debug_edge, 1, "--debug-edge", "save debug info from edge-directed interpolation" },
{ &debug_alias, 1, "--debug-alias", "save debug info about the alias map" },
{ &debug_rggb, 1, "--debug-rggb", "plot debug info for RGGB/BGGR autodetection (requires octave)" },
{ &debug_bddb, 1, "--debug-bddb", "plot debug info for bright/dark autodetection (requires octave)" },
{ &debug_wb, 1, "--debug-wb", "show the vectorscope used for white balance (requires octave)" },
{ &plot_iso_curve, 1, "--iso-curve", "plot the curve fitting results for ISO and black offset (requires octave)" },
{ &plot_mix_curve, 1, "--mix-curve", "plot the curve used for half-res blending (requires octave)" },
{ &plot_fullres_curve, 1, "--fullres-curve","plot the curve used for full-res blending (requires octave)" },
OPTION_EOL
},
},
OPTION_GROUP_EOL
};
static int startswith(char* str, char* prefix)
{
char* s = str;
char* p = prefix;
for (; *p; s++,p++)
if (*s != *p) return 0;
return 1;
}
static void parse_sscanf(char* user_input, char* format, void* ptr, int num_vars)
{
void* pointers[5] = {0, 0, 0, 0, 0};
if (num_vars > 5) goto err;
int i;
char* p = strchr(format, '%');
for (i = 0; p != NULL && i < num_vars; i++, p = strchr(p+1, '%'))
{
//~ printf("%s: %p %p\n", format, ptr, &soft_film_ev);
pointers[i] = ptr;
int size =
*(p+1) == 'd' ? sizeof(int) :
*(p+1) == 'f' ? sizeof(float) :
0;
if (size == 0) goto err;
ptr += size;
}
if (i != num_vars) goto err;
int num = sscanf(user_input, format, pointers[0], pointers[1], pointers[2], pointers[3], pointers[4]);
if (num != num_vars)
{
printf("Error parsing %s: expected %d param%s, got %d\n", format, num_vars, num_vars == 1 ? "" : "s", num);
exit(1);
}
return;
err:
printf("invalid option: %s (internal error)\n", format);
exit(1);
}
static void print_sscanf_option(char* format, void* ptr, int num_vars, char* help)
{
int i = 0;
int len = 0;
for (char* p = format; *p && i < num_vars; p++)
{
if (*p != '%')
{
len += printf("%c", *p);
}
else
{
if (*(p+1) == 'd')
{
len += printf("%d", *(int*)ptr);
ptr += sizeof(float);
}
else if (*(p+1) == 'f')
{
len += printf("%g", *(float*)ptr);
ptr += sizeof(int);
}
p++; i++;
}
}
while (len < 16)
{
len += printf(" ");
}
printf(": %s\n", help);
}
static void parse_commandline_option(char* option)
{
for (struct cmd_group * g = options; g->name; g++)
{
for (struct cmd_option * o = g->options; o->option; o++)
{
if (strchr(o->option, '%'))
{
char base[100];
snprintf(base, sizeof(base), "%s", o->option);
char* percent = strchr(base, '%');
if (percent)
{
*percent = 0; /* trim here */
if (startswith(option, base))
{
/* note that o->variable is the array where %d's or %f's are stored */
/* and o->value_to_assign is the number of items in that array */
parse_sscanf(option, o->option, o->variable, o->value_to_assign);
o->force_show = 1;
return;
}
}
}
else if (!strcmp(option, o->option))
{
*(o->variable) = o->value_to_assign;
check_shortcuts();
return;
}
}
}
printf("Unknown option: %s\n", option);
exit(1);
}
static void show_commandline_help(char* progname)
{
printf("Command-line usage: %s [OPTIONS] [FILES]\n\n", progname);
for (struct cmd_group * g = options; g->name; g++)
{
printf("%s:\n", g->name);
for (struct cmd_option * o = g->options; o->option; o++)
{
if (o->help)
{
printf("%-16s: %s\n", o->option, o->help);
}
}
printf("\n");
}
}
static void solve_commandline_deps()
{
if (!use_fullres)
use_alias_map = 0;
}
static void show_active_options()
{
printf("Active options:\n");
for (struct cmd_group * g = options; g->name; g++)
{
for (struct cmd_option * o = g->options; o->option; o++)
{
if (strchr(o->option, '%'))
{
if (o->force_show)
{
/* note that o->variable is the array where %d's or %f's are stored */
/* and o->value_to_assign is the number of items in that array */
print_sscanf_option(o->option, o->variable, o->value_to_assign, o->help);
}
}
else
{
if (o->help && (*o->variable) == o->value_to_assign)
{
printf("%-16s: %s\n", o->option, o->help);
}
}
}
}
}
/* here we only have a global raw_info */
#define save_dng(filename) save_dng(filename, &raw_info)
#define FAIL(fmt,...) { fprintf(stderr, "Error: "); fprintf(stderr, fmt, ## __VA_ARGS__); fprintf(stderr, "\n"); exit(1); }
#define CHECK(ok, fmt,...) { if (!(ok)) FAIL(fmt, ## __VA_ARGS__); }
static void* malloc_or_die(size_t size)
{
void* p = malloc(size);
CHECK(p, "malloc");
return p;
}
/* replace all malloc calls with malloc_or_die (if any call fails, abort right away) */
#define malloc(size) malloc_or_die(size)
#define COERCE(x,lo,hi) MAX(MIN((x),(hi)),(lo))
#define COUNT(x) ((int)(sizeof(x)/sizeof((x)[0])))
#define MIN(a,b) \
({ typeof ((a)+(b)) _a = (a); \
typeof ((a)+(b)) _b = (b); \
_a < _b ? _a : _b; })
#define MAX(a,b) \
({ typeof ((a)+(b)) _a = (a); \
typeof ((a)+(b)) _b = (b); \
_a > _b ? _a : _b; })
#define ABS(a) \
({ __typeof__ (a) _a = (a); \
_a > 0 ? _a : -_a; })
#define SGN(a) \
((a) > 0 ? 1 : -1 )
/* conversion from linear to EV space and back, with range checking */
/* when no range checking is needed, just access the array directly */
#define EV2RAW(x) ev2raw[COERCE(x, -10*EV_RESOLUTION, 14*EV_RESOLUTION-1)]
#define RAW2EV(x) raw2ev[COERCE(x, 0, 0xFFFFF)]
struct raw_info raw_info = {
.api_version = 1,
.bits_per_pixel = 16,
.black_level = 2048,
.white_level = 15000,
.cfa_pattern = 0x02010100, // Red Green Green Blue
.calibration_illuminant1 = 1, // Daylight
};
static int hdr_check();
static int hdr_interpolate();
static int black_subtract(int left_margin, int top_margin);
static int black_subtract_simple(int left_margin, int top_margin);
static void white_detect(int* white_dark, int* white_bright);
static void white_balance_gray(float* red_balance, float* blue_balance, int method);
static inline int raw_get_pixel16(int x, int y)
{
uint16_t * buf = raw_info.buffer;
int value = buf[x + y * raw_info.width];
return value;
}
static inline void raw_set_pixel16(int x, int y, int value)
{
uint16_t * buf = raw_info.buffer;
buf[x + y * raw_info.width] = value;
}
static inline int raw_get_pixel32(int x, int y)
{
uint32_t * buf = raw_info.buffer;
int value = buf[x + y * raw_info.width];
return value;
}
static inline void raw_set_pixel32(int x, int y, int value)
{
uint32_t * buf = raw_info.buffer;
buf[x + y * raw_info.width] = value;
}
static inline int raw_get_pixel20(int x, int y)
{
uint32_t * buf = raw_info.buffer;
int value = buf[x + y * raw_info.width];
return value & 0xFFFFF;
}
static inline void raw_set_pixel20(int x, int y, int value)
{
uint32_t * buf = raw_info.buffer;
buf[x + y * raw_info.width] = COERCE(value, 0, 0xFFFFF);
}
int raw_get_pixel(int x, int y) {
return raw_get_pixel16(x,y);
}
/* from 14 bit to 16 bit */
int raw_get_pixel_14to16(int x, int y) {
return (raw_get_pixel16(x,y) << 2) & 0xFFFF;
}
/* from 14 bit to 20 bit */
int raw_get_pixel_14to20(int x, int y) {
return (raw_get_pixel16(x,y) << 6) & 0xFFFFF;
}
/* from 20 bit to 16 bit */
int raw_get_pixel_20to16(int x, int y) {
return (raw_get_pixel32(x,y) >> 4) & 0xFFFF;
}
void raw_set_pixel_20to16(int x, int y, int value) {
raw_set_pixel16(x, y, value >> 4);
}
void raw_set_pixel_20to16_rand(int x, int y, int value) {
/* To avoid posterization, it's a good idea to add some noise before rounding */
/* The sweet spot seems to be with Gaussian noise of stdev=0.5, http://www.magiclantern.fm/forum/index.php?topic=10895.msg107972#msg107972 */
raw_set_pixel16(x, y, COERCE((int)(value / 16.0 + fast_randn05() + 0.5), 0, 0xFFFF));
}
static void reverse_bytes_order(void* buf, int count)
{
char* buf8 = (char*) buf;
uint16_t* buf16 = (uint16_t*) buf;
for (int i = 0; i < count/2; i++)
{
uint16_t x = buf16[i];
buf8[2*i+1] = x;
buf8[2*i] = x >> 8;
}
}
#if 0
static const char* module_get_string(const char* name)
{
module_strpair_t *strings = &__module_strings_MODULE_NAME[0];
if (strings)
{
for ( ; strings->name != NULL; strings++)
{
if (!strcmp(strings->name, name))
{
return strings->value;
}
}
}
return 0;
}
#endif
static void save_debug_dng(char* filename)
{
int black20 = raw_info.black_level;
int white20 = raw_info.white_level;
raw_info.black_level = black20/16;
raw_info.white_level = white20/16;
reverse_bytes_order(raw_info.buffer, raw_info.frame_size);
save_dng(filename);
raw_info.black_level = black20;
raw_info.white_level = white20;
}
static int is_file(const char* filename)
{
FILE* f = fopen(filename, "r");
if (f)
{
fclose(f);
return 1;
}
else
{
return 0;
}
}
int main(int argc, char** argv)
{
printf("cr2hdr: a post processing tool for Dual ISO images\n\n");
// printf("Last update: %s\n", module_get_string("Last update"));
fast_randn_init();
if (argc == 1)
{
printf("No input files.\n\n");
printf("GUI usage: drag some CR2 or DNG files over cr2hdr.exe.\n\n");
show_commandline_help(argv[0]);
return 0;
}
int r;
/* parse all command-line options */
for (int k = 1; k < argc; k++)
if (argv[k][0] == '-')
parse_commandline_option(argv[k]);
solve_commandline_deps();
show_active_options();
/* keep track of black and white levels (useful for deflicker) */
/* (we will not have more than "argc" files) */
int* file_indices = malloc(argc * sizeof(file_indices[0]));
int* blacks = malloc(argc * sizeof(blacks[0]));
int* whites = malloc(argc * sizeof(whites[0]));
int num_files = 0;
/* all other arguments are input files */
for (int k = 1; k < argc; k++)
{
if (argv[k][0] == '-')
continue;
char* filename = argv[k];
printf("\nInput file : %s\n", filename);
int len = strlen(filename);
char orig_filename[1000]; orig_filename[0] = 0;
char out_filename[1000];
if (strcmp(filename+len-4, ".DNG") == 0)
{
/* this DNG might have embedded CR2 data inside */
/* note: we only save uppercase .DNGs, so a case-sensitive extension check should be fine */
if (dng_has_original_raw(filename))
{
snprintf(orig_filename, sizeof(orig_filename), "%s", filename);
orig_filename[len-3] = 'C';
orig_filename[len-2] = 'R';
orig_filename[len-1] = '2';
if (is_file(orig_filename))
{
printf("Already exists : %s (error)\n", orig_filename);
continue;
}
if (extract_original_raw(filename, orig_filename))
{
/* use the extracted CR2 as input */
filename = orig_filename;
}
else
{
/* error message was already printed, now just skip this file */
continue;
}
}
}
snprintf(out_filename, sizeof(out_filename), "%s", filename);
out_filename[len-3] = 'D';
out_filename[len-2] = 'N';
out_filename[len-1] = 'G';
/* note: skip_existing will be ignored if we are working on a DNG file with embedded RAW */
if (skip_existing && is_file(out_filename) && !orig_filename[0])
{
printf("Already exists : %s (skipping)\n", out_filename);
continue;
}
char dcraw_cmd[1000];
snprintf(dcraw_cmd, sizeof(dcraw_cmd), "dcraw -v -i -t 0 \"%s\"", filename);
FILE* t = popen(dcraw_cmd, "r");
CHECK(t, "%s", filename);
const char * model = get_camera_model(filename);
get_raw_info(model, &raw_info);
int raw_width = 0, raw_height = 0;
int out_width = 0, out_height = 0;
char line[100];
while (fgets(line, sizeof(line), t))
{
if (startswith(line, "Full size: "))
{
r = sscanf(line, "Full size: %d x %d\n", &raw_width, &raw_height);
CHECK(r == 2, "sscanf");
}
else if (startswith(line, "Output size: "))
{
r = sscanf(line, "Output size: %d x %d\n", &out_width, &out_height);
CHECK(r == 2, "sscanf");
}
}
pclose(t);
if (raw_width == 0)
{
printf("dcraw could not open this file\n");
continue;
}
printf("Full size : %d x %d\n", raw_width, raw_height);
printf("Active area : %d x %d\n", out_width, out_height);
int left_margin = raw_width - out_width;
int top_margin = raw_height - out_height;
snprintf(dcraw_cmd, sizeof(dcraw_cmd), "dcraw -4 -E -c -t 0 \"%s\"", filename);
FILE* fp = popen(dcraw_cmd, "r");
CHECK(fp, "%s", filename);
#ifdef _O_BINARY
_setmode(_fileno(fp), _O_BINARY);
#endif
/* PGM read code from dcraw */
int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c;
if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
if (c == '#') comment = 1;
if (c == '\n') comment = 0;
if (comment) continue;
if (isdigit(c)) number = 1;
if (number) {
if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
else if (isspace(c)) {
number = 0; nd++;
} else error = 1;
}
}
if (error || nd < 3)
{
pclose(fp);
printf("dcraw output is not a valid PGM file\n");
continue;
}
int width = dim[0];
int height = dim[1];
CHECK(width == raw_width, "pgm width");
CHECK(height == raw_height, "pgm height");
void* buf = malloc(width * (height+1) * 2); /* 1 extra line for handling GBRG easier */
int size = fread(buf, 1, width * height * 2, fp);
CHECK(size == width * height * 2, "fread");
pclose(fp);
/* PGM is big endian, need to reverse it */
reverse_bytes_order(buf, width * height * 2);
raw_info.buffer = buf;
/* did we read the PGM correctly? (right byte order etc) */
//~ for (int i = 0; i < 10; i++)
//~ printf("%d ", raw_get_pixel16(i, 0));
//~ printf("\n");
raw_info.black_level = 2048;
raw_info.white_level = 15000;
raw_info.width = width;
raw_info.height = height;
raw_info.pitch = width * 2;
raw_info.frame_size = raw_info.height * raw_info.pitch;
raw_info.active_area.x1 = left_margin;
raw_info.active_area.x2 = raw_info.width;
raw_info.active_area.y1 = top_margin;
raw_info.active_area.y2 = raw_info.height;
raw_info.jpeg.x = 0;
raw_info.jpeg.y = 0;
raw_info.jpeg.width = raw_info.width - left_margin;
raw_info.jpeg.height = raw_info.height - top_margin;
dng_set_thumbnail_size(384, 252);
if (hdr_check())
{
if (!black_subtract(left_margin, top_margin))
printf("Black subtract didn't work\n");
if (hdr_interpolate())
{
reverse_bytes_order(raw_info.buffer, raw_info.frame_size);
/* This option doesn't really work, since Canon WB is broken with Dual ISO. */
if (exif_wb)
{
float red_balance = -1, blue_balance = -1;
read_white_balance(filename, &red_balance, &blue_balance);
if ((red_balance > 0) && (blue_balance > 0))
{
dng_set_wbgain(1000000, red_balance*1000000, 1, 1, 1000000, blue_balance*1000000);
printf("AsShotNeutral : %.2f 1 %.2f\n", 1/red_balance, 1/blue_balance);
}
else
{
printf("AsShotNeutral : (using default values)\n");
}
}
char renamed_filename[1000];
char* old_filename = 0;
if (strcasecmp(filename, out_filename) == 0)
{
/* if the filesystem is not case-sensitive, we will overwrite the input file */
/* I don't know how to detect this in a portable way, so I'll rename the input file just in case */
/* if no overwriting takes place, the renaming will be undone */
//~ printf("Might overwrite input file.\n");
snprintf(renamed_filename, sizeof(renamed_filename), "%s", filename);
int len = strlen(renamed_filename);
renamed_filename[len-1] = '6';
rename(filename, renamed_filename);
old_filename = filename;
filename = renamed_filename;
}
if (orig_filename[0])
{
dng_backup_metadata(out_filename);
}
printf("Output file : %s %s\n", out_filename, is_file(out_filename) ? "(already exists, overwriting)" : "");
save_dng(out_filename);
copy_tags_from_source(filename, out_filename);
if (orig_filename[0])
{
dng_restore_metadata(out_filename);
}
if (compress)
{
dng_compress(out_filename, compress-1);
}
if (embed_original || orig_filename[0])
{
/* this will move the input file into the DNG (and maybe delete the original) */
int delete_original = (embed_original != 2);
embed_original_raw(out_filename, filename, delete_original);
}
if (old_filename && is_file(renamed_filename))
{
if (!is_file(old_filename))
{
/* input file not overwritten, undo renaming */
rename(renamed_filename, old_filename);
}
else
{
/* output file would overwrite the input file */
unlink(renamed_filename);
}
}
/* record black and white levels */
file_indices[num_files] = k;
blacks[num_files] = raw_info.black_level;
whites[num_files] = raw_info.white_level;
num_files++;
}
else
{
printf("ISO blending didn't work\n");
}
}
else
{
printf("Doesn't look like interlaced ISO\n");
}
free(buf);
}
if (same_levels && num_files > 1)
{
/* Equalize white-black for all shots.
*
* Assuming all the pictures were shot at the same exposure settings,
* this step will make sure they are all rendered identically (without flicker).
*
* However, for this to work, all the files must be passed in the same command line.
*
* We will use something close to maximum range among all files (with outlier filter).
*
* This should work even if the black level is not the same in all shots.
*/
printf("\nEqualizing levels...\n");
int* ranges = malloc(num_files * sizeof(ranges[0]));
for (int i = 0; i < num_files; i++)
{
ranges[i] = whites[i] - blacks[i];
}
int new_range = kth_smallest_int(ranges, num_files, num_files * 8 / 9 - 1);
for (int i = 0; i < num_files; i++)
{
char* input_file = argv[file_indices[i]];
/* fixme: duplicate code */
char out_filename[1000];
snprintf(out_filename, sizeof(out_filename), "%s", input_file);
int len = strlen(out_filename);
out_filename[len-3] = 'D';
out_filename[len-2] = 'N';
out_filename[len-1] = 'G';
int new_white = blacks[i] + new_range;
printf("%-16s: %d ... %d\n", out_filename, blacks[i], new_white);
set_white_level(out_filename, new_white);
}
free(ranges);
}
free(whites);
free(blacks);
free(file_indices);
return 0;
}
static void white_detect(int* white_dark, int* white_bright)
{
/* sometimes the white level is much lower than 15000; this would cause pink highlights */
/* workaround: consider the white level as a little under the maximum pixel value from the raw file */
/* caveat: bright and dark exposure may have different white levels, so we'll take the minimum value */
/* side effect: if the image is not overexposed, it may get brightened a little; shouldn't hurt */
int whites[2] = { 0, 0};
int discard_pixels[2] = { 10, 50}; /* discard the brightest N pixels */
int safety_margins[2] = {100, 1500}; /* use a higher safety margin for the higher ISO */
/* note: with the high-ISO WL underestimated by 1500, you would lose around 0.15 EV of non-aliased detail */
int* pixels[2];
int max_pix = raw_info.width * raw_info.height / 2 / 9;
pixels[0] = malloc(max_pix * sizeof(pixels[0][0]));
pixels[1] = malloc(max_pix * sizeof(pixels[0][0]));
int counts[2] = {0, 0};
/* collect all the pixels and find the k-th max, thus ignoring hot pixels */
/* change the sign in order to use kth_smallest_int */
for (int y = raw_info.active_area.y1; y < raw_info.active_area.y2; y += 3)
{
for (int x = raw_info.active_area.x1; x < raw_info.active_area.x2; x += 3)
{
int pix = raw_get_pixel16(x, y);
#define BIN_IDX is_bright[y%4]
counts[BIN_IDX] = MIN(counts[BIN_IDX], max_pix-1);
pixels[BIN_IDX][counts[BIN_IDX]] = -pix;
counts[BIN_IDX]++;
#undef BIN_IDX
}
}
whites[0] = -kth_smallest_int(pixels[0], counts[0], discard_pixels[0]) - safety_margins[0];
whites[1] = -kth_smallest_int(pixels[1], counts[1], discard_pixels[1]) - safety_margins[1];
//~ printf("%8d %8d\n", whites[0], whites[1]);
//~ printf("%8d %8d\n", counts[0], counts[1]);
/* we assume 14-bit input data; out-of-range white levels may cause crash */
*white_dark = COERCE(whites[0], 10000, 16383);
*white_bright = COERCE(whites[1], 5000, 16383);
printf("White levels : %d %d\n", *white_dark, *white_bright);
free(pixels[0]);
free(pixels[1]);
}
static int black_subtract(int left_margin, int top_margin)
{
if (debug_black)
{
save_debug_dng("untouched.dng");
}
if (left_margin < 10 || top_margin < 10)
{
printf("Black borders : N/A\n");
return 1;