process_pipeline.c 13 KB

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