process_pipeline.c 21 KB

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