process_pipeline.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #include "process_pipeline.h"
  2. #include "pipeline.h"
  3. #include "main.h"
  4. #include "config.h"
  5. #include "quickpreview.h"
  6. #include <tiffio.h>
  7. #include <assert.h>
  8. #include <math.h>
  9. #include <wordexp.h>
  10. #include <gtk/gtk.h>
  11. #define TIFFTAG_FORWARDMATRIX1 50964
  12. static const float colormatrix_srgb[] = { 3.2409, -1.5373, -0.4986, -0.9692, 1.8759,
  13. 0.0415, 0.0556, -0.2039, 1.0569 };
  14. static MPPipeline *pipeline;
  15. static char burst_dir[23];
  16. static char processing_script[512];
  17. static volatile bool is_capturing = false;
  18. static volatile int frames_processed = 0;
  19. static volatile int frames_received = 0;
  20. static const struct mp_camera_config *camera;
  21. static MPCameraMode mode;
  22. static int burst_length;
  23. static int captures_remaining = 0;
  24. static int preview_width;
  25. static int preview_height;
  26. // static bool gain_is_manual;
  27. static int gain;
  28. static int gain_max;
  29. static bool exposure_is_manual;
  30. static int exposure;
  31. static char capture_fname[255];
  32. static void
  33. register_custom_tiff_tags(TIFF *tif)
  34. {
  35. static const TIFFFieldInfo custom_fields[] = {
  36. { TIFFTAG_FORWARDMATRIX1, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM, 1, 1,
  37. "ForwardMatrix1" },
  38. };
  39. // Add missing dng fields
  40. TIFFMergeFieldInfo(tif, custom_fields,
  41. sizeof(custom_fields) / sizeof(custom_fields[0]));
  42. }
  43. static bool
  44. find_processor(char *script)
  45. {
  46. char *xdg_config_home;
  47. char filename[] = "postprocess.sh";
  48. wordexp_t exp_result;
  49. // Resolve XDG stuff
  50. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  51. xdg_config_home = "~/.config";
  52. }
  53. wordexp(xdg_config_home, &exp_result, 0);
  54. xdg_config_home = strdup(exp_result.we_wordv[0]);
  55. wordfree(&exp_result);
  56. // Check postprocess.h in the current working directory
  57. sprintf(script, "%s", filename);
  58. if (access(script, F_OK) != -1) {
  59. sprintf(script, "./%s", filename);
  60. printf("Found postprocessor script at %s\n", script);
  61. return true;
  62. }
  63. // Check for a script in XDG_CONFIG_HOME
  64. sprintf(script, "%s/megapixels/%s", xdg_config_home, filename);
  65. if (access(script, F_OK) != -1) {
  66. printf("Found postprocessor script at %s\n", script);
  67. return true;
  68. }
  69. // Check user overridden /etc/megapixels/postprocessor.sh
  70. sprintf(script, "%s/megapixels/%s", SYSCONFDIR, filename);
  71. if (access(script, F_OK) != -1) {
  72. printf("Found postprocessor script at %s\n", script);
  73. return true;
  74. }
  75. // Check packaged /usr/share/megapixels/postprocessor.sh
  76. sprintf(script, "%s/megapixels/%s", DATADIR, filename);
  77. if (access(script, F_OK) != -1) {
  78. printf("Found postprocessor script at %s\n", script);
  79. return true;
  80. }
  81. return false;
  82. }
  83. static void
  84. setup(MPPipeline *pipeline, const void *data)
  85. {
  86. TIFFSetTagExtender(register_custom_tiff_tags);
  87. if (!find_processor(processing_script)) {
  88. g_printerr("Could not find any post-process script\n");
  89. exit(1);
  90. }
  91. }
  92. void
  93. mp_process_pipeline_start()
  94. {
  95. pipeline = mp_pipeline_new();
  96. mp_pipeline_invoke(pipeline, setup, NULL, 0);
  97. }
  98. void
  99. mp_process_pipeline_stop()
  100. {
  101. mp_pipeline_free(pipeline);
  102. }
  103. static cairo_surface_t *
  104. process_image_for_preview(const MPImage *image)
  105. {
  106. uint32_t surface_width, surface_height, skip;
  107. quick_preview_size(&surface_width, &surface_height, &skip, preview_width,
  108. preview_height, image->width, image->height,
  109. image->pixel_format, camera->rotate);
  110. cairo_surface_t *surface = cairo_image_surface_create(
  111. CAIRO_FORMAT_RGB24, surface_width, surface_height);
  112. uint8_t *pixels = cairo_image_surface_get_data(surface);
  113. quick_preview((uint32_t *)pixels, surface_width, surface_height, image->data,
  114. image->width, image->height, image->pixel_format,
  115. camera->rotate, camera->mirrored,
  116. camera->previewmatrix[0] == 0 ? NULL : camera->previewmatrix,
  117. camera->blacklevel, skip);
  118. // Create a thumbnail from the preview for the last capture
  119. cairo_surface_t *thumb = NULL;
  120. if (captures_remaining == 1) {
  121. printf("Making thumbnail\n");
  122. thumb = cairo_image_surface_create(
  123. CAIRO_FORMAT_ARGB32, MP_MAIN_THUMB_SIZE, MP_MAIN_THUMB_SIZE);
  124. cairo_t *cr = cairo_create(thumb);
  125. draw_surface_scaled_centered(
  126. cr, MP_MAIN_THUMB_SIZE, MP_MAIN_THUMB_SIZE, surface);
  127. cairo_destroy(cr);
  128. }
  129. // Pass processed preview to main
  130. mp_main_set_preview(surface);
  131. return thumb;
  132. }
  133. static void
  134. process_image_for_capture(const MPImage *image, int count)
  135. {
  136. time_t rawtime;
  137. time(&rawtime);
  138. struct tm tim = *(localtime(&rawtime));
  139. char datetime[20] = { 0 };
  140. strftime(datetime, 20, "%Y:%m:%d %H:%M:%S", &tim);
  141. char fname[255];
  142. sprintf(fname, "%s/%d.dng", burst_dir, count);
  143. TIFF *tif = TIFFOpen(fname, "w");
  144. if (!tif) {
  145. printf("Could not open tiff\n");
  146. }
  147. // Define TIFF thumbnail
  148. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 1);
  149. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, image->width >> 4);
  150. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, image->height >> 4);
  151. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  152. TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  153. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
  154. TIFFSetField(tif, TIFFTAG_MAKE, mp_get_device_make());
  155. TIFFSetField(tif, TIFFTAG_MODEL, mp_get_device_model());
  156. uint16_t orientation;
  157. if (camera->rotate == 0) {
  158. orientation = camera->mirrored ? ORIENTATION_TOPRIGHT :
  159. ORIENTATION_TOPLEFT;
  160. } else if (camera->rotate == 90) {
  161. orientation = camera->mirrored ? ORIENTATION_RIGHTBOT :
  162. ORIENTATION_LEFTBOT;
  163. } else if (camera->rotate == 180) {
  164. orientation = camera->mirrored ? ORIENTATION_BOTLEFT :
  165. ORIENTATION_BOTRIGHT;
  166. } else {
  167. orientation = camera->mirrored ? ORIENTATION_LEFTTOP :
  168. ORIENTATION_RIGHTTOP;
  169. }
  170. TIFFSetField(tif, TIFFTAG_ORIENTATION, orientation);
  171. TIFFSetField(tif, TIFFTAG_DATETIME, datetime);
  172. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
  173. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  174. TIFFSetField(tif, TIFFTAG_SOFTWARE, "Megapixels");
  175. long sub_offset = 0;
  176. TIFFSetField(tif, TIFFTAG_SUBIFD, 1, &sub_offset);
  177. TIFFSetField(tif, TIFFTAG_DNGVERSION, "\001\001\0\0");
  178. TIFFSetField(tif, TIFFTAG_DNGBACKWARDVERSION, "\001\0\0\0");
  179. char uniquecameramodel[255];
  180. sprintf(uniquecameramodel, "%s %s", mp_get_device_make(),
  181. mp_get_device_model());
  182. TIFFSetField(tif, TIFFTAG_UNIQUECAMERAMODEL, uniquecameramodel);
  183. if (camera->colormatrix[0]) {
  184. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, camera->colormatrix);
  185. } else {
  186. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, colormatrix_srgb);
  187. }
  188. if (camera->forwardmatrix[0]) {
  189. TIFFSetField(tif, TIFFTAG_FORWARDMATRIX1, 9, camera->forwardmatrix);
  190. }
  191. static const float neutral[] = { 1.0, 1.0, 1.0 };
  192. TIFFSetField(tif, TIFFTAG_ASSHOTNEUTRAL, 3, neutral);
  193. TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT1, 21);
  194. // Write black thumbnail, only windows uses this
  195. {
  196. unsigned char *buf =
  197. (unsigned char *)calloc(1, (int)image->width >> 4);
  198. for (int row = 0; row < (image->height >> 4); row++) {
  199. TIFFWriteScanline(tif, buf, row, 0);
  200. }
  201. free(buf);
  202. }
  203. TIFFWriteDirectory(tif);
  204. // Define main photo
  205. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 0);
  206. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, image->width);
  207. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, image->height);
  208. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  209. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CFA);
  210. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
  211. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  212. static const short cfapatterndim[] = { 2, 2 };
  213. TIFFSetField(tif, TIFFTAG_CFAREPEATPATTERNDIM, cfapatterndim);
  214. #if (TIFFLIB_VERSION < 20201219) && !LIBTIFF_CFA_PATTERN
  215. TIFFSetField(tif, TIFFTAG_CFAPATTERN, "\002\001\001\000"); // BGGR
  216. #else
  217. TIFFSetField(tif, TIFFTAG_CFAPATTERN, 4, "\002\001\001\000"); // BGGR
  218. #endif
  219. printf("TIFF version %d\n", TIFFLIB_VERSION);
  220. if (camera->whitelevel) {
  221. TIFFSetField(tif, TIFFTAG_WHITELEVEL, 1, &camera->whitelevel);
  222. }
  223. if (camera->blacklevel) {
  224. TIFFSetField(tif, TIFFTAG_BLACKLEVEL, 1, &camera->blacklevel);
  225. }
  226. TIFFCheckpointDirectory(tif);
  227. printf("Writing frame to %s\n", fname);
  228. unsigned char *pLine = (unsigned char *)malloc(image->width);
  229. for (int row = 0; row < image->height; row++) {
  230. TIFFWriteScanline(tif, image->data + (row * image->width), row, 0);
  231. }
  232. free(pLine);
  233. TIFFWriteDirectory(tif);
  234. // Add an EXIF block to the tiff
  235. TIFFCreateEXIFDirectory(tif);
  236. // 1 = manual, 2 = full auto, 3 = aperture priority, 4 = shutter priority
  237. if (!exposure_is_manual) {
  238. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 2);
  239. } else {
  240. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 1);
  241. }
  242. TIFFSetField(tif, EXIFTAG_EXPOSURETIME,
  243. (mode.frame_interval.numerator /
  244. (float)mode.frame_interval.denominator) /
  245. ((float)image->height / (float)exposure));
  246. uint16_t isospeed[1];
  247. isospeed[0] = (uint16_t)remap(gain - 1, 0, gain_max, camera->iso_min,
  248. camera->iso_max);
  249. TIFFSetField(tif, EXIFTAG_ISOSPEEDRATINGS, 1, isospeed);
  250. TIFFSetField(tif, EXIFTAG_FLASH, 0);
  251. TIFFSetField(tif, EXIFTAG_DATETIMEORIGINAL, datetime);
  252. TIFFSetField(tif, EXIFTAG_DATETIMEDIGITIZED, datetime);
  253. if (camera->fnumber) {
  254. TIFFSetField(tif, EXIFTAG_FNUMBER, camera->fnumber);
  255. }
  256. if (camera->focallength) {
  257. TIFFSetField(tif, EXIFTAG_FOCALLENGTH, camera->focallength);
  258. }
  259. if (camera->focallength && camera->cropfactor) {
  260. TIFFSetField(tif, EXIFTAG_FOCALLENGTHIN35MMFILM,
  261. (short)(camera->focallength * camera->cropfactor));
  262. }
  263. uint64_t exif_offset = 0;
  264. TIFFWriteCustomDirectory(tif, &exif_offset);
  265. TIFFFreeDirectory(tif);
  266. // Update exif pointer
  267. TIFFSetDirectory(tif, 0);
  268. TIFFSetField(tif, TIFFTAG_EXIFIFD, exif_offset);
  269. TIFFRewriteDirectory(tif);
  270. TIFFClose(tif);
  271. }
  272. static void
  273. post_process_finished(GSubprocess *proc, GAsyncResult *res, cairo_surface_t *thumb)
  274. {
  275. char *stdout;
  276. g_subprocess_communicate_utf8_finish(proc, res, &stdout, NULL, NULL);
  277. // The last line contains the file name
  278. int end = strlen(stdout);
  279. // Skip the newline at the end
  280. stdout[--end] = '\0';
  281. char *path = path = stdout + end - 1;
  282. do {
  283. if (*path == '\n') {
  284. path++;
  285. break;
  286. }
  287. --path;
  288. } while (path > stdout);
  289. mp_main_capture_completed(thumb, path);
  290. }
  291. static void
  292. process_capture_burst(cairo_surface_t *thumb)
  293. {
  294. time_t rawtime;
  295. time(&rawtime);
  296. struct tm tim = *(localtime(&rawtime));
  297. char timestamp[30];
  298. strftime(timestamp, 30, "%Y%m%d%H%M%S", &tim);
  299. sprintf(capture_fname,
  300. "%s/IMG%s",
  301. g_get_user_special_dir(G_USER_DIRECTORY_PICTURES),
  302. timestamp);
  303. // Start post-processing the captured burst
  304. g_print("Post process %s to %s.ext\n", burst_dir, capture_fname);
  305. GError *error = NULL;
  306. GSubprocess *proc = g_subprocess_new(
  307. G_SUBPROCESS_FLAGS_STDOUT_PIPE,
  308. &error,
  309. processing_script,
  310. burst_dir,
  311. capture_fname,
  312. NULL);
  313. if (!proc) {
  314. g_printerr("Failed to spawn postprocess process: %s\n",
  315. error->message);
  316. return;
  317. }
  318. g_subprocess_communicate_utf8_async(
  319. proc,
  320. NULL,
  321. NULL,
  322. (GAsyncReadyCallback)post_process_finished,
  323. thumb);
  324. }
  325. static void
  326. process_image(MPPipeline *pipeline, const MPImage *image)
  327. {
  328. assert(image->width == mode.width && image->height == mode.height);
  329. cairo_surface_t *thumb = process_image_for_preview(image);
  330. if (captures_remaining > 0) {
  331. int count = burst_length - captures_remaining;
  332. --captures_remaining;
  333. process_image_for_capture(image, count);
  334. if (captures_remaining == 0) {
  335. assert(thumb);
  336. process_capture_burst(thumb);
  337. } else {
  338. assert(!thumb);
  339. }
  340. } else {
  341. assert(!thumb);
  342. }
  343. free(image->data);
  344. ++frames_processed;
  345. if (captures_remaining == 0) {
  346. is_capturing = false;
  347. }
  348. }
  349. void
  350. mp_process_pipeline_process_image(MPImage image)
  351. {
  352. // If we haven't processed the previous frame yet, drop this one
  353. if (frames_received != frames_processed && !is_capturing) {
  354. printf("Dropped frame at capture\n");
  355. return;
  356. }
  357. ++frames_received;
  358. mp_pipeline_invoke(pipeline, (MPPipelineCallback)process_image, &image,
  359. sizeof(MPImage));
  360. }
  361. static void
  362. capture()
  363. {
  364. char template[] = "/tmp/megapixels.XXXXXX";
  365. char *tempdir;
  366. tempdir = mkdtemp(template);
  367. if (tempdir == NULL) {
  368. g_printerr("Could not make capture directory %s\n", template);
  369. exit(EXIT_FAILURE);
  370. }
  371. strcpy(burst_dir, tempdir);
  372. captures_remaining = burst_length;
  373. }
  374. void
  375. mp_process_pipeline_capture()
  376. {
  377. is_capturing = true;
  378. mp_pipeline_invoke(pipeline, capture, NULL, 0);
  379. }
  380. static void
  381. update_state(MPPipeline *pipeline, const struct mp_process_pipeline_state *state)
  382. {
  383. camera = state->camera;
  384. mode = state->mode;
  385. burst_length = state->burst_length;
  386. preview_width = state->preview_width;
  387. preview_height = state->preview_height;
  388. // gain_is_manual = state->gain_is_manual;
  389. gain = state->gain;
  390. gain_max = state->gain_max;
  391. exposure_is_manual = state->exposure_is_manual;
  392. exposure = state->exposure;
  393. struct mp_main_state main_state = {
  394. .camera = camera,
  395. .mode = mode,
  396. .gain_is_manual = state->gain_is_manual,
  397. .gain = gain,
  398. .gain_max = gain_max,
  399. .exposure_is_manual = exposure_is_manual,
  400. .exposure = exposure,
  401. .has_auto_focus_continuous = state->has_auto_focus_continuous,
  402. .has_auto_focus_start = state->has_auto_focus_start,
  403. };
  404. mp_main_update_state(&main_state);
  405. }
  406. void
  407. mp_process_pipeline_update_state(const struct mp_process_pipeline_state *new_state)
  408. {
  409. mp_pipeline_invoke(pipeline, (MPPipelineCallback)update_state, new_state,
  410. sizeof(struct mp_process_pipeline_state));
  411. }