process_pipeline.c 13 KB

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