-
Notifications
You must be signed in to change notification settings - Fork 8
/
ufraw_ufraw.c
2388 lines (2219 loc) · 87.3 KB
/
ufraw_ufraw.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
/*
* UFRaw - Unidentified Flying Raw converter for digital camera images
*
* ufraw_ufraw.c - program interface to all the components
* Copyright 2004-2016 by Udi Fuchs
*
* 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.
*/
#include "ufraw.h"
#include "dcraw_api.h"
#ifdef HAVE_LENSFUN
#include <lensfun.h>
#endif
#include <glib/gi18n.h>
#include <string.h>
#include <sys/stat.h> /* for fstat() */
#include <math.h>
#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#ifdef HAVE_LIBBZ2
#include <bzlib.h>
#endif
void (*ufraw_progress)(int what, int ticks) = NULL;
#ifdef HAVE_LENSFUN
#define UF_LF_TRANSFORM ( \
LF_MODIFY_DISTORTION | LF_MODIFY_GEOMETRY | LF_MODIFY_SCALE)
static void ufraw_convert_image_vignetting(ufraw_data *uf,
ufraw_image_data *img, UFRectangle *area);
static void ufraw_convert_image_tca(ufraw_data *uf, ufraw_image_data *img,
ufraw_image_data *outimg,
UFRectangle *area);
void ufraw_prepare_tca(ufraw_data *uf);
#endif
static void ufraw_image_format(int *colors, int *bytes, ufraw_image_data *img,
const char *formats, const char *caller);
static void ufraw_convert_image_raw(ufraw_data *uf, UFRawPhase phase);
static void ufraw_convert_image_first(ufraw_data *uf, UFRawPhase phase);
static void ufraw_convert_image_transform(ufraw_data *uf, ufraw_image_data *img,
ufraw_image_data *outimg, UFRectangle *area);
static void ufraw_convert_prepare_first_buffer(ufraw_data *uf,
ufraw_image_data *img);
static void ufraw_convert_prepare_transform_buffer(ufraw_data *uf,
ufraw_image_data *img, int width, int height);
static void ufraw_convert_reverse_wb(ufraw_data *uf, UFRawPhase phase);
static void ufraw_convert_import_buffer(ufraw_data *uf, UFRawPhase phase,
dcraw_image_data *dcimg);
static int make_temporary(char *basefilename, char **tmpfilename)
{
int fd;
char *basename = g_path_get_basename(basefilename);
char *template = g_strconcat(basename, ".tmp.XXXXXX", NULL);
fd = g_file_open_tmp(template, tmpfilename, NULL);
g_free(template);
g_free(basename);
return fd;
}
static ssize_t writeall(int fd, const char *buf, ssize_t size)
{
ssize_t written;
ssize_t wr;
for (written = 0; size > 0; size -= wr, written += wr, buf += wr)
if ((wr = write(fd, buf, size)) < 0)
break;
return written;
}
static char *decompress_gz(char *origfilename)
{
#ifdef HAVE_LIBZ
char *tempfilename;
int tmpfd;
gzFile gzfile;
char buf[8192];
ssize_t size;
if ((tmpfd = make_temporary(origfilename, &tempfilename)) == -1)
return NULL;
char *filename = uf_win32_locale_filename_from_utf8(origfilename);
gzfile = gzopen(filename, "rb");
uf_win32_locale_filename_free(filename);
if (gzfile != NULL) {
while ((size = gzread(gzfile, buf, sizeof buf)) > 0) {
if (writeall(tmpfd, buf, size) != size)
break;
}
gzclose(gzfile);
if (size == 0)
if (close(tmpfd) == 0)
return tempfilename;
}
close(tmpfd);
g_unlink(tempfilename);
g_free(tempfilename);
return NULL;
#else
(void)origfilename;
ufraw_message(UFRAW_SET_ERROR,
"Cannot open gzip compressed images.\n");
return NULL;
#endif
}
static char *decompress_bz2(char *origfilename)
{
#ifdef HAVE_LIBBZ2
char *tempfilename;
int tmpfd;
FILE *compfile;
BZFILE *bzfile;
int bzerror;
char buf[8192];
ssize_t size;
if ((tmpfd = make_temporary(origfilename, &tempfilename)) == -1)
return NULL;
compfile = g_fopen(origfilename, "rb");
if (compfile != NULL) {
if ((bzfile = BZ2_bzReadOpen(&bzerror, compfile, 0, 0, 0, 0)) != 0) {
while ((size = BZ2_bzRead(&bzerror, bzfile, buf, sizeof buf)) > 0)
if (writeall(tmpfd, buf, size) != size)
break;
BZ2_bzReadClose(&bzerror, bzfile);
fclose(compfile);
if (size == 0) {
close(tmpfd);
return tempfilename;
}
}
}
close(tmpfd);
g_unlink(tempfilename);
g_free(tempfilename);
return NULL;
#else
(void)origfilename;
ufraw_message(UFRAW_SET_ERROR,
"Cannot open bzip2 compressed images.\n");
return NULL;
#endif
}
ufraw_data *ufraw_open(char *filename)
{
int status;
ufraw_data *uf;
dcraw_data *raw;
ufraw_message(UFRAW_CLEAN, NULL);
conf_data *conf = NULL;
char *fname, *hostname;
char *origfilename;
gchar *unzippedBuf = NULL;
gsize unzippedBufLen = 0;
fname = g_filename_from_uri(filename, &hostname, NULL);
if (fname != NULL) {
if (hostname != NULL) {
ufraw_message(UFRAW_SET_ERROR, _("Remote URI is not supported"));
g_free(hostname);
g_free(fname);
return NULL;
}
g_strlcpy(filename, fname, max_path);
g_free(fname);
}
/* First handle ufraw ID files. */
if (strcasecmp(filename + strlen(filename) - 6, ".ufraw") == 0) {
conf = g_new(conf_data, 1);
status = conf_load(conf, filename);
if (status != UFRAW_SUCCESS) {
g_free(conf);
return NULL;
}
/* If inputFilename and outputFilename have the same path,
* then inputFilename is searched for in the path of the ID file.
* This allows moving raw and ID files together between folders. */
char *inPath = g_path_get_dirname(conf->inputFilename);
char *outPath = g_path_get_dirname(conf->outputFilename);
if (strcmp(inPath, outPath) == 0) {
char *path = g_path_get_dirname(filename);
char *inName = g_path_get_basename(conf->inputFilename);
char *inFile = g_build_filename(path, inName , NULL);
if (g_file_test(inFile, G_FILE_TEST_EXISTS)) {
g_strlcpy(conf->inputFilename, inFile, max_path);
}
g_free(path);
g_free(inName);
g_free(inFile);
}
g_free(inPath);
g_free(outPath);
/* Output image should be created in the path of the ID file */
char *path = g_path_get_dirname(filename);
g_strlcpy(conf->outputPath, path, max_path);
g_free(path);
filename = conf->inputFilename;
}
origfilename = filename;
if (!strcasecmp(filename + strlen(filename) - 3, ".gz"))
filename = decompress_gz(filename);
else if (!strcasecmp(filename + strlen(filename) - 4, ".bz2"))
filename = decompress_bz2(filename);
if (filename == 0) {
ufraw_message(UFRAW_SET_ERROR,
"Error creating temporary file for compressed data.");
return NULL;
}
raw = g_new(dcraw_data, 1);
status = dcraw_open(raw, filename);
if (filename != origfilename) {
g_file_get_contents(filename, &unzippedBuf, &unzippedBufLen, NULL);
g_unlink(filename);
g_free(filename);
filename = origfilename;
}
if (status != DCRAW_SUCCESS) {
/* Hold the message without displaying it */
ufraw_message(UFRAW_SET_WARNING, raw->message);
if (status != DCRAW_WARNING) {
g_free(raw);
g_free(unzippedBuf);
return NULL;
}
}
uf = g_new0(ufraw_data, 1);
ufraw_message_init(uf);
uf->rgbMax = 0; // This indicates that the raw file was not loaded yet.
uf->unzippedBuf = unzippedBuf;
uf->unzippedBufLen = unzippedBufLen;
uf->conf = conf;
g_strlcpy(uf->filename, filename, max_path);
int i;
for (i = ufraw_raw_phase; i < ufraw_phases_num; i++) {
uf->Images[i].buffer = NULL;
uf->Images[i].width = 0;
uf->Images[i].height = 0;
uf->Images[i].valid = 0;
uf->Images[i].invalidate_event = TRUE;
}
uf->thumb.buffer = NULL;
uf->raw = raw;
uf->colors = raw->colors;
uf->raw_color = raw->raw_color;
uf->developer = NULL;
uf->AutoDeveloper = NULL;
uf->displayProfile = NULL;
uf->displayProfileSize = 0;
uf->RawHistogram = NULL;
uf->HaveFilters = raw->filters != 0;
uf->IsXTrans = raw->filters == 9;
#ifdef HAVE_LENSFUN
uf->modFlags = 0;
uf->TCAmodifier = NULL;
uf->modifier = NULL;
#endif
uf->inputExifBuf = NULL;
uf->outputExifBuf = NULL;
ufraw_message(UFRAW_SET_LOG, "ufraw_open: w:%d h:%d curvesize:%d\n",
raw->width, raw->height, raw->toneCurveSize);
return uf;
}
int ufraw_load_darkframe(ufraw_data *uf)
{
if (strlen(uf->conf->darkframeFile) == 0)
return UFRAW_SUCCESS;
if (uf->conf->darkframe != NULL) {
// If the same file was already openned, there is nothing to do.
if (strcmp(uf->conf->darkframeFile, uf->conf->darkframe->filename) == 0)
return UFRAW_SUCCESS;
// Otherwise we need to close the previous darkframe
ufraw_close_darkframe(uf->conf);
}
ufraw_data *dark = uf->conf->darkframe =
ufraw_open(uf->conf->darkframeFile);
if (dark == NULL) {
ufraw_message(UFRAW_ERROR, _("darkframe error: %s is not a raw file\n"),
uf->conf->darkframeFile);
uf->conf->darkframeFile[0] = '\0';
return UFRAW_ERROR;
}
dark->conf = g_new(conf_data, 1);
conf_init(dark->conf);
/* initialize ufobject member */
dark->conf->ufobject = ufraw_image_new();
/* disable all auto settings on darkframe */
dark->conf->autoExposure = disabled_state;
dark->conf->autoBlack = disabled_state;
if (ufraw_load_raw(dark) != UFRAW_SUCCESS) {
ufraw_message(UFRAW_ERROR, _("error loading darkframe '%s'\n"),
uf->conf->darkframeFile);
ufraw_close(dark);
g_free(dark);
uf->conf->darkframe = NULL;
uf->conf->darkframeFile[0] = '\0';
return UFRAW_ERROR;
}
// Make sure the darkframe matches the main data
dcraw_data *raw = uf->raw;
dcraw_data *darkRaw = dark->raw;
if (raw->width != darkRaw->width ||
raw->height != darkRaw->height ||
raw->colors != darkRaw->colors) {
ufraw_message(UFRAW_WARNING,
_("Darkframe '%s' is incompatible with main image"),
uf->conf->darkframeFile);
ufraw_close(dark);
g_free(dark);
uf->conf->darkframe = NULL;
uf->conf->darkframeFile[0] = '\0';
return UFRAW_ERROR;
}
ufraw_message(UFRAW_BATCH_MESSAGE, _("using darkframe '%s'\n"),
uf->conf->darkframeFile);
/* Calculate dark frame hot pixel thresholds as the 99.99th percentile
* value. That is, the value at which 99.99% of the pixels are darker.
* Pixels below this threshold are considered to be bias noise, and
* those above are "hot". */
int color;
int i;
long frequency[65536];
long sum;
long point = darkRaw->raw.width * darkRaw->raw.height / 10000;
for (color = 0; color < darkRaw->raw.colors; ++color) {
memset(frequency, 0, sizeof frequency);
for (i = 0; i < darkRaw->raw.width * darkRaw->raw.height; ++i)
frequency[darkRaw->raw.image[i][color]]++;
for (sum = 0, i = 65535; i > 1; --i) {
sum += frequency[i];
if (sum >= point)
break;
}
darkRaw->thresholds[color] = i + 1;
}
return UFRAW_SUCCESS;
}
// Get the dimensions of the unshrunk, rotated image.autoCrop
// The crop coordinates are calculated based on these dimensions.
void ufraw_get_image_dimensions(ufraw_data *uf)
{
dcraw_image_dimensions(uf->raw, uf->conf->orientation, 1,
&uf->initialHeight, &uf->initialWidth);
ufraw_get_image(uf, ufraw_transform_phase, FALSE);
if (uf->conf->fullCrop || uf->conf->CropX1 < 0) uf->conf->CropX1 = 0;
if (uf->conf->fullCrop || uf->conf->CropY1 < 0) uf->conf->CropY1 = 0;
if (uf->conf->fullCrop || uf->conf->CropX2 < 0) uf->conf->CropX2 = uf->rotatedWidth;
if (uf->conf->fullCrop || uf->conf->CropY2 < 0) uf->conf->CropY2 = uf->rotatedHeight;
if (uf->conf->fullCrop)
uf->conf->aspectRatio = (double)uf->rotatedWidth / uf->rotatedHeight;
else if (uf->conf->aspectRatio <= 0) {
if (uf->conf->autoCrop)
/* preserve the initial aspect ratio - this should be consistent
with ufraw_convert_prepare_transform */
uf->conf->aspectRatio = ((double)uf->initialWidth) / uf->initialHeight;
else
/* full rotated image / manually entered crop */
uf->conf->aspectRatio = ((double)uf->conf->CropX2 - uf->conf->CropX1)
/ (uf->conf->CropY2 - uf->conf->CropY1);
} else {
/* given aspectRatio */
int cropWidth = uf->conf->CropX2 - uf->conf->CropX1;
int cropHeight = uf->conf->CropY2 - uf->conf->CropY1;
if (cropWidth != (int)floor(cropHeight * uf->conf->aspectRatio + 0.5)) {
/* aspectRatio does not match the crop area - shrink the area */
if ((double)cropWidth / cropHeight > uf->conf->aspectRatio) {
cropWidth = floor(cropHeight * uf->conf->aspectRatio + 0.5);
uf->conf->CropX1 = (uf->conf->CropX1 + uf->conf->CropX2 - cropWidth) / 2;
uf->conf->CropX2 = uf->conf->CropX1 + cropWidth;
} else {
cropHeight = floor(cropWidth / uf->conf->aspectRatio + 0.5);
uf->conf->CropY1 = (uf->conf->CropY1 + uf->conf->CropY2 - cropHeight) / 2;
uf->conf->CropY2 = uf->conf->CropY1 + cropHeight;
}
}
}
}
/* Get scaled crop coordinates in final image coordinates */
void ufraw_get_scaled_crop(ufraw_data *uf, UFRectangle *crop)
{
ufraw_image_data *img = ufraw_get_image(uf, ufraw_transform_phase, FALSE);
float scale_x = ((float)img->width) / uf->rotatedWidth;
float scale_y = ((float)img->height) / uf->rotatedHeight;
crop->x = MAX(floor(uf->conf->CropX1 * scale_x), 0);
int x2 = MIN(ceil(uf->conf->CropX2 * scale_x), img->width);
crop->width = x2 - crop->x;
crop->y = MAX(floor(uf->conf->CropY1 * scale_y), 0);
int y2 = MIN(ceil(uf->conf->CropY2 * scale_y), img->height);
crop->height = y2 - crop->y;
}
int ufraw_config(ufraw_data *uf, conf_data *rc, conf_data *conf, conf_data *cmd)
{
int status;
if (rc->autoExposure == enabled_state) rc->autoExposure = apply_state;
if (rc->autoBlack == enabled_state) rc->autoBlack = apply_state;
g_assert(uf != NULL);
/* Check if we are loading an ID file */
if (uf->conf != NULL) {
/* ID file configuration is put "on top" of the rc data */
uf->LoadingID = TRUE;
conf_data tmp = *rc;
tmp.ufobject = uf->conf->ufobject;
conf_copy_image(&tmp, uf->conf);
conf_copy_transform(&tmp, uf->conf);
conf_copy_save(&tmp, uf->conf);
g_strlcpy(tmp.outputFilename, uf->conf->outputFilename, max_path);
g_strlcpy(tmp.outputPath, uf->conf->outputPath, max_path);
*uf->conf = tmp;
} else {
uf->LoadingID = FALSE;
uf->conf = g_new(conf_data, 1);
*uf->conf = *rc;
uf->conf->ufobject = ufraw_image_new();
ufobject_copy(uf->conf->ufobject,
ufgroup_element(rc->ufobject, ufRawImage));
}
if (conf != NULL && conf->version != 0) {
conf_copy_image(uf->conf, conf);
conf_copy_save(uf->conf, conf);
if (uf->conf->autoExposure == enabled_state)
uf->conf->autoExposure = apply_state;
if (uf->conf->autoBlack == enabled_state)
uf->conf->autoBlack = apply_state;
}
if (cmd != NULL) {
status = conf_set_cmd(uf->conf, cmd);
if (status != UFRAW_SUCCESS) return status;
}
dcraw_data *raw = uf->raw;
if (ufobject_name(uf->conf->ufobject) != ufRawImage)
g_warning("uf->conf->ufobject is not a ufRawImage");
/*Reset EXIF data text fields to avoid spill over between images.*/
strcpy(uf->conf->isoText, "");
strcpy(uf->conf->shutterText, "");
strcpy(uf->conf->apertureText, "");
strcpy(uf->conf->focalLenText, "");
strcpy(uf->conf->focalLen35Text, "");
strcpy(uf->conf->lensText, "");
strcpy(uf->conf->flashText, "");
// lensText is used in ufraw_lensfun_init()
if (!uf->conf->embeddedImage) {
if (ufraw_exif_read_input(uf) != UFRAW_SUCCESS) {
ufraw_message(UFRAW_SET_LOG, "Error reading EXIF data from %s\n",
uf->filename);
// If exiv2 fails to read the EXIF data, use the EXIF tags read
// by dcraw.
g_strlcpy(uf->conf->exifSource, "DCRaw", max_name);
uf->conf->iso_speed = raw->iso_speed;
g_snprintf(uf->conf->isoText, max_name, "%d",
(int)uf->conf->iso_speed);
uf->conf->shutter = raw->shutter;
if (uf->conf->shutter > 0 && uf->conf->shutter < 1)
g_snprintf(uf->conf->shutterText, max_name, "1/%0.1f s",
1 / uf->conf->shutter);
else
g_snprintf(uf->conf->shutterText, max_name, "%0.1f s",
uf->conf->shutter);
uf->conf->aperture = raw->aperture;
g_snprintf(uf->conf->apertureText, max_name, "F/%0.1f",
uf->conf->aperture);
uf->conf->focal_len = raw->focal_len;
g_snprintf(uf->conf->focalLenText, max_name, "%0.1f mm",
uf->conf->focal_len);
}
}
ufraw_image_set_data(uf->conf->ufobject, uf);
#ifdef HAVE_LENSFUN
// Do not reset lensfun settings while loading ID.
UFBoolean reset = !uf->LoadingID;
if (conf != NULL && conf->version > 0 && conf->ufobject != NULL) {
UFObject *conf_lensfun_auto = ufgroup_element(conf->ufobject,
ufLensfunAuto);
// Do not reset lensfun settings from conf file.
if (ufstring_is_equal(conf_lensfun_auto, "no"))
reset = FALSE;
}
ufraw_lensfun_init(ufgroup_element(uf->conf->ufobject, ufLensfun), reset);
#endif
char *absname = uf_file_set_absolute(uf->filename);
g_strlcpy(uf->conf->inputFilename, absname, max_path);
g_free(absname);
if (!uf->LoadingID) {
g_snprintf(uf->conf->inputURI, max_path, "file://%s",
uf->conf->inputFilename);
struct stat s;
fstat(fileno(raw->ifp), &s);
g_snprintf(uf->conf->inputModTime, max_name, "%d", (int)s.st_mtime);
}
if (strlen(uf->conf->outputFilename) == 0) {
/* If output filename wasn't specified use input filename */
char *filename = uf_file_set_type(uf->filename,
file_type[uf->conf->type]);
if (strlen(uf->conf->outputPath) > 0) {
char *cp = g_path_get_basename(filename);
g_free(filename);
filename = g_build_filename(uf->conf->outputPath, cp , NULL);
g_free(cp);
}
g_strlcpy(uf->conf->outputFilename, filename, max_path);
g_free(filename);
}
g_free(uf->unzippedBuf);
uf->unzippedBuf = NULL;
/* Set the EXIF data */
#ifdef __MINGW32__
/* MinG32 does not have ctime_r(). */
g_strlcpy(uf->conf->timestampText, ctime(&raw->timestamp), max_name);
#elif defined(__sun) && !defined(_POSIX_PTHREAD_SEMANTICS) /* Solaris */
/*
* Some versions of Solaris followed a draft POSIX.1c standard
* where ctime_r took a third length argument.
*/
ctime_r(&raw->timestamp, uf->conf->timestampText,
sizeof(uf->conf->timestampText));
#else
/* POSIX.1c version of ctime_r() */
ctime_r(&raw->timestamp, uf->conf->timestampText);
#endif
if (uf->conf->timestampText[strlen(uf->conf->timestampText) - 1] == '\n')
uf->conf->timestampText[strlen(uf->conf->timestampText) - 1] = '\0';
uf->conf->timestamp = raw->timestamp;
uf->conf->CameraOrientation = raw->flip;
if (!uf->conf->rotate) {
uf->conf->orientation = 0;
uf->conf->rotationAngle = 0;
} else {
if (!uf->LoadingID || uf->conf->orientation < 0)
uf->conf->orientation = uf->conf->CameraOrientation;
// Normalise rotations to a flip, then rotation of 0 < a < 90 degrees.
ufraw_normalize_rotation(uf);
}
/* If there is an embeded curve we "turn on" the custom/camera curve
* mechanism */
if (raw->toneCurveSize != 0) {
CurveData nc;
long pos = ftell(raw->ifp);
if (RipNikonNEFCurve(raw->ifp, raw->toneCurveOffset, &nc, NULL)
!= UFRAW_SUCCESS) {
ufraw_message(UFRAW_ERROR, _("Error reading NEF curve"));
return UFRAW_WARNING;
}
fseek(raw->ifp, pos, SEEK_SET);
if (nc.m_numAnchors < 2) nc = conf_default.BaseCurve[0];
g_strlcpy(nc.name, uf->conf->BaseCurve[custom_curve].name, max_name);
uf->conf->BaseCurve[custom_curve] = nc;
int use_custom_curve = 0;
if (raw->toneModeSize) {
// "AUTO " "HIGH " "CS " "MID.L " "MID.H "NORMAL " "LOW "
long pos = ftell(raw->ifp);
char buf[9];
fseek(raw->ifp, raw->toneModeOffset, SEEK_SET);
// read it in.
size_t num = fread(&buf, 9, 1, raw->ifp);
if (num != 1)
// Maybe this should be a UFRAW_WARNING
ufraw_message(UFRAW_SET_LOG,
"Warning: tone mode fread %d != %d\n", num, 1);
fseek(raw->ifp, pos, SEEK_SET);
if (!strncmp(buf, "CS ", sizeof(buf))) use_custom_curve = 1;
// down the line, we need to translate the other values into
// tone curves!
}
if (use_custom_curve) {
uf->conf->BaseCurve[camera_curve] =
uf->conf->BaseCurve[custom_curve];
g_strlcpy(uf->conf->BaseCurve[camera_curve].name,
conf_default.BaseCurve[camera_curve].name, max_name);
} else {
uf->conf->BaseCurve[camera_curve] =
conf_default.BaseCurve[camera_curve];
}
} else {
/* If there is no embeded curve we "turn off" the custom/camera curve
* mechanism */
uf->conf->BaseCurve[camera_curve].m_numAnchors = 0;
uf->conf->BaseCurve[custom_curve].m_numAnchors = 0;
if (uf->conf->BaseCurveIndex == custom_curve ||
uf->conf->BaseCurveIndex == camera_curve)
uf->conf->BaseCurveIndex = linear_curve;
}
ufraw_load_darkframe(uf);
ufraw_get_image_dimensions(uf);
return UFRAW_SUCCESS;
}
/* Scale pixel values: occupy 16 bits to get more precision. In addition
* this normalizes the pixel values which is good for non-linear algorithms
* which forget to check rgbMax or assume a particular value. */
static unsigned ufraw_scale_raw(dcraw_data *raw)
{
guint16 *p, *end;
int scale;
scale = 0;
while ((raw->rgbMax << 1) <= 0xffff) {
raw->rgbMax <<= 1;
++scale;
}
if (scale) {
end = (guint16 *)(raw->raw.image + raw->raw.width * raw->raw.height);
/* OpenMP overhead appears to be too large in this case */
int max = 0x10000 >> scale;
for (p = (guint16 *)raw->raw.image; p < end; ++p)
if (*p < max)
*p <<= scale;
else
*p = 0xffff;
raw->black <<= scale;
}
return 1 << scale;
}
int ufraw_load_raw(ufraw_data *uf)
{
int status;
dcraw_data *raw = uf->raw;
if (uf->conf->embeddedImage) {
dcraw_image_data thumb;
if ((status = dcraw_load_thumb(raw, &thumb)) != DCRAW_SUCCESS) {
ufraw_message(status, raw->message);
return status;
}
uf->thumb.height = thumb.height;
uf->thumb.width = thumb.width;
return ufraw_read_embedded(uf);
}
if ((status = dcraw_load_raw(raw)) != DCRAW_SUCCESS) {
ufraw_message(UFRAW_SET_LOG, raw->message);
ufraw_message(status, raw->message);
if (status != DCRAW_WARNING) return status;
}
uf->HaveFilters = raw->filters != 0;
uf->raw_multiplier = ufraw_scale_raw(raw);
/* Canon EOS cameras require special exposure normalization */
if (strcasecmp(uf->conf->make, "Canon") == 0 &&
strncmp(uf->conf->model, "EOS", 3) == 0) {
int c, max = raw->cam_mul[0];
for (c = 1; c < raw->colors; c++) max = MAX(raw->cam_mul[c], max);
/* Camera multipliers in DNG file are normalized to 1.
* Therefore, they can not be used to normalize exposure.
* Also, for some Canon DSLR cameras dcraw cannot read the
* camera multipliers (1D for example). */
if (max < 100) {
uf->conf->ExposureNorm = 0;
ufraw_message(UFRAW_SET_LOG, "Failed to normalizing exposure\n");
} else {
/* Convert exposure value from old ID files from before
* ExposureNorm */
if (uf->LoadingID && uf->conf->ExposureNorm == 0)
uf->conf->exposure -= log(1.0 * raw->rgbMax / max) / log(2);
uf->conf->ExposureNorm = max * raw->rgbMax / 4095;
ufraw_message(UFRAW_SET_LOG,
"Exposure Normalization set to %d (%.2f EV)\n",
uf->conf->ExposureNorm,
log(1.0 * raw->rgbMax / uf->conf->ExposureNorm) / log(2));
}
/* FUJIFILM cameras have a special tag for exposure normalization */
} else if (strcasecmp(uf->conf->make, "FUJIFILM") == 0) {
if (raw->fuji_dr == 0) {
uf->conf->ExposureNorm = 0;
} else {
int c, max = raw->cam_mul[0];
for (c = 1; c < raw->colors; c++) max = MAX(raw->cam_mul[c], max);
if (uf->LoadingID && uf->conf->ExposureNorm == 0)
uf->conf->exposure -= log(1.0 * raw->rgbMax / max) / log(2);
uf->conf->ExposureNorm = (int)(1.0 * raw->rgbMax * pow(2, (double)raw->fuji_dr / 100));
ufraw_message(UFRAW_SET_LOG,
"Exposure Normalization set to %d (%.2f EV)\n",
uf->conf->ExposureNorm, -(float)raw->fuji_dr / 100);
}
} else {
uf->conf->ExposureNorm = 0;
}
uf->rgbMax = raw->rgbMax - raw->black;
memcpy(uf->rgb_cam, raw->rgb_cam, sizeof uf->rgb_cam);
/* Foveon image dimensions are knows only after load_raw()*/
ufraw_get_image_dimensions(uf);
if (uf->conf->CropX2 > uf->rotatedWidth)
uf->conf->CropX2 = uf->rotatedWidth;
if (uf->conf->CropY2 > uf->rotatedHeight)
uf->conf->CropY2 = uf->rotatedHeight;
// Now we can finally calculate the channel multipliers.
if (uf->WBDirty) {
UFObject *wb = ufgroup_element(uf->conf->ufobject, ufWB);
char *oldWB = g_strdup(ufobject_string_value(wb));
UFObject *wbTuning = ufgroup_element(uf->conf->ufobject,
ufWBFineTuning);
double oldTuning = ufnumber_value(wbTuning);
ufraw_set_wb(uf, FALSE);
/* Here ufobject's automation goes against us. A change in
* ChannelMultipliers might change ufWB to uf_manual_wb.
* So we need to change it back. */
if (ufarray_is_equal(wb, uf_manual_wb))
ufobject_set_string(wb, oldWB);
ufnumber_set(wbTuning, oldTuning);
g_free(oldWB);
}
ufraw_auto_expose(uf);
ufraw_auto_black(uf);
return UFRAW_SUCCESS;
}
/* Free any darkframe associated with conf */
void ufraw_close_darkframe(conf_data *conf)
{
if (conf && conf->darkframe != NULL) {
ufraw_close(conf->darkframe);
g_free(conf->darkframe);
conf->darkframe = NULL;
conf->darkframeFile[0] = '\0';
}
}
void ufraw_close(ufraw_data *uf)
{
dcraw_close(uf->raw);
g_free(uf->unzippedBuf);
g_free(uf->raw);
g_free(uf->inputExifBuf);
g_free(uf->outputExifBuf);
int i;
for (i = ufraw_raw_phase; i < ufraw_phases_num; i++)
g_free(uf->Images[i].buffer);
g_free(uf->thumb.buffer);
developer_destroy(uf->developer);
developer_destroy(uf->AutoDeveloper);
g_free(uf->displayProfile);
g_free(uf->RawHistogram);
#ifdef HAVE_LENSFUN
if (uf->TCAmodifier != NULL)
lf_modifier_destroy(uf->TCAmodifier);
if (uf->modifier != NULL)
lf_modifier_destroy(uf->modifier);
#endif
ufobject_delete(uf->conf->ufobject);
g_free(uf->conf);
ufraw_message_reset(uf);
ufraw_message(UFRAW_CLEAN, NULL);
}
/* Return the coordinates and the size of given image subarea.
* There are always 32 subareas, numbered 0 to 31, ordered in a 4x8 matrix.
*/
UFRectangle ufraw_image_get_subarea_rectangle(ufraw_image_data *img,
unsigned saidx)
{
int saw = (img->width + 3) / 4;
int sah = (img->height + 7) / 8;
int sax = saidx % 4;
int say = saidx / 4;
UFRectangle area;
area.x = saw * sax;
area.y = sah * say;
area.width = (sax < 3) ? saw : (img->width - saw * 3);
area.height = (say < 7) ? sah : (img->height - sah * 7);
return area;
}
/* Return the subarea index given some X,Y image coordinates.
*/
unsigned ufraw_img_get_subarea_idx(ufraw_image_data *img, int x, int y)
{
int saw = (img->width + 3) / 4;
int sah = (img->height + 7) / 8;
return (x / saw) + (y / sah) * 4;
}
void ufraw_developer_prepare(ufraw_data *uf, DeveloperMode mode)
{
int useMatrix = uf->conf->profileIndex[0] == 1 || uf->colors == 4;
if (mode == auto_developer) {
if (uf->AutoDeveloper == NULL)
uf->AutoDeveloper = developer_init();
developer_prepare(uf->AutoDeveloper, uf->conf,
uf->rgbMax, uf->rgb_cam, uf->colors, useMatrix, mode);
} else {
if (uf->developer == NULL)
uf->developer = developer_init();
if (mode == display_developer) {
if (uf->conf->profileIndex[display_profile] != 0) {
g_free(uf->displayProfile);
uf->displayProfile = NULL;
}
developer_display_profile(uf->developer, uf->displayProfile,
uf->displayProfileSize,
uf->conf->profile[display_profile]
[uf->conf->profileIndex[display_profile]].productName);
}
developer_prepare(uf->developer, uf->conf,
uf->rgbMax, uf->rgb_cam, uf->colors, useMatrix, mode);
}
}
int ufraw_convert_image(ufraw_data *uf)
{
uf->mark_hotpixels = FALSE;
ufraw_developer_prepare(uf, file_developer);
ufraw_convert_image_raw(uf, ufraw_raw_phase);
ufraw_image_data *img = &uf->Images[ufraw_first_phase];
ufraw_convert_prepare_first_buffer(uf, img);
ufraw_convert_image_first(uf, ufraw_first_phase);
UFRectangle area = { 0, 0, img->width, img->height };
// prepare_transform has to be called before applying vignetting
ufraw_image_data *img2 = &uf->Images[ufraw_transform_phase];
ufraw_convert_prepare_transform_buffer(uf, img2, img->width, img->height);
#ifdef HAVE_LENSFUN
if (uf->modifier != NULL) {
ufraw_convert_image_vignetting(uf, img, &area);
}
#endif
if (img2->buffer != NULL) {
area.width = img2->width;
area.height = img2->height;
/* Apply distortion, geometry and rotation */
ufraw_convert_image_transform(uf, img, img2, &area);
g_free(img->buffer);
*img = *img2;
img2->buffer = NULL;
}
if (uf->conf->autoCrop && !uf->LoadingID) {
ufraw_get_image_dimensions(uf);
uf->conf->CropX1 = (uf->rotatedWidth - uf->autoCropWidth) / 2;
uf->conf->CropX2 = uf->conf->CropX1 + uf->autoCropWidth;
uf->conf->CropY1 = (uf->rotatedHeight - uf->autoCropHeight) / 2;
uf->conf->CropY2 = uf->conf->CropY1 + uf->autoCropHeight;
}
return UFRAW_SUCCESS;
}
#ifdef HAVE_LENSFUN
static void ufraw_convert_image_vignetting(ufraw_data *uf,
ufraw_image_data *img, UFRectangle *area)
{
/* Apply vignetting correction first, before distorting the image */
if (uf->modFlags & LF_MODIFY_VIGNETTING)
lf_modifier_apply_color_modification(
uf->modifier, img->buffer,
area->x, area->y, area->width, area->height,
LF_CR_4(RED, GREEN, BLUE, UNKNOWN), img->rowstride);
}
#endif
/*
ufraw_interpolate_pixel_linearly()
Interpolate a new pixel value, for one or all colors, from a 2x2 pixel
patch around coordinates x and y in the image, and write it to dst.
*/
/*
Because integer arithmetic is faster than floating point operations,
on popular CISC architectures, we cast floats to 32 bit integers,
scaling them first will maintain sufficient precision.
*/
#define SCALAR 256
static inline void ufraw_interpolate_pixel_linearly(ufraw_image_data *image, float x, float y, ufraw_image_type *dst, int color)
{
int i, j, c, cmax, xx, yy;
unsigned int dx, dy, v, weights[2][2];
ufraw_image_type *src;
/*
When casting a float to an integer it will be rounded toward zero,
that will cause problems when x or y is negative (along the top and
left border) so, we add 2 and subtract that later, using floor()
and round() is much slower.
*/
x += 2;
y += 2;
xx = x;
yy = y;
/*
Calculate weights for every pixel in the patch using the fractional
part of the coordinates.
*/
dx = (int)(x * SCALAR + 0.5) - (xx * SCALAR);
dy = (int)(y * SCALAR + 0.5) - (yy * SCALAR);
weights[0][0] = (SCALAR - dy) * (SCALAR - dx);
weights[0][1] = (SCALAR - dy) * dx;
weights[1][0] = dy * (SCALAR - dx);
weights[1][1] = dy * dx;
xx -= 2;
yy -= 2;
src = (ufraw_image_type *)image->buffer + yy * image->width + xx;
/* If an existing color number is given, then only that color will be interpolated, else all will be. */
if (color < 0 || color >= (3 + (image->rgbg == TRUE)))
c = 0, cmax = 2 + (image->rgbg == TRUE);
else
c = cmax = color;
/* Check if the source pixels are near a border, if they aren't we can use faster code. */
if (xx >= 0 && yy >= 0 && xx + 1 < image->width && yy + 1 < image->height) {
for (; c <= cmax ; c++) {
v = 0;
for (i = 0 ; i < 2 ; i++)
for (j = 0 ; j < 2 ; j++)
v += weights[i][j] * src[i * image->width + j][c];
dst[0][c] = v / (SCALAR * SCALAR);
}
} else { /* Near a border. */
for (; c <= cmax ; c++) {
v = 0;
for (i = 0 ; i < 2 ; i++)
for (j = 0 ; j < 2 ; j++)
/* Check if the source pixel lies inside the image */
if (xx + j >= 0 && yy + i >= 0 && xx + j < image->width && yy + i < image->height)
v += weights[i][j] * src[i * image->width + j][c];
dst[0][c] = v / (SCALAR * SCALAR);
}
}
}
#undef SCALAR
/* Apply distortion, geometry and rotation in a single pass */
static void ufraw_convert_image_transform(ufraw_data *uf, ufraw_image_data *img,
ufraw_image_data *outimg, UFRectangle *area)
{
float sine = sin(uf->conf->rotationAngle * 2 * M_PI / 360);
float cosine = cos(uf->conf->rotationAngle * 2 * M_PI / 360);
// If we rotate around the center:
// srcX = (X-outimg->width/2)*cosine + (Y-outimg->height/2)*sine;
// srcY = -(X-outimg->width/2)*sine + (Y-outimg->height/2)*cosine;
// Then the base offset is:
// baseX = img->width/2;
// baseY = img->height/2;
// Since we rotate around the top-left corner, the base offset is:
float baseX = img->width / 2 - outimg->width / 2 * cosine - outimg->height / 2 * sine;
float baseY = img->height / 2 + outimg->width / 2 * sine - outimg->height / 2 * cosine;
#ifdef HAVE_LENSFUN
gboolean applyLF = uf->modifier != NULL && (uf->modFlags & UF_LF_TRANSFORM);
#endif
int x, y;
for (y = area->y; y < area->y + area->height; y++) {
guint8 *cur0 = outimg->buffer + y * outimg->rowstride;
float srcX0 = y * sine + baseX;
float srcY0 = y * cosine + baseY;
for (x = area->x; x < area->x + area->width; x++) {
guint16 *cur = (guint16 *)(cur0 + x * outimg->depth);