postprocess.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #include <assert.h>
  2. #include <string.h>
  3. #include <dirent.h>
  4. #include <libraw/libraw.h>
  5. #include <jpeglib.h>
  6. #include <libexif/exif-data.h>
  7. #include <time.h>
  8. #include <unistd.h>
  9. #include <libdng.h>
  10. #include "postprocess.h"
  11. #include "stacker.h"
  12. libraw_processed_image_t *
  13. debayer_file(char *filename)
  14. {
  15. libraw_data_t *raw;
  16. int ret;
  17. raw = libraw_init(0);
  18. if (libraw_open_file(raw, filename) != LIBRAW_SUCCESS) {
  19. err("could not open file");
  20. libraw_close(raw);
  21. }
  22. if (libraw_unpack(raw) != LIBRAW_SUCCESS) {
  23. err("could not unpack file");
  24. libraw_close(raw);
  25. }
  26. raw->params.no_auto_bright = 1;
  27. if (libraw_dcraw_process(raw) != LIBRAW_SUCCESS) {
  28. err("could not process file");
  29. libraw_free_image(raw);
  30. libraw_close(raw);
  31. }
  32. libraw_processed_image_t *proc_img = libraw_dcraw_make_mem_image(raw, &ret);
  33. libraw_free_image(raw);
  34. if (!proc_img) {
  35. err("could not export image");
  36. libraw_close(raw);
  37. }
  38. libraw_recycle(raw);
  39. libraw_close(raw);
  40. return proc_img;
  41. }
  42. void
  43. save_jpeg(char *path, libraw_processed_image_t *data, int quality, ExifData *exif)
  44. {
  45. unsigned char *exif_data;
  46. unsigned int exif_len;
  47. FILE *out = fopen(path, "wb");
  48. if (!out) {
  49. err("could not open target file");
  50. exit(1);
  51. }
  52. struct jpeg_compress_struct jpeg;
  53. struct jpeg_error_mgr error_mgr;
  54. jpeg.err = jpeg_std_error(&error_mgr);
  55. jpeg_create_compress(&jpeg);
  56. jpeg_stdio_dest(&jpeg, out);
  57. jpeg.image_width = data->width;
  58. jpeg.image_height = data->height;
  59. jpeg.input_components = 3;
  60. jpeg.in_color_space = JCS_RGB;
  61. jpeg_set_defaults(&jpeg);
  62. jpeg_set_quality(&jpeg, quality, 1);
  63. jpeg_start_compress(&jpeg, 1);
  64. // Write exif
  65. exif_data_save_data(exif, &exif_data, &exif_len);
  66. jpeg_write_marker(&jpeg, JPEG_APP1, exif_data, exif_len);
  67. // Write image data
  68. JSAMPROW row_pointer;
  69. int row_stride = jpeg.image_width * jpeg.input_components;
  70. while (jpeg.next_scanline < jpeg.image_height) {
  71. row_pointer = (JSAMPROW) &data->data[jpeg.next_scanline * row_stride];
  72. jpeg_write_scanlines(&jpeg, &row_pointer, 1);
  73. }
  74. jpeg_finish_compress(&jpeg);
  75. jpeg_destroy_compress(&jpeg);
  76. fclose(out);
  77. }
  78. static ExifEntry *
  79. init_tag(ExifData *exif, ExifIfd ifd, ExifTag tag)
  80. {
  81. ExifEntry *entry;
  82. /* Return an existing tag if one exists */
  83. if (!((entry = exif_content_get_entry(exif->ifd[ifd], tag)))) {
  84. /* Allocate a new entry */
  85. entry = exif_entry_new();
  86. assert(entry != NULL); /* catch an out of memory condition */
  87. entry->tag = tag; /* tag must be set before calling
  88. exif_content_add_entry */
  89. /* Attach the ExifEntry to an IFD */
  90. exif_content_add_entry(exif->ifd[ifd], entry);
  91. /* Allocate memory for the entry and fill with default data */
  92. exif_entry_initialize(entry, tag);
  93. /* Ownership of the ExifEntry has now been passed to the IFD.
  94. * One must be very careful in accessing a structure after
  95. * unref'ing it; in this case, we know "entry" won't be freed
  96. * because the reference count was bumped when it was added to
  97. * the IFD.
  98. */
  99. exif_entry_unref(entry);
  100. }
  101. return entry;
  102. }
  103. void
  104. exif_set_string(ExifEntry *ed, const char *s, size_t size)
  105. {
  106. if (ed->data) {
  107. free(ed->data);
  108. }
  109. ed->components = size + 1;
  110. ed->size = sizeof(char) * ed->components;
  111. ed->data = (unsigned char *) malloc(ed->size);
  112. if (!ed->data) {
  113. err("Could not allocate exif string");
  114. exit(1);
  115. }
  116. strncpy((char *) ed->data, (char *) s, size);
  117. exif_entry_fix(ed);
  118. }
  119. ExifData *
  120. create_exif(struct Imagedata data)
  121. {
  122. ExifEntry *entry;
  123. ExifRational rational;
  124. long denominator = 100000;
  125. ExifData *exif = exif_data_new();
  126. if (!exif) {
  127. err("Could not initialize libexif");
  128. }
  129. exif_data_set_option(exif, EXIF_DATA_OPTION_FOLLOW_SPECIFICATION);
  130. exif_data_set_data_type(exif, EXIF_DATA_TYPE_COMPRESSED);
  131. exif_data_set_byte_order(exif, EXIF_BYTE_ORDER_INTEL);
  132. exif_data_fix(exif);
  133. // Width
  134. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_PIXEL_X_DIMENSION);
  135. exif_set_long(entry->data, EXIF_BYTE_ORDER_INTEL, data.width);
  136. // Height
  137. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_PIXEL_Y_DIMENSION);
  138. exif_set_long(entry->data, EXIF_BYTE_ORDER_INTEL, data.height);
  139. // Colorspace, 1=sRGB
  140. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_COLOR_SPACE);
  141. exif_set_long(entry->data, EXIF_BYTE_ORDER_INTEL, 1);
  142. // Exposure program, enum
  143. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_EXPOSURE_PROGRAM);
  144. exif_set_long(entry->data, EXIF_BYTE_ORDER_INTEL, data.exposure_program);
  145. // Camera make
  146. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_MAKE);
  147. exif_set_string(entry, data.make, strlen(data.make));
  148. // Camera model
  149. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_MODEL);
  150. exif_set_string(entry, data.model, strlen(data.model));
  151. // Processing software
  152. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_SOFTWARE);
  153. exif_set_string(entry, data.software, strlen(data.software));
  154. // Various datetime fields
  155. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME);
  156. exif_set_string(entry, data.datetime, strlen(data.datetime));
  157. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME_DIGITIZED);
  158. exif_set_string(entry, data.datetime, strlen(data.datetime));
  159. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME_ORIGINAL);
  160. exif_set_string(entry, data.datetime, strlen(data.datetime));
  161. // Exposure time
  162. rational.numerator = (long) ((double) data.exposure_time * denominator);
  163. rational.denominator = denominator;
  164. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_EXPOSURE_TIME);
  165. exif_set_rational(entry->data, EXIF_BYTE_ORDER_INTEL, rational);
  166. // fnumber
  167. rational.numerator = (long) ((double) data.fnumber * denominator);
  168. rational.denominator = denominator;
  169. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_FNUMBER);
  170. exif_set_rational(entry->data, EXIF_BYTE_ORDER_INTEL, rational);
  171. // focal length
  172. rational.numerator = (long) ((double) data.focal_length * denominator);
  173. rational.denominator = denominator;
  174. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_FOCAL_LENGTH);
  175. exif_set_rational(entry->data, EXIF_BYTE_ORDER_INTEL, rational);
  176. // focal length, 35mm equiv
  177. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_FOCAL_LENGTH_IN_35MM_FILM);
  178. exif_set_short(entry->data, EXIF_BYTE_ORDER_INTEL, data.focal_length_35mm);
  179. // ISO
  180. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_ISO_SPEED_RATINGS);
  181. exif_set_long(entry->data, EXIF_BYTE_ORDER_INTEL, data.isospeed);
  182. // Flash
  183. entry = init_tag(exif, EXIF_IFD_EXIF, EXIF_TAG_FLASH);
  184. exif_set_short(entry->data, EXIF_BYTE_ORDER_INTEL, data.flash);
  185. return exif;
  186. }
  187. struct Imagedata
  188. read_exif(char *filename)
  189. {
  190. struct Imagedata imagedata;
  191. uint16_t subifd_count;
  192. uint32_t *subifd_offsets;
  193. uint32_t exif_offset;
  194. uint32_t value_count;
  195. uint16_t *short_array;
  196. char *temp;
  197. libdng_info dng = {0};
  198. if (libdng_read(&dng, filename) != 1) {
  199. err("Could not load DNG file");
  200. }
  201. imagedata.make = strdup(dng.camera_make);
  202. imagedata.model = strdup(dng.camera_model);
  203. imagedata.datetime = malloc(20);
  204. imagedata.software = strdup(dng.software);
  205. strftime(imagedata.datetime, 20, "%Y:%m:%d %H:%M:%S", &dng.datetime);
  206. imagedata.orientation = dng.orientation;
  207. imagedata.width = dng.width;
  208. imagedata.height = dng.height;
  209. imagedata.bitspersample = dng.bit_depth;
  210. imagedata.exposure_time = dng.exposure_time;
  211. imagedata.exposure_program = dng.exposure_program;
  212. imagedata.fnumber = dng.fnumber;
  213. imagedata.isospeed = (uint16_t) dng.iso;
  214. imagedata.focal_length = dng.focal_length;
  215. imagedata.focal_length_35mm = (uint16_t) (dng.focal_length * dng.crop_factor);
  216. imagedata.dist_a = dng.distortion_a;
  217. imagedata.dist_b = dng.distortion_b;
  218. imagedata.dist_c = dng.distortion_c;
  219. imagedata.vignette_k1 = dng.vignette_k1;
  220. imagedata.vignette_k2 = dng.vignette_k2;
  221. imagedata.vignette_k3 = dng.vignette_k3;
  222. imagedata.flash = 0;
  223. return imagedata;
  224. }
  225. static int
  226. filter_dng(const struct dirent *dir)
  227. {
  228. if (!dir)
  229. return 0;
  230. if (dir->d_type == DT_REG) {
  231. const char *ext = strrchr(dir->d_name, '.');
  232. if ((!ext) || (ext == dir->d_name))
  233. return 0;
  234. else {
  235. if (strcmp(ext, ".dng") == 0)
  236. return 1;
  237. }
  238. }
  239. return 0;
  240. }
  241. void
  242. postprocess_setup(void)
  243. {
  244. libdng_init();
  245. }
  246. void
  247. postprocess_internal(char *burst_dir, char *target_dir, int keep)
  248. {
  249. struct dirent **namelist;
  250. int burst_size;
  251. int first = 1;
  252. struct Imagedata imagedata;
  253. libraw_processed_image_t *decoded;
  254. ExifData *exif;
  255. char path[512];
  256. char outpath[512];
  257. char stackpath[512];
  258. nice(19);
  259. burst_size = scandir(burst_dir, &namelist, filter_dng, alphasort);
  260. if (burst_size < 0) {
  261. printf("oop\n");
  262. exit(1);
  263. }
  264. if (burst_size == 0) {
  265. printf("No DNG files found\n");
  266. exit(1);
  267. }
  268. stacker_t *stacker = stacker_create(1, imagedata);
  269. while (burst_size--) {
  270. fprintf(stderr, "DEBAYER %s\n", namelist[burst_size]->d_name);
  271. snprintf(path, sizeof(path), "%s/%s", burst_dir, namelist[burst_size]->d_name);
  272. if (keep)
  273. snprintf(outpath, sizeof(outpath), "%s.%d.jpg", target_dir, burst_size);
  274. else
  275. snprintf(outpath, sizeof(outpath), "%s.jpg", target_dir);
  276. if (first) {
  277. imagedata = read_exif(path);
  278. exif = create_exif(imagedata);
  279. }
  280. decoded = debayer_file(path);
  281. if (keep || first) {
  282. fprintf(stderr, "JPEG %s\n", namelist[burst_size]->d_name);
  283. save_jpeg(outpath, decoded, 90, exif);
  284. }
  285. fprintf(stderr, "CONVERG %s\n", namelist[burst_size]->d_name);
  286. stacker_add_image(stacker, decoded->data, decoded->width, decoded->height);
  287. free(namelist[burst_size]);
  288. if (first) {
  289. first = 0;
  290. }
  291. }
  292. free(namelist);
  293. fprintf(stderr, "STACK stacked.jpg\n");
  294. // Convert opencv result to a libraw struct and feed it in the jpeg encoder with the original exif data
  295. char *stacked = stacker_get_result(stacker);
  296. decoded->width = stacker_get_width(stacker);
  297. decoded->height = stacker_get_height(stacker);
  298. int result_size = decoded->width * decoded->height * 3;
  299. libraw_processed_image_t *stacked_data = (libraw_processed_image_t *) malloc(
  300. sizeof(libraw_processed_image_t) + result_size);
  301. memset(stacked_data, 0, sizeof(libraw_processed_image_t));
  302. stacked_data->colors = 3;
  303. stacked_data->width = decoded->width;
  304. stacked_data->height = decoded->height;
  305. memmove(stacked_data->data, stacked, result_size);
  306. // Save the final file
  307. fprintf(stderr, "JPEG stacked.jpg\n");
  308. if (keep)
  309. snprintf(stackpath, sizeof(stackpath), "%s.stacked.jpg", target_dir);
  310. else
  311. snprintf(stackpath, sizeof(stackpath), "%s.jpg", target_dir);
  312. save_jpeg(stackpath, stacked_data, 90, exif);
  313. }
  314. void
  315. postprocess_single(char *in_path, char *out_path, int quality, int verbose)
  316. {
  317. libraw_processed_image_t *decoded;
  318. libraw_processed_image_t *processed_data;
  319. struct Imagedata imagedata;
  320. ExifData *exif;
  321. int width, height, result_size;
  322. char *result;
  323. clock_t timer;
  324. imagedata = read_exif(in_path);
  325. stacker_t *stacker = stacker_create(verbose, imagedata);
  326. // Give the operating system more cpu time
  327. nice(19);
  328. // Parse exif data from original file
  329. timer = clock();
  330. exif = create_exif(imagedata);
  331. if (verbose) {
  332. printf("[%.1fms] %s\n", (float) (clock() - timer) / CLOCKS_PER_SEC * 1000, "exif read");
  333. }
  334. // Convert the sensor data to rgb
  335. timer = clock();
  336. decoded = debayer_file(in_path);
  337. if (verbose) {
  338. printf("[%.1fms] %s\n", (float) (clock() - timer) / CLOCKS_PER_SEC * 1000, "debayer");
  339. }
  340. // Run the opencv postprocessing on the single frame
  341. result = stacker_postprocess(stacker, decoded->data, decoded->width, decoded->height);
  342. width = stacker_get_width(stacker);
  343. height = stacker_get_height(stacker);
  344. // Export the final jpeg with the original exif data
  345. timer = clock();
  346. result_size = width * height * 3;
  347. processed_data = (libraw_processed_image_t *) malloc(sizeof(libraw_processed_image_t) + result_size);
  348. memset(processed_data, 0, sizeof(libraw_processed_image_t));
  349. processed_data->colors = 3;
  350. processed_data->width = decoded->width;
  351. processed_data->height = decoded->height;
  352. memmove(processed_data->data, result, result_size);
  353. save_jpeg(out_path, processed_data, quality, exif);
  354. if (verbose) {
  355. printf("[%.1fms] %s\n", (float) (clock() - timer) / CLOCKS_PER_SEC * 1000, "export");
  356. }
  357. }