process_pipeline.c 14 KB

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