process_pipeline.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 "gl_quickpreview.h"
  9. #include <tiffio.h>
  10. #include <assert.h>
  11. #include <math.h>
  12. #include <wordexp.h>
  13. #include <gtk/gtk.h>
  14. #include "gl_utils.h"
  15. #include <EGL/egl.h>
  16. #include <EGL/eglext.h>
  17. #include <gdk/gdkwayland.h>
  18. #define TIFFTAG_FORWARDMATRIX1 50964
  19. static const float colormatrix_srgb[] = { 3.2409, -1.5373, -0.4986, -0.9692, 1.8759,
  20. 0.0415, 0.0556, -0.2039, 1.0569 };
  21. static MPPipeline *pipeline;
  22. static char burst_dir[23];
  23. static char processing_script[512];
  24. static volatile bool is_capturing = false;
  25. static volatile int frames_processed = 0;
  26. static volatile int frames_received = 0;
  27. static const struct mp_camera_config *camera;
  28. static MPCameraMode mode;
  29. static int burst_length;
  30. static int captures_remaining = 0;
  31. static int preview_width;
  32. static int preview_height;
  33. // static bool gain_is_manual;
  34. static int gain;
  35. static int gain_max;
  36. static bool exposure_is_manual;
  37. static int exposure;
  38. static char capture_fname[255];
  39. static void
  40. register_custom_tiff_tags(TIFF *tif)
  41. {
  42. static const TIFFFieldInfo custom_fields[] = {
  43. { TIFFTAG_FORWARDMATRIX1, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM, 1, 1,
  44. "ForwardMatrix1" },
  45. };
  46. // Add missing dng fields
  47. TIFFMergeFieldInfo(tif, custom_fields,
  48. sizeof(custom_fields) / sizeof(custom_fields[0]));
  49. }
  50. static bool
  51. find_processor(char *script)
  52. {
  53. char *xdg_config_home;
  54. char filename[] = "postprocess.sh";
  55. wordexp_t exp_result;
  56. // Resolve XDG stuff
  57. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  58. xdg_config_home = "~/.config";
  59. }
  60. wordexp(xdg_config_home, &exp_result, 0);
  61. xdg_config_home = strdup(exp_result.we_wordv[0]);
  62. wordfree(&exp_result);
  63. // Check postprocess.h in the current working directory
  64. sprintf(script, "%s", filename);
  65. if (access(script, F_OK) != -1) {
  66. sprintf(script, "./%s", filename);
  67. printf("Found postprocessor script at %s\n", script);
  68. return true;
  69. }
  70. // Check for a script in XDG_CONFIG_HOME
  71. sprintf(script, "%s/megapixels/%s", xdg_config_home, filename);
  72. if (access(script, F_OK) != -1) {
  73. printf("Found postprocessor script at %s\n", script);
  74. return true;
  75. }
  76. // Check user overridden /etc/megapixels/postprocessor.sh
  77. sprintf(script, "%s/megapixels/%s", SYSCONFDIR, filename);
  78. if (access(script, F_OK) != -1) {
  79. printf("Found postprocessor script at %s\n", script);
  80. return true;
  81. }
  82. // Check packaged /usr/share/megapixels/postprocessor.sh
  83. sprintf(script, "%s/megapixels/%s", DATADIR, filename);
  84. if (access(script, F_OK) != -1) {
  85. printf("Found postprocessor script at %s\n", script);
  86. return true;
  87. }
  88. return false;
  89. }
  90. static void
  91. setup(MPPipeline *pipeline, const void *data)
  92. {
  93. TIFFSetTagExtender(register_custom_tiff_tags);
  94. if (!find_processor(processing_script)) {
  95. g_printerr("Could not find any post-process script\n");
  96. exit(1);
  97. }
  98. }
  99. void
  100. mp_process_pipeline_start()
  101. {
  102. pipeline = mp_pipeline_new();
  103. mp_pipeline_invoke(pipeline, setup, NULL, 0);
  104. mp_zbar_pipeline_start();
  105. }
  106. void
  107. mp_process_pipeline_stop()
  108. {
  109. mp_pipeline_free(pipeline);
  110. mp_zbar_pipeline_stop();
  111. }
  112. void
  113. mp_process_pipeline_sync()
  114. {
  115. mp_pipeline_sync(pipeline);
  116. }
  117. #define NUM_BUFFERS 4
  118. static GLQuickPreview *gl_quick_preview_state = NULL;
  119. static EGLDisplay egl_display = EGL_NO_DISPLAY;
  120. static EGLContext egl_context = EGL_NO_CONTEXT;
  121. // struct buffer {
  122. // GLuint texture_id;
  123. // EGLImage egl_image;
  124. // int dma_fd;
  125. // int dma_stride;
  126. // int dma_offset;
  127. // void *data;
  128. // };
  129. // static struct buffer input_buffers[NUM_BUFFERS];
  130. // static struct buffer output_buffers[NUM_BUFFERS];
  131. static PFNEGLEXPORTDMABUFIMAGEMESAPROC eglExportDMABUFImageMESA;
  132. static const char *
  133. egl_get_error_str()
  134. {
  135. EGLint error = eglGetError();
  136. switch (error) {
  137. case EGL_SUCCESS: return "EGL_SUCCESS";
  138. case EGL_NOT_INITIALIZED: return "EGL_NOT_INITIALIZED";
  139. case EGL_BAD_ACCESS: return "EGL_BAD_ACCESS";
  140. case EGL_BAD_ALLOC: return "EGL_BAD_ALLOC";
  141. case EGL_BAD_ATTRIBUTE: return "EGL_BAD_ATTRIBUTE";
  142. case EGL_BAD_CONTEXT: return "EGL_BAD_CONTEXT";
  143. case EGL_BAD_CONFIG: return "EGL_BAD_CONFIG";
  144. case EGL_BAD_CURRENT_SURFACE: return "EGL_BAD_CURRENT_SURFACE";
  145. case EGL_BAD_DISPLAY: return "EGL_BAD_DISPLAY";
  146. case EGL_BAD_SURFACE: return "EGL_BAD_SURFACE";
  147. case EGL_BAD_MATCH: return "EGL_BAD_MATCH";
  148. case EGL_BAD_PARAMETER: return "EGL_BAD_PARAMETER";
  149. case EGL_BAD_NATIVE_PIXMAP: return "EGL_BAD_NATIVE_PIXMAP";
  150. case EGL_BAD_NATIVE_WINDOW: return "EGL_BAD_NATIVE_WINDOW";
  151. case EGL_CONTEXT_LOST: return "EGL_CONTEXT_LOST";
  152. }
  153. return "Unknown";
  154. }
  155. #define RENDERDOC
  156. #ifdef RENDERDOC
  157. #include <dlfcn.h>
  158. #include <renderdoc/app.h>
  159. RENDERDOC_API_1_1_2 *rdoc_api = NULL;
  160. #endif
  161. static void
  162. init_gl(MPPipeline *pipeline, GdkWindow **window)
  163. {
  164. #ifdef RENDERDOC
  165. {
  166. void *mod = dlopen("librenderdoc.so", RTLD_NOW | RTLD_NOLOAD);
  167. if (mod)
  168. {
  169. pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym(mod, "RENDERDOC_GetAPI");
  170. int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void **)&rdoc_api);
  171. assert(ret == 1);
  172. }
  173. else
  174. {
  175. printf("Renderdoc not found\n");
  176. }
  177. }
  178. #endif
  179. GdkDisplay *gdk_display = gdk_window_get_display(*window);
  180. egl_display = eglGetDisplay((EGLNativeDisplayType) gdk_wayland_display_get_wl_display(gdk_display));
  181. assert(egl_display != EGL_NO_DISPLAY);
  182. EGLint major, minor;
  183. if (!eglInitialize(egl_display, &major, &minor)) {
  184. printf("Failed to initialize egl: %s\n", egl_get_error_str());
  185. return;
  186. }
  187. if (!eglBindAPI(EGL_OPENGL_ES_API)) {
  188. printf("Failed to bind OpenGL ES: %s\n", egl_get_error_str());
  189. return;
  190. }
  191. printf("extensions: %s\n", eglQueryString(egl_display, EGL_EXTENSIONS));
  192. EGLint config_attrs[1] = {
  193. EGL_NONE
  194. };
  195. EGLConfig config;
  196. EGLint num_configs = 0;
  197. if (!eglChooseConfig(egl_display, config_attrs, &config, 1, &num_configs)) {
  198. printf("Failed to pick a egl config: %s\n", egl_get_error_str());
  199. return;
  200. }
  201. if (num_configs != 1) {
  202. printf("No egl configs found: %s\n", egl_get_error_str());
  203. return;
  204. }
  205. EGLint context_attrs[5] = {
  206. EGL_CONTEXT_CLIENT_VERSION,
  207. 2,
  208. EGL_CONTEXT_FLAGS_KHR,
  209. EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR,
  210. EGL_NONE,
  211. };
  212. egl_context = eglCreateContext(egl_display, config, NULL, context_attrs);
  213. if (egl_context == EGL_NO_CONTEXT) {
  214. printf("Failed to create OpenGL ES context: %s\n", egl_get_error_str());
  215. return;
  216. }
  217. if (!eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context))
  218. {
  219. printf("Failed to set current OpenGL context: %s\n", egl_get_error_str());
  220. return;
  221. }
  222. check_gl();
  223. eglExportDMABUFImageMESA = (PFNEGLEXPORTDMABUFIMAGEMESAPROC)
  224. eglGetProcAddress("eglExportDMABUFImageMESA");
  225. // Generate textures for the buffers
  226. // GLuint textures[NUM_BUFFERS * 2];
  227. // glGenTextures(NUM_BUFFERS * 2, textures);
  228. // for (size_t i = 0; i < NUM_BUFFERS; ++i) {
  229. // input_buffers[i].texture_id = textures[i];
  230. // input_buffers[i].egl_image = EGL_NO_IMAGE;
  231. // input_buffers[i].dma_fd = -1;
  232. // }
  233. // for (size_t i = 0; i < NUM_BUFFERS; ++i) {
  234. // output_buffers[i].texture_id = textures[NUM_BUFFERS + i];
  235. // output_buffers[i].egl_image = EGL_NO_IMAGE;
  236. // output_buffers[i].dma_fd = -1;
  237. // }
  238. check_gl();
  239. gl_quick_preview_state = gl_quick_preview_new();
  240. check_gl();
  241. printf("Initialized OpenGL\n");
  242. }
  243. void
  244. mp_process_pipeline_init_gl(GdkWindow *window)
  245. {
  246. mp_pipeline_invoke(pipeline, (MPPipelineCallback) init_gl, &window, sizeof(GdkWindow *));
  247. }
  248. static cairo_surface_t *
  249. process_image_for_preview(const uint8_t *image)
  250. {
  251. cairo_surface_t *surface;
  252. if (gl_quick_preview_state && ql_quick_preview_supports_format(gl_quick_preview_state, mode.pixel_format)) {
  253. #ifdef RENDERDOC
  254. if (rdoc_api) rdoc_api->StartFrameCapture(NULL, NULL);
  255. #endif
  256. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  257. check_gl();
  258. GLuint textures[2];
  259. glGenTextures(2, textures);
  260. glBindTexture(GL_TEXTURE_2D, textures[0]);
  261. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  262. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  263. glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, mode.width, mode.height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
  264. check_gl();
  265. glBindTexture(GL_TEXTURE_2D, textures[1]);
  266. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  267. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  268. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, preview_width, preview_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
  269. check_gl();
  270. gl_quick_preview(
  271. gl_quick_preview_state,
  272. textures[1], preview_width, preview_height,
  273. textures[0], mode.width, mode.height,
  274. mode.pixel_format,
  275. camera->rotate, camera->mirrored,
  276. camera->previewmatrix[0] == 0 ? NULL : camera->previewmatrix,
  277. camera->blacklevel);
  278. check_gl();
  279. surface = cairo_image_surface_create(
  280. CAIRO_FORMAT_RGB24, preview_width, preview_height);
  281. uint8_t *pixels = cairo_image_surface_get_data(surface);
  282. glReadPixels(0, 0, preview_width, preview_height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  283. check_gl();
  284. glBindTexture(GL_TEXTURE_2D, 0);
  285. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  286. #ifdef RENDERDOC
  287. if(rdoc_api) rdoc_api->EndFrameCapture(NULL, NULL);
  288. #endif
  289. } else {
  290. uint32_t surface_width, surface_height, skip;
  291. quick_preview_size(&surface_width, &surface_height, &skip, preview_width,
  292. preview_height, mode.width, mode.height,
  293. mode.pixel_format, camera->rotate);
  294. surface = cairo_image_surface_create(
  295. CAIRO_FORMAT_RGB24, surface_width, surface_height);
  296. uint8_t *pixels = cairo_image_surface_get_data(surface);
  297. quick_preview((uint32_t *)pixels, surface_width, surface_height, image,
  298. mode.width, mode.height, mode.pixel_format,
  299. camera->rotate, camera->mirrored,
  300. camera->previewmatrix[0] == 0 ? NULL : camera->previewmatrix,
  301. camera->blacklevel, skip);
  302. }
  303. // Create a thumbnail from the preview for the last capture
  304. cairo_surface_t *thumb = NULL;
  305. if (captures_remaining == 1) {
  306. printf("Making thumbnail\n");
  307. thumb = cairo_image_surface_create(
  308. CAIRO_FORMAT_ARGB32, MP_MAIN_THUMB_SIZE, MP_MAIN_THUMB_SIZE);
  309. cairo_t *cr = cairo_create(thumb);
  310. draw_surface_scaled_centered(
  311. cr, MP_MAIN_THUMB_SIZE, MP_MAIN_THUMB_SIZE, surface);
  312. cairo_destroy(cr);
  313. }
  314. // Pass processed preview to main and zbar
  315. mp_zbar_pipeline_process_image(cairo_surface_reference(surface));
  316. mp_main_set_preview(surface);
  317. return thumb;
  318. }
  319. static void
  320. process_image_for_capture(const uint8_t *image, int count)
  321. {
  322. time_t rawtime;
  323. time(&rawtime);
  324. struct tm tim = *(localtime(&rawtime));
  325. char datetime[20] = { 0 };
  326. strftime(datetime, 20, "%Y:%m:%d %H:%M:%S", &tim);
  327. char fname[255];
  328. sprintf(fname, "%s/%d.dng", burst_dir, count);
  329. TIFF *tif = TIFFOpen(fname, "w");
  330. if (!tif) {
  331. printf("Could not open tiff\n");
  332. }
  333. // Define TIFF thumbnail
  334. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 1);
  335. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, mode.width >> 4);
  336. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, mode.height >> 4);
  337. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  338. TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  339. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
  340. TIFFSetField(tif, TIFFTAG_MAKE, mp_get_device_make());
  341. TIFFSetField(tif, TIFFTAG_MODEL, mp_get_device_model());
  342. uint16_t orientation;
  343. if (camera->rotate == 0) {
  344. orientation = camera->mirrored ? ORIENTATION_TOPRIGHT :
  345. ORIENTATION_TOPLEFT;
  346. } else if (camera->rotate == 90) {
  347. orientation = camera->mirrored ? ORIENTATION_RIGHTBOT :
  348. ORIENTATION_LEFTBOT;
  349. } else if (camera->rotate == 180) {
  350. orientation = camera->mirrored ? ORIENTATION_BOTLEFT :
  351. ORIENTATION_BOTRIGHT;
  352. } else {
  353. orientation = camera->mirrored ? ORIENTATION_LEFTTOP :
  354. ORIENTATION_RIGHTTOP;
  355. }
  356. TIFFSetField(tif, TIFFTAG_ORIENTATION, orientation);
  357. TIFFSetField(tif, TIFFTAG_DATETIME, datetime);
  358. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
  359. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  360. TIFFSetField(tif, TIFFTAG_SOFTWARE, "Megapixels");
  361. long sub_offset = 0;
  362. TIFFSetField(tif, TIFFTAG_SUBIFD, 1, &sub_offset);
  363. TIFFSetField(tif, TIFFTAG_DNGVERSION, "\001\001\0\0");
  364. TIFFSetField(tif, TIFFTAG_DNGBACKWARDVERSION, "\001\0\0\0");
  365. char uniquecameramodel[255];
  366. sprintf(uniquecameramodel, "%s %s", mp_get_device_make(),
  367. mp_get_device_model());
  368. TIFFSetField(tif, TIFFTAG_UNIQUECAMERAMODEL, uniquecameramodel);
  369. if (camera->colormatrix[0]) {
  370. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, camera->colormatrix);
  371. } else {
  372. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, colormatrix_srgb);
  373. }
  374. if (camera->forwardmatrix[0]) {
  375. TIFFSetField(tif, TIFFTAG_FORWARDMATRIX1, 9, camera->forwardmatrix);
  376. }
  377. static const float neutral[] = { 1.0, 1.0, 1.0 };
  378. TIFFSetField(tif, TIFFTAG_ASSHOTNEUTRAL, 3, neutral);
  379. TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT1, 21);
  380. // Write black thumbnail, only windows uses this
  381. {
  382. unsigned char *buf =
  383. (unsigned char *)calloc(1, (int)mode.width >> 4);
  384. for (int row = 0; row < (mode.height >> 4); row++) {
  385. TIFFWriteScanline(tif, buf, row, 0);
  386. }
  387. free(buf);
  388. }
  389. TIFFWriteDirectory(tif);
  390. // Define main photo
  391. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 0);
  392. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, mode.width);
  393. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, mode.height);
  394. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  395. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CFA);
  396. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
  397. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  398. static const short cfapatterndim[] = { 2, 2 };
  399. TIFFSetField(tif, TIFFTAG_CFAREPEATPATTERNDIM, cfapatterndim);
  400. #if (TIFFLIB_VERSION < 20201219) && !LIBTIFF_CFA_PATTERN
  401. TIFFSetField(tif, TIFFTAG_CFAPATTERN, "\002\001\001\000"); // BGGR
  402. #else
  403. TIFFSetField(tif, TIFFTAG_CFAPATTERN, 4, "\002\001\001\000"); // BGGR
  404. #endif
  405. printf("TIFF version %d\n", TIFFLIB_VERSION);
  406. if (camera->whitelevel) {
  407. TIFFSetField(tif, TIFFTAG_WHITELEVEL, 1, &camera->whitelevel);
  408. }
  409. if (camera->blacklevel) {
  410. TIFFSetField(tif, TIFFTAG_BLACKLEVEL, 1, &camera->blacklevel);
  411. }
  412. TIFFCheckpointDirectory(tif);
  413. printf("Writing frame to %s\n", fname);
  414. unsigned char *pLine = (unsigned char *)malloc(mode.width);
  415. for (int row = 0; row < mode.height; row++) {
  416. TIFFWriteScanline(tif, (void *) image + (row * mode.width), row, 0);
  417. }
  418. free(pLine);
  419. TIFFWriteDirectory(tif);
  420. // Add an EXIF block to the tiff
  421. TIFFCreateEXIFDirectory(tif);
  422. // 1 = manual, 2 = full auto, 3 = aperture priority, 4 = shutter priority
  423. if (!exposure_is_manual) {
  424. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 2);
  425. } else {
  426. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 1);
  427. }
  428. TIFFSetField(tif, EXIFTAG_EXPOSURETIME,
  429. (mode.frame_interval.numerator /
  430. (float)mode.frame_interval.denominator) /
  431. ((float)mode.height / (float)exposure));
  432. uint16_t isospeed[1];
  433. isospeed[0] = (uint16_t)remap(gain - 1, 0, gain_max, camera->iso_min,
  434. camera->iso_max);
  435. TIFFSetField(tif, EXIFTAG_ISOSPEEDRATINGS, 1, isospeed);
  436. TIFFSetField(tif, EXIFTAG_FLASH, 0);
  437. TIFFSetField(tif, EXIFTAG_DATETIMEORIGINAL, datetime);
  438. TIFFSetField(tif, EXIFTAG_DATETIMEDIGITIZED, datetime);
  439. if (camera->fnumber) {
  440. TIFFSetField(tif, EXIFTAG_FNUMBER, camera->fnumber);
  441. }
  442. if (camera->focallength) {
  443. TIFFSetField(tif, EXIFTAG_FOCALLENGTH, camera->focallength);
  444. }
  445. if (camera->focallength && camera->cropfactor) {
  446. TIFFSetField(tif, EXIFTAG_FOCALLENGTHIN35MMFILM,
  447. (short)(camera->focallength * camera->cropfactor));
  448. }
  449. uint64_t exif_offset = 0;
  450. TIFFWriteCustomDirectory(tif, &exif_offset);
  451. TIFFFreeDirectory(tif);
  452. // Update exif pointer
  453. TIFFSetDirectory(tif, 0);
  454. TIFFSetField(tif, TIFFTAG_EXIFIFD, exif_offset);
  455. TIFFRewriteDirectory(tif);
  456. TIFFClose(tif);
  457. }
  458. static void
  459. post_process_finished(GSubprocess *proc, GAsyncResult *res, cairo_surface_t *thumb)
  460. {
  461. char *stdout;
  462. g_subprocess_communicate_utf8_finish(proc, res, &stdout, NULL, NULL);
  463. // The last line contains the file name
  464. int end = strlen(stdout);
  465. // Skip the newline at the end
  466. stdout[--end] = '\0';
  467. char *path = path = stdout + end - 1;
  468. do {
  469. if (*path == '\n') {
  470. path++;
  471. break;
  472. }
  473. --path;
  474. } while (path > stdout);
  475. mp_main_capture_completed(thumb, path);
  476. }
  477. static void
  478. process_capture_burst(cairo_surface_t *thumb)
  479. {
  480. time_t rawtime;
  481. time(&rawtime);
  482. struct tm tim = *(localtime(&rawtime));
  483. char timestamp[30];
  484. strftime(timestamp, 30, "%Y%m%d%H%M%S", &tim);
  485. if (g_get_user_special_dir(G_USER_DIRECTORY_PICTURES) != NULL) {
  486. sprintf(capture_fname,
  487. "%s/IMG%s",
  488. g_get_user_special_dir(G_USER_DIRECTORY_PICTURES),
  489. timestamp);
  490. } else if (getenv("XDG_PICTURES_DIR") != NULL) {
  491. sprintf(capture_fname,
  492. "%s/IMG%s",
  493. getenv("XDG_PICTURES_DIR"),
  494. timestamp);
  495. } else {
  496. sprintf(capture_fname,
  497. "%s/Pictures/IMG%s",
  498. getenv("HOME"),
  499. timestamp);
  500. }
  501. // Start post-processing the captured burst
  502. g_print("Post process %s to %s.ext\n", burst_dir, capture_fname);
  503. GError *error = NULL;
  504. GSubprocess *proc = g_subprocess_new(
  505. G_SUBPROCESS_FLAGS_STDOUT_PIPE,
  506. &error,
  507. processing_script,
  508. burst_dir,
  509. capture_fname,
  510. NULL);
  511. if (!proc) {
  512. g_printerr("Failed to spawn postprocess process: %s\n",
  513. error->message);
  514. return;
  515. }
  516. g_subprocess_communicate_utf8_async(
  517. proc,
  518. NULL,
  519. NULL,
  520. (GAsyncReadyCallback)post_process_finished,
  521. thumb);
  522. }
  523. static void
  524. process_image(MPPipeline *pipeline, const MPBuffer *buffer)
  525. {
  526. size_t size =
  527. mp_pixel_format_width_to_bytes(mode.pixel_format, mode.width) *
  528. mode.height;
  529. uint8_t *image = malloc(size);
  530. memcpy(image, buffer->data, size);
  531. mp_io_pipeline_release_buffer(buffer->index);
  532. cairo_surface_t *thumb = process_image_for_preview(image);
  533. if (captures_remaining > 0) {
  534. int count = burst_length - captures_remaining;
  535. --captures_remaining;
  536. process_image_for_capture(image, count);
  537. if (captures_remaining == 0) {
  538. assert(thumb);
  539. process_capture_burst(thumb);
  540. } else {
  541. assert(!thumb);
  542. }
  543. } else {
  544. assert(!thumb);
  545. }
  546. free(image);
  547. ++frames_processed;
  548. if (captures_remaining == 0) {
  549. is_capturing = false;
  550. }
  551. }
  552. void
  553. mp_process_pipeline_process_image(MPBuffer buffer)
  554. {
  555. // If we haven't processed the previous frame yet, drop this one
  556. if (frames_received != frames_processed && !is_capturing) {
  557. printf("Dropped frame at capture\n");
  558. mp_io_pipeline_release_buffer(buffer.index);
  559. return;
  560. }
  561. ++frames_received;
  562. mp_pipeline_invoke(pipeline, (MPPipelineCallback)process_image, &buffer,
  563. sizeof(MPBuffer));
  564. }
  565. static void
  566. capture()
  567. {
  568. char template[] = "/tmp/megapixels.XXXXXX";
  569. char *tempdir;
  570. tempdir = mkdtemp(template);
  571. if (tempdir == NULL) {
  572. g_printerr("Could not make capture directory %s\n", template);
  573. exit(EXIT_FAILURE);
  574. }
  575. strcpy(burst_dir, tempdir);
  576. captures_remaining = burst_length;
  577. }
  578. void
  579. mp_process_pipeline_capture()
  580. {
  581. is_capturing = true;
  582. mp_pipeline_invoke(pipeline, capture, NULL, 0);
  583. }
  584. static void
  585. update_state(MPPipeline *pipeline, const struct mp_process_pipeline_state *state)
  586. {
  587. camera = state->camera;
  588. mode = state->mode;
  589. burst_length = state->burst_length;
  590. preview_width = state->preview_width;
  591. preview_height = state->preview_height;
  592. // gain_is_manual = state->gain_is_manual;
  593. gain = state->gain;
  594. gain_max = state->gain_max;
  595. exposure_is_manual = state->exposure_is_manual;
  596. exposure = state->exposure;
  597. struct mp_main_state main_state = {
  598. .camera = camera,
  599. .mode = mode,
  600. .gain_is_manual = state->gain_is_manual,
  601. .gain = gain,
  602. .gain_max = gain_max,
  603. .exposure_is_manual = exposure_is_manual,
  604. .exposure = exposure,
  605. .has_auto_focus_continuous = state->has_auto_focus_continuous,
  606. .has_auto_focus_start = state->has_auto_focus_start,
  607. };
  608. mp_main_update_state(&main_state);
  609. }
  610. void
  611. mp_process_pipeline_update_state(const struct mp_process_pipeline_state *new_state)
  612. {
  613. mp_pipeline_invoke(pipeline, (MPPipelineCallback)update_state, new_state,
  614. sizeof(struct mp_process_pipeline_state));
  615. }