main.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <linux/videodev2.h>
  4. #include <linux/media.h>
  5. #include <linux/v4l2-subdev.h>
  6. #include <sys/ioctl.h>
  7. #include <sys/mman.h>
  8. #include <sys/stat.h>
  9. #include <time.h>
  10. #include <assert.h>
  11. #include <limits.h>
  12. #include <linux/kdev_t.h>
  13. #include <sys/sysmacros.h>
  14. #include <asm/errno.h>
  15. #include <wordexp.h>
  16. #include <gtk/gtk.h>
  17. #include <tiffio.h>
  18. #include "config.h"
  19. #include "ini.h"
  20. #include "quickdebayer.h"
  21. enum user_control {
  22. USER_CONTROL_ISO,
  23. USER_CONTROL_SHUTTER
  24. };
  25. #define TIFFTAG_FORWARDMATRIX1 50964
  26. struct buffer {
  27. void *start;
  28. size_t length;
  29. };
  30. struct camerainfo {
  31. char dev_name[260];
  32. unsigned int entity_id;
  33. char dev[260];
  34. int width;
  35. int height;
  36. int rate;
  37. int rotate;
  38. int fmt;
  39. int mbus;
  40. int fd;
  41. float colormatrix[9];
  42. float forwardmatrix[9];
  43. int blacklevel;
  44. int whitelevel;
  45. float focallength;
  46. float cropfactor;
  47. double fnumber;
  48. int iso_min;
  49. int iso_max;
  50. int gain_ctrl;
  51. int gain_max;
  52. int has_af_c;
  53. int has_af_s;
  54. };
  55. static float colormatrix_srgb[] = {
  56. 3.2409, -1.5373, -0.4986,
  57. -0.9692, 1.8759, 0.0415,
  58. 0.0556, -0.2039, 1.0569
  59. };
  60. struct buffer *buffers;
  61. static unsigned int n_buffers;
  62. struct camerainfo rear_cam;
  63. struct camerainfo front_cam;
  64. struct camerainfo current;
  65. // Camera interface
  66. static char *media_drv_name;
  67. static unsigned int interface_entity_id;
  68. static char dev_name[260];
  69. static int media_fd;
  70. static int video_fd;
  71. static char *exif_make;
  72. static char *exif_model;
  73. // State
  74. static int ready = 0;
  75. static int capture = 0;
  76. static int current_is_rear = 1;
  77. static cairo_surface_t *surface = NULL;
  78. static cairo_surface_t *status_surface = NULL;
  79. static int preview_width = -1;
  80. static int preview_height = -1;
  81. static char *last_path = NULL;
  82. static int auto_exposure = 1;
  83. static int exposure = 1;
  84. static int auto_gain = 1;
  85. static int gain = 1;
  86. static int burst_length = 5;
  87. static char burst_dir[23];
  88. static char processing_script[512];
  89. static enum user_control current_control;
  90. // Widgets
  91. GtkWidget *preview;
  92. GtkWidget *error_box;
  93. GtkWidget *error_message;
  94. GtkWidget *main_stack;
  95. GtkWidget *thumb_last;
  96. GtkWidget *control_box;
  97. GtkWidget *control_name;
  98. GtkWidget *control_slider;
  99. GtkWidget *control_auto;
  100. static int
  101. xioctl(int fd, int request, void *arg)
  102. {
  103. int r;
  104. do {
  105. r = ioctl(fd, request, arg);
  106. } while (r == -1 && errno == EINTR);
  107. return r;
  108. }
  109. static void
  110. errno_exit(const char *s)
  111. {
  112. fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));
  113. exit(EXIT_FAILURE);
  114. }
  115. static void
  116. show_error(const char *s)
  117. {
  118. gtk_label_set_text(GTK_LABEL(error_message), s);
  119. gtk_widget_show(error_box);
  120. }
  121. int
  122. remap(int value, int input_min, int input_max, int output_min, int output_max)
  123. {
  124. const long long factor = 1000000000;
  125. long long output_spread = output_max - output_min;
  126. long long input_spread = input_max - input_min;
  127. long long zero_value = value - input_min;
  128. zero_value *= factor;
  129. long long percentage = zero_value / input_spread;
  130. long long zero_output = percentage * output_spread / factor;
  131. long long result = output_min + zero_output;
  132. return (int)result;
  133. }
  134. static void
  135. start_capturing(int fd)
  136. {
  137. enum v4l2_buf_type type;
  138. for (int i = 0; i < n_buffers; ++i) {
  139. struct v4l2_buffer buf = {
  140. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  141. .memory = V4L2_MEMORY_MMAP,
  142. .index = i,
  143. };
  144. if (xioctl(fd, VIDIOC_QBUF, &buf) == -1) {
  145. errno_exit("VIDIOC_QBUF");
  146. }
  147. }
  148. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  149. if (xioctl(fd, VIDIOC_STREAMON, &type) == -1) {
  150. errno_exit("VIDIOC_STREAMON");
  151. }
  152. ready = 1;
  153. }
  154. static void
  155. stop_capturing(int fd)
  156. {
  157. int i;
  158. ready = 0;
  159. printf("Stopping capture\n");
  160. enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  161. if (xioctl(fd, VIDIOC_STREAMOFF, &type) == -1) {
  162. errno_exit("VIDIOC_STREAMOFF");
  163. }
  164. for (i = 0; i < n_buffers; ++i) {
  165. munmap(buffers[i].start, buffers[i].length);
  166. }
  167. }
  168. static void
  169. init_mmap(int fd)
  170. {
  171. struct v4l2_requestbuffers req = {0};
  172. req.count = 4;
  173. req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  174. req.memory = V4L2_MEMORY_MMAP;
  175. if (xioctl(fd, VIDIOC_REQBUFS, &req) == -1) {
  176. if (errno == EINVAL) {
  177. fprintf(stderr, "%s does not support memory mapping",
  178. dev_name);
  179. exit(EXIT_FAILURE);
  180. } else {
  181. errno_exit("VIDIOC_REQBUFS");
  182. }
  183. }
  184. if (req.count < 2) {
  185. fprintf(stderr, "Insufficient buffer memory on %s\n",
  186. dev_name);
  187. exit(EXIT_FAILURE);
  188. }
  189. buffers = calloc(req.count, sizeof(buffers[0]));
  190. if (!buffers) {
  191. fprintf(stderr, "Out of memory\\n");
  192. exit(EXIT_FAILURE);
  193. }
  194. for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
  195. struct v4l2_buffer buf = {
  196. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  197. .memory = V4L2_MEMORY_MMAP,
  198. .index = n_buffers,
  199. };
  200. if (xioctl(fd, VIDIOC_QUERYBUF, &buf) == -1) {
  201. errno_exit("VIDIOC_QUERYBUF");
  202. }
  203. buffers[n_buffers].length = buf.length;
  204. buffers[n_buffers].start = mmap(NULL /* start anywhere */,
  205. buf.length,
  206. PROT_READ | PROT_WRITE /* required */,
  207. MAP_SHARED /* recommended */,
  208. fd, buf.m.offset);
  209. if (MAP_FAILED == buffers[n_buffers].start) {
  210. errno_exit("mmap");
  211. }
  212. }
  213. }
  214. static int
  215. v4l2_ctrl_set(int fd, uint32_t id, int val)
  216. {
  217. struct v4l2_control ctrl = {0};
  218. ctrl.id = id;
  219. ctrl.value = val;
  220. if (xioctl(fd, VIDIOC_S_CTRL, &ctrl) == -1) {
  221. g_printerr("Failed to set control %d to %d\n", id, val);
  222. return -1;
  223. }
  224. return 0;
  225. }
  226. static int
  227. v4l2_ctrl_get(int fd, uint32_t id)
  228. {
  229. struct v4l2_control ctrl = {0};
  230. ctrl.id = id;
  231. if (xioctl(fd, VIDIOC_G_CTRL, &ctrl) == -1) {
  232. g_printerr("Failed to get control %d\n", id);
  233. return -1;
  234. }
  235. return ctrl.value;
  236. }
  237. static int
  238. v4l2_ctrl_get_max(int fd, uint32_t id)
  239. {
  240. struct v4l2_queryctrl queryctrl;
  241. int ret;
  242. memset(&queryctrl, 0, sizeof(queryctrl));
  243. queryctrl.id = id;
  244. ret = xioctl(fd, VIDIOC_QUERYCTRL, &queryctrl);
  245. if (ret)
  246. return 0;
  247. if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) {
  248. return 0;
  249. }
  250. return queryctrl.maximum;
  251. }
  252. static int
  253. v4l2_has_control(int fd, int control_id)
  254. {
  255. struct v4l2_queryctrl queryctrl;
  256. int ret;
  257. memset(&queryctrl, 0, sizeof(queryctrl));
  258. queryctrl.id = control_id;
  259. ret = xioctl(fd, VIDIOC_QUERYCTRL, &queryctrl);
  260. if (ret)
  261. return 0;
  262. if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) {
  263. return 0;
  264. }
  265. return 1;
  266. }
  267. static void
  268. draw_controls()
  269. {
  270. cairo_t *cr;
  271. char iso[6];
  272. int temp;
  273. char shutterangle[6];
  274. if (auto_exposure) {
  275. sprintf(shutterangle, "auto");
  276. } else {
  277. temp = (int)((float)exposure / (float)current.height * 360);
  278. sprintf(shutterangle, "%d\u00b0", temp);
  279. }
  280. if (auto_gain) {
  281. sprintf(iso, "auto");
  282. } else {
  283. temp = remap(gain - 1, 0, current.gain_max, current.iso_min, current.iso_max);
  284. sprintf(iso, "%d", temp);
  285. }
  286. if (status_surface)
  287. cairo_surface_destroy(status_surface);
  288. // Make a service to show status of controls, 32px high
  289. status_surface = gdk_window_create_similar_surface(gtk_widget_get_window(preview),
  290. CAIRO_CONTENT_COLOR_ALPHA,
  291. preview_width, 32);
  292. cr = cairo_create(status_surface);
  293. cairo_set_source_rgba(cr, 0, 0, 0, 0.0);
  294. cairo_paint(cr);
  295. // Draw the outlines for the headings
  296. cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
  297. cairo_set_font_size(cr, 9);
  298. cairo_set_source_rgba(cr, 0, 0, 0, 1);
  299. cairo_move_to(cr, 16, 16);
  300. cairo_text_path(cr, "ISO");
  301. cairo_stroke(cr);
  302. cairo_move_to(cr, 60, 16);
  303. cairo_text_path(cr, "Shutter");
  304. cairo_stroke(cr);
  305. // Draw the fill for the headings
  306. cairo_set_source_rgba(cr, 1, 1, 1, 1);
  307. cairo_move_to(cr, 16, 16);
  308. cairo_show_text(cr, "ISO");
  309. cairo_move_to(cr, 60, 16);
  310. cairo_show_text(cr, "Shutter");
  311. // Draw the outlines for the values
  312. cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
  313. cairo_set_font_size(cr, 11);
  314. cairo_set_source_rgba(cr, 0, 0, 0, 1);
  315. cairo_move_to(cr, 16, 26);
  316. cairo_text_path(cr, iso);
  317. cairo_stroke(cr);
  318. cairo_move_to(cr, 60, 26);
  319. cairo_text_path(cr, shutterangle);
  320. cairo_stroke(cr);
  321. // Draw the fill for the values
  322. cairo_set_source_rgba(cr, 1, 1, 1, 1);
  323. cairo_move_to(cr, 16, 26);
  324. cairo_show_text(cr, iso);
  325. cairo_move_to(cr, 60, 26);
  326. cairo_show_text(cr, shutterangle);
  327. cairo_destroy(cr);
  328. }
  329. static void
  330. init_sensor(char *fn, int width, int height, int mbus, int rate)
  331. {
  332. int fd;
  333. struct v4l2_subdev_frame_interval interval = {};
  334. struct v4l2_subdev_format fmt = {};
  335. fd = open(fn, O_RDWR);
  336. g_printerr("Setting sensor rate to %d\n", rate);
  337. interval.pad = 0;
  338. interval.interval.numerator = 1;
  339. interval.interval.denominator = rate;
  340. if (xioctl(fd, VIDIOC_SUBDEV_S_FRAME_INTERVAL, &interval) == -1) {
  341. errno_exit("VIDIOC_SUBDEV_S_FRAME_INTERVAL");
  342. }
  343. g_printerr("Driver returned %d/%d frameinterval\n",
  344. interval.interval.numerator, interval.interval.denominator);
  345. g_printerr("Setting sensor to %dx%d fmt %d\n",
  346. width, height, mbus);
  347. fmt.pad = 0;
  348. fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
  349. fmt.format.code = mbus;
  350. fmt.format.width = width;
  351. fmt.format.height = height;
  352. fmt.format.field = V4L2_FIELD_ANY;
  353. if (xioctl(fd, VIDIOC_SUBDEV_S_FMT, &fmt) == -1) {
  354. errno_exit("VIDIOC_SUBDEV_S_FMT");
  355. }
  356. g_printerr("Driver returned %dx%d fmt %d\n",
  357. fmt.format.width, fmt.format.height,
  358. fmt.format.code);
  359. // Trigger continuous auto focus if the sensor supports it
  360. if (v4l2_has_control(fd, V4L2_CID_FOCUS_AUTO)) {
  361. current.has_af_c = 1;
  362. v4l2_ctrl_set(fd, V4L2_CID_FOCUS_AUTO, 1);
  363. }
  364. if (v4l2_has_control(fd, V4L2_CID_AUTO_FOCUS_START)) {
  365. current.has_af_s = 1;
  366. }
  367. if (v4l2_has_control(fd, V4L2_CID_GAIN)) {
  368. current.gain_ctrl = V4L2_CID_GAIN;
  369. current.gain_max = v4l2_ctrl_get_max(fd, V4L2_CID_GAIN);
  370. }
  371. if (v4l2_has_control(fd, V4L2_CID_ANALOGUE_GAIN)) {
  372. current.gain_ctrl = V4L2_CID_ANALOGUE_GAIN;
  373. current.gain_max = v4l2_ctrl_get_max(fd, V4L2_CID_ANALOGUE_GAIN);
  374. }
  375. auto_exposure = 1;
  376. auto_gain = 1;
  377. draw_controls();
  378. close(current.fd);
  379. current.fd = fd;
  380. }
  381. static int
  382. init_device(int fd)
  383. {
  384. struct v4l2_capability cap;
  385. if (xioctl(fd, VIDIOC_QUERYCAP, &cap) == -1) {
  386. if (errno == EINVAL) {
  387. fprintf(stderr, "%s is no V4L2 device\n",
  388. dev_name);
  389. exit(EXIT_FAILURE);
  390. } else {
  391. errno_exit("VIDIOC_QUERYCAP");
  392. }
  393. }
  394. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  395. fprintf(stderr, "%s is no video capture device\n",
  396. dev_name);
  397. exit(EXIT_FAILURE);
  398. }
  399. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  400. fprintf(stderr, "%s does not support streaming i/o\n",
  401. dev_name);
  402. exit(EXIT_FAILURE);
  403. }
  404. /* Select video input, video standard and tune here. */
  405. struct v4l2_cropcap cropcap = {
  406. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  407. };
  408. struct v4l2_crop crop = {0};
  409. if (xioctl(fd, VIDIOC_CROPCAP, &cropcap) == 0) {
  410. crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  411. crop.c = cropcap.defrect; /* reset to default */
  412. if (xioctl(fd, VIDIOC_S_CROP, &crop) == -1) {
  413. switch (errno) {
  414. case EINVAL:
  415. /* Cropping not supported. */
  416. break;
  417. default:
  418. /* Errors ignored. */
  419. break;
  420. }
  421. }
  422. } else {
  423. /* Errors ignored. */
  424. }
  425. struct v4l2_format fmt = {
  426. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  427. };
  428. if (current.width > 0) {
  429. g_printerr("Setting camera to %dx%d fmt %d\n",
  430. current.width, current.height, current.fmt);
  431. fmt.fmt.pix.width = current.width;
  432. fmt.fmt.pix.height = current.height;
  433. fmt.fmt.pix.pixelformat = current.fmt;
  434. fmt.fmt.pix.field = V4L2_FIELD_ANY;
  435. if (xioctl(fd, VIDIOC_S_FMT, &fmt) == -1) {
  436. g_printerr("VIDIOC_S_FMT failed");
  437. show_error("Could not set camera mode");
  438. return -1;
  439. }
  440. g_printerr("Driver returned %dx%d fmt %d\n",
  441. fmt.fmt.pix.width, fmt.fmt.pix.height,
  442. fmt.fmt.pix.pixelformat);
  443. /* Note VIDIOC_S_FMT may change width and height. */
  444. } else {
  445. g_printerr("Querying camera format\n");
  446. /* Preserve original settings as set by v4l2-ctl for example */
  447. if (xioctl(fd, VIDIOC_G_FMT, &fmt) == -1) {
  448. errno_exit("VIDIOC_G_FMT");
  449. }
  450. g_printerr("Driver returned %dx%d fmt %d\n",
  451. fmt.fmt.pix.width, fmt.fmt.pix.height,
  452. fmt.fmt.pix.pixelformat);
  453. current.width = fmt.fmt.pix.width;
  454. current.height = fmt.fmt.pix.height;
  455. }
  456. current.fmt = fmt.fmt.pix.pixelformat;
  457. /* Buggy driver paranoia. */
  458. unsigned int min = fmt.fmt.pix.width * 2;
  459. if (fmt.fmt.pix.bytesperline < min) {
  460. fmt.fmt.pix.bytesperline = min;
  461. }
  462. min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
  463. if (fmt.fmt.pix.sizeimage < min) {
  464. fmt.fmt.pix.sizeimage = min;
  465. }
  466. init_mmap(fd);
  467. return 0;
  468. }
  469. static void
  470. register_custom_tiff_tags(TIFF *tif)
  471. {
  472. static const TIFFFieldInfo custom_fields[] = {
  473. {TIFFTAG_FORWARDMATRIX1, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM, 1, 1, "ForwardMatrix1"},
  474. };
  475. // Add missing dng fields
  476. TIFFMergeFieldInfo(tif, custom_fields, sizeof(custom_fields) / sizeof(custom_fields[0]));
  477. }
  478. static void
  479. process_image(const int *p, int size)
  480. {
  481. time_t rawtime;
  482. char datetime[20] = {0};
  483. struct tm tim;
  484. uint8_t *pixels;
  485. char fname[255];
  486. char fname_target[255];
  487. char command[1024];
  488. char timestamp[30];
  489. char uniquecameramodel[255];
  490. GdkPixbuf *pixbuf;
  491. GdkPixbuf *pixbufrot;
  492. GdkPixbuf *thumb;
  493. GError *error = NULL;
  494. double scale;
  495. cairo_t *cr;
  496. TIFF *tif;
  497. int skip = 2;
  498. long sub_offset = 0;
  499. uint64 exif_offset = 0;
  500. static const short cfapatterndim[] = {2, 2};
  501. static const float neutral[] = {1.0, 1.0, 1.0};
  502. static uint16_t isospeed[] = {0};
  503. // Only process preview frames when not capturing
  504. if (capture == 0) {
  505. if(current.width > 1280) {
  506. skip = 3;
  507. }
  508. pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, current.width / (skip*2), current.height / (skip*2));
  509. pixels = gdk_pixbuf_get_pixels(pixbuf);
  510. quick_debayer_bggr8((const uint8_t *)p, pixels, current.width, current.height, skip);
  511. if (current.rotate == 0) {
  512. pixbufrot = pixbuf;
  513. } else if (current.rotate == 90) {
  514. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE);
  515. } else if (current.rotate == 180) {
  516. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_UPSIDEDOWN);
  517. } else if (current.rotate == 270) {
  518. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_CLOCKWISE);
  519. }
  520. // Draw preview image
  521. scale = (double) preview_width / gdk_pixbuf_get_width(pixbufrot);
  522. cr = cairo_create(surface);
  523. cairo_set_source_rgb(cr, 0, 0, 0);
  524. cairo_paint(cr);
  525. cairo_scale(cr, scale, scale);
  526. gdk_cairo_set_source_pixbuf(cr, pixbufrot, 0, 0);
  527. cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_NONE);
  528. cairo_paint(cr);
  529. // Draw controls over preview
  530. cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
  531. cairo_set_source_surface(cr, status_surface, 0, 0);
  532. cairo_paint(cr);
  533. // Queue gtk3 repaint of the preview area
  534. gtk_widget_queue_draw_area(preview, 0, 0, preview_width, preview_height);
  535. cairo_destroy(cr);
  536. g_object_unref(pixbufrot);
  537. g_object_unref(pixbuf);
  538. } else {
  539. capture--;
  540. time(&rawtime);
  541. tim = *(localtime(&rawtime));
  542. strftime(timestamp, 30, "%Y%m%d%H%M%S", &tim);
  543. strftime(datetime, 20, "%Y:%m:%d %H:%M:%S", &tim);
  544. sprintf(fname_target, "%s/Pictures/IMG%s", getenv("HOME"), timestamp);
  545. sprintf(fname, "%s/%d.dng", burst_dir, burst_length - capture);
  546. // Get latest exposure and gain now the auto gain/exposure is disabled while capturing
  547. gain = v4l2_ctrl_get(current.fd, current.gain_ctrl);
  548. exposure = v4l2_ctrl_get(current.fd, V4L2_CID_EXPOSURE);
  549. if(!(tif = TIFFOpen(fname, "w"))) {
  550. printf("Could not open tiff\n");
  551. }
  552. // Define TIFF thumbnail
  553. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 1);
  554. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, current.width >> 4);
  555. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, current.height >> 4);
  556. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  557. TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  558. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
  559. TIFFSetField(tif, TIFFTAG_MAKE, exif_make);
  560. TIFFSetField(tif, TIFFTAG_MODEL, exif_model);
  561. TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
  562. TIFFSetField(tif, TIFFTAG_DATETIME, datetime);
  563. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
  564. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  565. TIFFSetField(tif, TIFFTAG_SOFTWARE, "Megapixels");
  566. TIFFSetField(tif, TIFFTAG_SUBIFD, 1, &sub_offset);
  567. TIFFSetField(tif, TIFFTAG_DNGVERSION, "\001\001\0\0");
  568. TIFFSetField(tif, TIFFTAG_DNGBACKWARDVERSION, "\001\0\0\0");
  569. sprintf(uniquecameramodel, "%s %s", exif_make, exif_model);
  570. TIFFSetField(tif, TIFFTAG_UNIQUECAMERAMODEL, uniquecameramodel);
  571. if(current.colormatrix[0]) {
  572. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, current.colormatrix);
  573. } else {
  574. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, colormatrix_srgb);
  575. }
  576. if(current.forwardmatrix[0]) {
  577. TIFFSetField(tif, TIFFTAG_FORWARDMATRIX1, 9, current.forwardmatrix);
  578. }
  579. TIFFSetField(tif, TIFFTAG_ASSHOTNEUTRAL, 3, neutral);
  580. TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT1, 21);
  581. // Write black thumbnail, only windows uses this
  582. {
  583. unsigned char *buf = (unsigned char *)calloc(1, (int)current.width >> 4);
  584. for (int row = 0; row < current.height>>4; row++) {
  585. TIFFWriteScanline(tif, buf, row, 0);
  586. }
  587. free(buf);
  588. }
  589. TIFFWriteDirectory(tif);
  590. // Define main photo
  591. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 0);
  592. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, current.width);
  593. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, current.height);
  594. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  595. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CFA);
  596. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
  597. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  598. TIFFSetField(tif, TIFFTAG_CFAREPEATPATTERNDIM, cfapatterndim);
  599. TIFFSetField(tif, TIFFTAG_CFAPATTERN, "\002\001\001\000"); // BGGR
  600. if(current.whitelevel) {
  601. TIFFSetField(tif, TIFFTAG_WHITELEVEL, 1, &current.whitelevel);
  602. }
  603. if(current.blacklevel) {
  604. TIFFSetField(tif, TIFFTAG_BLACKLEVEL, 1, &current.blacklevel);
  605. }
  606. TIFFCheckpointDirectory(tif);
  607. printf("Writing frame to %s\n", fname);
  608. unsigned char *pLine = (unsigned char*)malloc(current.width);
  609. for(int row = 0; row < current.height; row++){
  610. TIFFWriteScanline(tif, ((uint8_t *)p)+(row*current.width), row, 0);
  611. }
  612. free(pLine);
  613. TIFFWriteDirectory(tif);
  614. // Add an EXIF block to the tiff
  615. TIFFCreateEXIFDirectory(tif);
  616. // 1 = manual, 2 = full auto, 3 = aperture priority, 4 = shutter priority
  617. if (auto_exposure) {
  618. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 2);
  619. } else {
  620. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 1);
  621. }
  622. TIFFSetField(tif, EXIFTAG_EXPOSURETIME, (1.0/current.rate) / ((float)current.height / (float)exposure));
  623. isospeed[0] = (uint16_t)remap(gain - 1, 0, current.gain_max, current.iso_min, current.iso_max);
  624. TIFFSetField(tif, EXIFTAG_ISOSPEEDRATINGS, 1, isospeed);
  625. TIFFSetField(tif, EXIFTAG_FLASH, 0);
  626. TIFFSetField(tif, EXIFTAG_DATETIMEORIGINAL, datetime);
  627. TIFFSetField(tif, EXIFTAG_DATETIMEDIGITIZED, datetime);
  628. if(current.fnumber) {
  629. TIFFSetField(tif, EXIFTAG_FNUMBER, current.fnumber);
  630. }
  631. if(current.focallength) {
  632. TIFFSetField(tif, EXIFTAG_FOCALLENGTH, current.focallength);
  633. }
  634. if(current.focallength && current.cropfactor) {
  635. TIFFSetField(tif, EXIFTAG_FOCALLENGTHIN35MMFILM, (short)(current.focallength * current.cropfactor));
  636. }
  637. TIFFWriteCustomDirectory(tif, &exif_offset);
  638. TIFFFreeDirectory(tif);
  639. // Update exif pointer
  640. TIFFSetDirectory(tif, 0);
  641. TIFFSetField(tif, TIFFTAG_EXIFIFD, exif_offset);
  642. TIFFRewriteDirectory(tif);
  643. TIFFClose(tif);
  644. if (capture == 0) {
  645. // Update the thumbnail if this is the last frame
  646. pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, current.width / (skip*2), current.height / (skip*2));
  647. pixels = gdk_pixbuf_get_pixels(pixbuf);
  648. quick_debayer_bggr8((const uint8_t *)p, pixels, current.width, current.height, skip);
  649. if (current.rotate == 0) {
  650. pixbufrot = pixbuf;
  651. } else if (current.rotate == 90) {
  652. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE);
  653. } else if (current.rotate == 180) {
  654. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_UPSIDEDOWN);
  655. } else if (current.rotate == 270) {
  656. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_CLOCKWISE);
  657. }
  658. thumb = gdk_pixbuf_scale_simple(pixbufrot, 24, 24, GDK_INTERP_BILINEAR);
  659. gtk_image_set_from_pixbuf(GTK_IMAGE(thumb_last), thumb);
  660. last_path = strdup(fname);
  661. if (error != NULL) {
  662. g_printerr("%s\n", error->message);
  663. g_clear_error(&error);
  664. }
  665. g_object_unref(pixbufrot);
  666. g_object_unref(pixbuf);
  667. // Start post-processing the captured burst
  668. g_printerr("Post process %s to %s.ext\n", burst_dir, fname_target);
  669. sprintf(command, "%s %s %s &", processing_script, burst_dir, fname_target);
  670. system(command);
  671. // Restore the auto exposure and gain if needed
  672. if (auto_exposure) {
  673. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_AUTO);
  674. }
  675. if (auto_gain) {
  676. v4l2_ctrl_set(current.fd, V4L2_CID_AUTOGAIN, 1);
  677. }
  678. }
  679. }
  680. }
  681. static gboolean
  682. preview_draw(GtkWidget *widget, cairo_t *cr, gpointer data)
  683. {
  684. cairo_set_source_surface(cr, surface, 0, 0);
  685. cairo_paint(cr);
  686. return FALSE;
  687. }
  688. static gboolean
  689. preview_configure(GtkWidget *widget, GdkEventConfigure *event)
  690. {
  691. cairo_t *cr;
  692. if (surface)
  693. cairo_surface_destroy(surface);
  694. surface = gdk_window_create_similar_surface(gtk_widget_get_window(widget),
  695. CAIRO_CONTENT_COLOR,
  696. gtk_widget_get_allocated_width(widget),
  697. gtk_widget_get_allocated_height(widget));
  698. preview_width = gtk_widget_get_allocated_width(widget);
  699. preview_height = gtk_widget_get_allocated_height(widget);
  700. cr = cairo_create(surface);
  701. cairo_set_source_rgb(cr, 0, 0, 0);
  702. cairo_paint(cr);
  703. cairo_destroy(cr);
  704. draw_controls();
  705. return TRUE;
  706. }
  707. static int
  708. read_frame(int fd)
  709. {
  710. struct v4l2_buffer buf = {0};
  711. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  712. buf.memory = V4L2_MEMORY_MMAP;
  713. if (xioctl(fd, VIDIOC_DQBUF, &buf) == -1) {
  714. switch (errno) {
  715. case EAGAIN:
  716. return 0;
  717. case EIO:
  718. /* Could ignore EIO, see spec. */
  719. /* fallthrough */
  720. default:
  721. errno_exit("VIDIOC_DQBUF");
  722. break;
  723. }
  724. }
  725. //assert(buf.index < n_buffers);
  726. process_image(buffers[buf.index].start, buf.bytesused);
  727. if (xioctl(fd, VIDIOC_QBUF, &buf) == -1) {
  728. errno_exit("VIDIOC_QBUF");
  729. }
  730. return 1;
  731. }
  732. gboolean
  733. get_frame()
  734. {
  735. if (ready == 0)
  736. return TRUE;
  737. while (1) {
  738. fd_set fds;
  739. struct timeval tv;
  740. int r;
  741. FD_ZERO(&fds);
  742. FD_SET(video_fd, &fds);
  743. /* Timeout. */
  744. tv.tv_sec = 2;
  745. tv.tv_usec = 0;
  746. r = select(video_fd + 1, &fds, NULL, NULL, &tv);
  747. if (r == -1) {
  748. if (EINTR == errno) {
  749. continue;
  750. }
  751. errno_exit("select");
  752. } else if (r == 0) {
  753. fprintf(stderr, "select timeout\\n");
  754. exit(EXIT_FAILURE);
  755. }
  756. if (read_frame(video_fd)) {
  757. break;
  758. }
  759. /* EAGAIN - continue select loop. */
  760. }
  761. return TRUE;
  762. }
  763. int
  764. strtoint(const char *nptr, char **endptr, int base)
  765. {
  766. long x = strtol(nptr, endptr, base);
  767. assert(x <= INT_MAX);
  768. return (int) x;
  769. }
  770. static int
  771. config_ini_handler(void *user, const char *section, const char *name,
  772. const char *value)
  773. {
  774. struct camerainfo *cc;
  775. if (strcmp(section, "rear") == 0 || strcmp(section, "front") == 0) {
  776. if (strcmp(section, "rear") == 0) {
  777. cc = &rear_cam;
  778. } else {
  779. cc = &front_cam;
  780. }
  781. if (strcmp(name, "width") == 0) {
  782. cc->width = strtoint(value, NULL, 10);
  783. } else if (strcmp(name, "height") == 0) {
  784. cc->height = strtoint(value, NULL, 10);
  785. } else if (strcmp(name, "rate") == 0) {
  786. cc->rate = strtoint(value, NULL, 10);
  787. } else if (strcmp(name, "rotate") == 0) {
  788. cc->rotate = strtoint(value, NULL, 10);
  789. } else if (strcmp(name, "fmt") == 0) {
  790. if (strcmp(value, "RGGB8") == 0) {
  791. cc->fmt = V4L2_PIX_FMT_SRGGB8;
  792. } else if (strcmp(value, "BGGR8") == 0) {
  793. cc->fmt = V4L2_PIX_FMT_SBGGR8;
  794. cc->mbus = MEDIA_BUS_FMT_SBGGR8_1X8;
  795. } else if (strcmp(value, "GRBG8") == 0) {
  796. cc->fmt = V4L2_PIX_FMT_SGRBG8;
  797. } else if (strcmp(value, "GBRG8") == 0) {
  798. cc->fmt = V4L2_PIX_FMT_SGBRG8;
  799. } else {
  800. g_printerr("Unsupported pixelformat %s\n", value);
  801. exit(1);
  802. }
  803. } else if (strcmp(name, "driver") == 0) {
  804. strcpy(cc->dev_name, value);
  805. } else if (strcmp(name, "colormatrix") == 0) {
  806. sscanf(value, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
  807. cc->colormatrix+0,
  808. cc->colormatrix+1,
  809. cc->colormatrix+2,
  810. cc->colormatrix+3,
  811. cc->colormatrix+4,
  812. cc->colormatrix+5,
  813. cc->colormatrix+6,
  814. cc->colormatrix+7,
  815. cc->colormatrix+8
  816. );
  817. } else if (strcmp(name, "forwardmatrix") == 0) {
  818. sscanf(value, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
  819. cc->forwardmatrix+0,
  820. cc->forwardmatrix+1,
  821. cc->forwardmatrix+2,
  822. cc->forwardmatrix+3,
  823. cc->forwardmatrix+4,
  824. cc->forwardmatrix+5,
  825. cc->forwardmatrix+6,
  826. cc->forwardmatrix+7,
  827. cc->forwardmatrix+8
  828. );
  829. } else if (strcmp(name, "whitelevel") == 0) {
  830. cc->whitelevel = strtoint(value, NULL, 10);
  831. } else if (strcmp(name, "blacklevel") == 0) {
  832. cc->blacklevel = strtoint(value, NULL, 10);
  833. } else if (strcmp(name, "focallength") == 0) {
  834. cc->focallength = strtof(value, NULL);
  835. } else if (strcmp(name, "cropfactor") == 0) {
  836. cc->cropfactor = strtof(value, NULL);
  837. } else if (strcmp(name, "fnumber") == 0) {
  838. cc->fnumber = strtod(value, NULL);
  839. } else if (strcmp(name, "iso-min") == 0) {
  840. cc->iso_min = strtod(value, NULL);
  841. } else if (strcmp(name, "iso-max") == 0) {
  842. cc->iso_max = strtod(value, NULL);
  843. } else {
  844. g_printerr("Unknown key '%s' in [%s]\n", name, section);
  845. exit(1);
  846. }
  847. } else if (strcmp(section, "device") == 0) {
  848. if (strcmp(name, "csi") == 0) {
  849. media_drv_name = strdup(value);
  850. } else if (strcmp(name, "make") == 0) {
  851. exif_make = strdup(value);
  852. } else if (strcmp(name, "model") == 0) {
  853. exif_model = strdup(value);
  854. } else {
  855. g_printerr("Unknown key '%s' in [device]\n", name);
  856. exit(1);
  857. }
  858. } else {
  859. g_printerr("Unknown section '%s' in config file\n", section);
  860. exit(1);
  861. }
  862. return 1;
  863. }
  864. int
  865. find_dev_node(int maj, int min, char *fnbuf)
  866. {
  867. DIR *d;
  868. struct dirent *dir;
  869. struct stat info;
  870. d = opendir("/dev");
  871. while ((dir = readdir(d)) != NULL) {
  872. sprintf(fnbuf, "/dev/%s", dir->d_name);
  873. stat(fnbuf, &info);
  874. if (!S_ISCHR(info.st_mode)) {
  875. continue;
  876. }
  877. if (major(info.st_rdev) == maj && minor(info.st_rdev) == min) {
  878. return 0;
  879. }
  880. }
  881. return -1;
  882. }
  883. int
  884. setup_rear()
  885. {
  886. struct media_link_desc link = {0};
  887. // Disable the interface<->front link
  888. link.flags = 0;
  889. link.source.entity = front_cam.entity_id;
  890. link.source.index = 0;
  891. link.sink.entity = interface_entity_id;
  892. link.sink.index = 0;
  893. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  894. g_printerr("Could not disable front camera link\n");
  895. return -1;
  896. }
  897. // Enable the interface<->rear link
  898. link.flags = MEDIA_LNK_FL_ENABLED;
  899. link.source.entity = rear_cam.entity_id;
  900. link.source.index = 0;
  901. link.sink.entity = interface_entity_id;
  902. link.sink.index = 0;
  903. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  904. g_printerr("Could not enable rear camera link\n");
  905. return -1;
  906. }
  907. current = rear_cam;
  908. // Find camera node
  909. init_sensor(current.dev, current.width, current.height, current.mbus, current.rate);
  910. return 0;
  911. }
  912. int
  913. setup_front()
  914. {
  915. struct media_link_desc link = {0};
  916. // Disable the interface<->rear link
  917. link.flags = 0;
  918. link.source.entity = rear_cam.entity_id;
  919. link.source.index = 0;
  920. link.sink.entity = interface_entity_id;
  921. link.sink.index = 0;
  922. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  923. g_printerr("Could not disable rear camera link\n");
  924. return -1;
  925. }
  926. // Enable the interface<->rear link
  927. link.flags = MEDIA_LNK_FL_ENABLED;
  928. link.source.entity = front_cam.entity_id;
  929. link.source.index = 0;
  930. link.sink.entity = interface_entity_id;
  931. link.sink.index = 0;
  932. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  933. g_printerr("Could not enable front camera link\n");
  934. return -1;
  935. }
  936. current = front_cam;
  937. // Find camera node
  938. init_sensor(current.dev, current.width, current.height, current.mbus, current.rate);
  939. return 0;
  940. }
  941. int
  942. find_cameras()
  943. {
  944. struct media_entity_desc entity = {0};
  945. int ret;
  946. int found = 0;
  947. while (1) {
  948. entity.id = entity.id | MEDIA_ENT_ID_FLAG_NEXT;
  949. ret = xioctl(media_fd, MEDIA_IOC_ENUM_ENTITIES, &entity);
  950. if (ret < 0) {
  951. break;
  952. }
  953. printf("At node %s, (0x%x)\n", entity.name, entity.type);
  954. if (strncmp(entity.name, front_cam.dev_name, strlen(front_cam.dev_name)) == 0) {
  955. front_cam.entity_id = entity.id;
  956. find_dev_node(entity.dev.major, entity.dev.minor, front_cam.dev);
  957. printf("Found front cam, is %s at %s\n", entity.name, front_cam.dev);
  958. found++;
  959. }
  960. if (strncmp(entity.name, rear_cam.dev_name, strlen(rear_cam.dev_name)) == 0) {
  961. rear_cam.entity_id = entity.id;
  962. find_dev_node(entity.dev.major, entity.dev.minor, rear_cam.dev);
  963. printf("Found rear cam, is %s at %s\n", entity.name, rear_cam.dev);
  964. found++;
  965. }
  966. if (entity.type == MEDIA_ENT_F_IO_V4L) {
  967. interface_entity_id = entity.id;
  968. find_dev_node(entity.dev.major, entity.dev.minor, dev_name);
  969. printf("Found v4l2 interface node at %s\n", dev_name);
  970. }
  971. }
  972. if (found < 2) {
  973. return -1;
  974. }
  975. return 0;
  976. }
  977. int
  978. find_media_fd()
  979. {
  980. DIR *d;
  981. struct dirent *dir;
  982. int fd;
  983. char fnbuf[261];
  984. struct media_device_info mdi = {0};
  985. d = opendir("/dev");
  986. while ((dir = readdir(d)) != NULL) {
  987. if (strncmp(dir->d_name, "media", 5) == 0) {
  988. sprintf(fnbuf, "/dev/%s", dir->d_name);
  989. printf("Checking %s\n", fnbuf);
  990. fd = open(fnbuf, O_RDWR);
  991. xioctl(fd, MEDIA_IOC_DEVICE_INFO, &mdi);
  992. printf("Found media device: %s\n", mdi.driver);
  993. if (strcmp(mdi.driver, media_drv_name) == 0) {
  994. media_fd = fd;
  995. return 0;
  996. }
  997. close(fd);
  998. }
  999. }
  1000. return 1;
  1001. }
  1002. void
  1003. on_open_last_clicked(GtkWidget *widget, gpointer user_data)
  1004. {
  1005. char uri[270];
  1006. GError *error = NULL;
  1007. if(!last_path) {
  1008. return;
  1009. }
  1010. sprintf(uri, "file://%s", last_path);
  1011. if(!g_app_info_launch_default_for_uri(uri, NULL, &error)){
  1012. g_printerr("Could not launch image viewer: %s\n", error->message);
  1013. }
  1014. }
  1015. void
  1016. on_open_directory_clicked(GtkWidget *widget, gpointer user_data)
  1017. {
  1018. char uri[270];
  1019. GError *error = NULL;
  1020. sprintf(uri, "file://%s/Pictures", getenv("HOME"));
  1021. if(!g_app_info_launch_default_for_uri(uri, NULL, &error)){
  1022. g_printerr("Could not launch image viewer: %s\n", error->message);
  1023. }
  1024. }
  1025. void
  1026. on_shutter_clicked(GtkWidget *widget, gpointer user_data)
  1027. {
  1028. char template[] = "/tmp/megapixels.XXXXXX";
  1029. char *tempdir;
  1030. tempdir = mkdtemp(template);
  1031. if (tempdir == NULL) {
  1032. g_printerr("Could not make capture directory %s\n", template);
  1033. exit (EXIT_FAILURE);
  1034. }
  1035. strcpy(burst_dir, tempdir);
  1036. // Disable the autogain/exposure while taking the burst
  1037. v4l2_ctrl_set(current.fd, V4L2_CID_AUTOGAIN, 0);
  1038. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
  1039. capture = burst_length;
  1040. }
  1041. void
  1042. on_preview_tap(GtkWidget *widget, GdkEventButton *event, gpointer user_data)
  1043. {
  1044. if (event->type != GDK_BUTTON_PRESS)
  1045. return;
  1046. // Handle taps on the controls
  1047. if (event->y < 32) {
  1048. if (gtk_widget_is_visible(control_box)) {
  1049. gtk_widget_hide(control_box);
  1050. return;
  1051. } else {
  1052. gtk_widget_show(control_box);
  1053. }
  1054. if (event->x < 60 ) {
  1055. // ISO
  1056. current_control = USER_CONTROL_ISO;
  1057. gtk_label_set_text(GTK_LABEL(control_name), "ISO");
  1058. gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(control_auto), auto_gain);
  1059. gtk_adjustment_set_lower(GTK_ADJUSTMENT(control_slider), 0.0);
  1060. gtk_adjustment_set_upper(GTK_ADJUSTMENT(control_slider), (float)current.gain_max);
  1061. gtk_adjustment_set_value(GTK_ADJUSTMENT(control_slider), (double)gain);
  1062. } else if (event->x > 60 && event->x < 120) {
  1063. // Shutter angle
  1064. current_control = USER_CONTROL_SHUTTER;
  1065. gtk_label_set_text(GTK_LABEL(control_name), "Shutter");
  1066. gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(control_auto), auto_exposure);
  1067. gtk_adjustment_set_lower(GTK_ADJUSTMENT(control_slider), 1.0);
  1068. gtk_adjustment_set_upper(GTK_ADJUSTMENT(control_slider), 360.0);
  1069. gtk_adjustment_set_value(GTK_ADJUSTMENT(control_slider), (double)exposure);
  1070. }
  1071. return;
  1072. }
  1073. // Tapped preview image itself, try focussing
  1074. if (current.has_af_s) {
  1075. v4l2_ctrl_set(current.fd, V4L2_CID_AUTO_FOCUS_STOP, 1);
  1076. v4l2_ctrl_set(current.fd, V4L2_CID_AUTO_FOCUS_START, 1);
  1077. }
  1078. }
  1079. void
  1080. on_error_close_clicked(GtkWidget *widget, gpointer user_data)
  1081. {
  1082. gtk_widget_hide(error_box);
  1083. }
  1084. void
  1085. on_camera_switch_clicked(GtkWidget *widget, gpointer user_data)
  1086. {
  1087. stop_capturing(video_fd);
  1088. close(current.fd);
  1089. if (current_is_rear == 1) {
  1090. setup_front();
  1091. current_is_rear = 0;
  1092. } else {
  1093. setup_rear();
  1094. current_is_rear = 1;
  1095. }
  1096. close(video_fd);
  1097. video_fd = open(dev_name, O_RDWR);
  1098. if (video_fd == -1) {
  1099. g_printerr("Error opening video device: %s\n", dev_name);
  1100. return;
  1101. }
  1102. init_device(video_fd);
  1103. start_capturing(video_fd);
  1104. }
  1105. void
  1106. on_settings_btn_clicked(GtkWidget *widget, gpointer user_data)
  1107. {
  1108. gtk_stack_set_visible_child_name(GTK_STACK(main_stack), "settings");
  1109. }
  1110. void
  1111. on_back_clicked(GtkWidget *widget, gpointer user_data)
  1112. {
  1113. gtk_stack_set_visible_child_name(GTK_STACK(main_stack), "main");
  1114. }
  1115. void
  1116. on_control_auto_toggled(GtkToggleButton *widget, gpointer user_data)
  1117. {
  1118. int fd = current.fd;
  1119. switch (current_control) {
  1120. case USER_CONTROL_ISO:
  1121. auto_gain = gtk_toggle_button_get_active(widget);
  1122. if (auto_gain) {
  1123. v4l2_ctrl_set(fd, V4L2_CID_AUTOGAIN, 1);
  1124. } else {
  1125. v4l2_ctrl_set(fd, V4L2_CID_AUTOGAIN, 0);
  1126. gain = v4l2_ctrl_get(fd, V4L2_CID_GAIN);
  1127. gtk_adjustment_set_value(GTK_ADJUSTMENT(control_slider), (double)gain);
  1128. }
  1129. break;
  1130. case USER_CONTROL_SHUTTER:
  1131. auto_exposure = gtk_toggle_button_get_active(widget);
  1132. if (auto_exposure) {
  1133. v4l2_ctrl_set(fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_AUTO);
  1134. } else {
  1135. v4l2_ctrl_set(fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
  1136. exposure = v4l2_ctrl_get(fd, V4L2_CID_EXPOSURE);
  1137. gtk_adjustment_set_value(GTK_ADJUSTMENT(control_slider), (double)exposure);
  1138. }
  1139. break;
  1140. }
  1141. draw_controls();
  1142. }
  1143. void
  1144. on_control_slider_changed(GtkAdjustment *widget, gpointer user_data)
  1145. {
  1146. double value = gtk_adjustment_get_value(widget);
  1147. switch (current_control) {
  1148. case USER_CONTROL_ISO:
  1149. gain = (int)value;
  1150. v4l2_ctrl_set(current.fd, current.gain_ctrl, gain);
  1151. break;
  1152. case USER_CONTROL_SHUTTER:
  1153. // So far all sensors use exposure time in number of sensor rows
  1154. exposure = (int)(value / 360.0 * current.height);
  1155. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE, exposure);
  1156. break;
  1157. }
  1158. draw_controls();
  1159. }
  1160. int
  1161. find_config(char *conffile)
  1162. {
  1163. char buf[512];
  1164. char *xdg_config_home;
  1165. wordexp_t exp_result;
  1166. FILE *fp;
  1167. // Resolve XDG stuff
  1168. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  1169. xdg_config_home = "~/.config";
  1170. }
  1171. wordexp(xdg_config_home, &exp_result, 0);
  1172. xdg_config_home = strdup(exp_result.we_wordv[0]);
  1173. wordfree(&exp_result);
  1174. if(access("/proc/device-tree/compatible", F_OK) != -1) {
  1175. // Reads to compatible string of the current device tree, looks like:
  1176. // pine64,pinephone-1.2\0allwinner,sun50i-a64\0
  1177. fp = fopen("/proc/device-tree/compatible", "r");
  1178. fgets(buf, 512, fp);
  1179. fclose(fp);
  1180. // Check config/%dt.ini in the current working directory
  1181. sprintf(conffile, "config/%s.ini", buf);
  1182. if(access(conffile, F_OK) != -1) {
  1183. printf("Found config file at %s\n", conffile);
  1184. return 0;
  1185. }
  1186. // Check for a config file in XDG_CONFIG_HOME
  1187. sprintf(conffile, "%s/megapixels/config/%s.ini", xdg_config_home, buf);
  1188. if(access(conffile, F_OK) != -1) {
  1189. printf("Found config file at %s\n", conffile);
  1190. return 0;
  1191. }
  1192. // Check user overridden /etc/megapixels/config/$dt.ini
  1193. sprintf(conffile, "%s/megapixels/config/%s.ini", SYSCONFDIR, buf);
  1194. if(access(conffile, F_OK) != -1) {
  1195. printf("Found config file at %s\n", conffile);
  1196. return 0;
  1197. }
  1198. // Check packaged /usr/share/megapixels/config/$dt.ini
  1199. sprintf(conffile, "%s/megapixels/config/%s.ini", DATADIR, buf);
  1200. if(access(conffile, F_OK) != -1) {
  1201. printf("Found config file at %s\n", conffile);
  1202. return 0;
  1203. }
  1204. printf("%s not found\n", conffile);
  1205. } else {
  1206. printf("Could not read device name from device tree\n");
  1207. }
  1208. // If all else fails, fall back to /etc/megapixels.ini
  1209. conffile = "/etc/megapixels.ini";
  1210. if(access(conffile, F_OK) != -1) {
  1211. printf("Found config file at %s\n", conffile);
  1212. return 0;
  1213. }
  1214. return -1;
  1215. }
  1216. int
  1217. find_processor(char *script)
  1218. {
  1219. char *xdg_config_home;
  1220. char filename[] = "postprocess.sh";
  1221. wordexp_t exp_result;
  1222. // Resolve XDG stuff
  1223. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  1224. xdg_config_home = "~/.config";
  1225. }
  1226. wordexp(xdg_config_home, &exp_result, 0);
  1227. xdg_config_home = strdup(exp_result.we_wordv[0]);
  1228. wordfree(&exp_result);
  1229. // Check postprocess.h in the current working directory
  1230. sprintf(script, "%s", filename);
  1231. if(access(script, F_OK) != -1) {
  1232. sprintf(script, "./%s", filename);
  1233. printf("Found postprocessor script at %s\n", script);
  1234. return 0;
  1235. }
  1236. // Check for a script in XDG_CONFIG_HOME
  1237. sprintf(script, "%s/megapixels/%s", xdg_config_home, filename);
  1238. if(access(script, F_OK) != -1) {
  1239. printf("Found postprocessor script at %s\n", script);
  1240. return 0;
  1241. }
  1242. // Check user overridden /etc/megapixels/postprocessor.sh
  1243. sprintf(script, "%s/megapixels/%s", SYSCONFDIR, filename);
  1244. if(access(script, F_OK) != -1) {
  1245. printf("Found postprocessor script at %s\n", script);
  1246. return 0;
  1247. }
  1248. // Check packaged /usr/share/megapixels/postprocessor.sh
  1249. sprintf(script, "%s/megapixels/%s", DATADIR, filename);
  1250. if(access(script, F_OK) != -1) {
  1251. printf("Found postprocessor script at %s\n", script);
  1252. return 0;
  1253. }
  1254. return -1;
  1255. }
  1256. int
  1257. main(int argc, char *argv[])
  1258. {
  1259. int ret;
  1260. char conffile[512];
  1261. ret = find_config(conffile);
  1262. if (ret) {
  1263. g_printerr("Could not find any config file\n");
  1264. return ret;
  1265. }
  1266. ret = find_processor(processing_script);
  1267. if (ret) {
  1268. g_printerr("Could not find any post-process script\n");
  1269. return ret;
  1270. }
  1271. TIFFSetTagExtender(register_custom_tiff_tags);
  1272. gtk_init(&argc, &argv);
  1273. g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", TRUE, NULL);
  1274. GtkBuilder *builder = gtk_builder_new_from_resource("/org/postmarketos/Megapixels/camera.glade");
  1275. GtkWidget *window = GTK_WIDGET(gtk_builder_get_object(builder, "window"));
  1276. GtkWidget *preview_box = GTK_WIDGET(gtk_builder_get_object(builder, "preview_box"));
  1277. GtkWidget *shutter = GTK_WIDGET(gtk_builder_get_object(builder, "shutter"));
  1278. GtkWidget *switch_btn = GTK_WIDGET(gtk_builder_get_object(builder, "switch_camera"));
  1279. GtkWidget *settings_btn = GTK_WIDGET(gtk_builder_get_object(builder, "settings"));
  1280. GtkWidget *settings_back = GTK_WIDGET(gtk_builder_get_object(builder, "settings_back"));
  1281. GtkWidget *error_close = GTK_WIDGET(gtk_builder_get_object(builder, "error_close"));
  1282. GtkWidget *open_last = GTK_WIDGET(gtk_builder_get_object(builder, "open_last"));
  1283. GtkWidget *open_directory = GTK_WIDGET(gtk_builder_get_object(builder, "open_directory"));
  1284. preview = GTK_WIDGET(gtk_builder_get_object(builder, "preview"));
  1285. error_box = GTK_WIDGET(gtk_builder_get_object(builder, "error_box"));
  1286. error_message = GTK_WIDGET(gtk_builder_get_object(builder, "error_message"));
  1287. main_stack = GTK_WIDGET(gtk_builder_get_object(builder, "main_stack"));
  1288. thumb_last = GTK_WIDGET(gtk_builder_get_object(builder, "thumb_last"));
  1289. control_box = GTK_WIDGET(gtk_builder_get_object(builder, "control_box"));
  1290. control_name = GTK_WIDGET(gtk_builder_get_object(builder, "control_name"));
  1291. control_slider = GTK_WIDGET(gtk_builder_get_object(builder, "control_adj"));
  1292. control_auto = GTK_WIDGET(gtk_builder_get_object(builder, "control_auto"));
  1293. g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  1294. g_signal_connect(shutter, "clicked", G_CALLBACK(on_shutter_clicked), NULL);
  1295. g_signal_connect(error_close, "clicked", G_CALLBACK(on_error_close_clicked), NULL);
  1296. g_signal_connect(switch_btn, "clicked", G_CALLBACK(on_camera_switch_clicked), NULL);
  1297. g_signal_connect(settings_btn, "clicked", G_CALLBACK(on_settings_btn_clicked), NULL);
  1298. g_signal_connect(settings_back, "clicked", G_CALLBACK(on_back_clicked), NULL);
  1299. g_signal_connect(open_last, "clicked", G_CALLBACK(on_open_last_clicked), NULL);
  1300. g_signal_connect(open_directory, "clicked", G_CALLBACK(on_open_directory_clicked), NULL);
  1301. g_signal_connect(preview, "draw", G_CALLBACK(preview_draw), NULL);
  1302. g_signal_connect(preview, "configure-event", G_CALLBACK(preview_configure), NULL);
  1303. gtk_widget_set_events(preview, gtk_widget_get_events(preview) |
  1304. GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK);
  1305. g_signal_connect(preview, "button-press-event", G_CALLBACK(on_preview_tap), NULL);
  1306. g_signal_connect(control_auto, "toggled", G_CALLBACK(on_control_auto_toggled), NULL);
  1307. g_signal_connect(control_slider, "value-changed", G_CALLBACK(on_control_slider_changed), NULL);
  1308. GtkCssProvider *provider = gtk_css_provider_new();
  1309. if (access("camera.css", F_OK) != -1) {
  1310. gtk_css_provider_load_from_path(provider, "camera.css", NULL);
  1311. } else {
  1312. gtk_css_provider_load_from_resource(provider, "/org/postmarketos/Megapixels/camera.css");
  1313. }
  1314. GtkStyleContext *context = gtk_widget_get_style_context(preview_box);
  1315. gtk_style_context_add_provider(context,
  1316. GTK_STYLE_PROVIDER(provider),
  1317. GTK_STYLE_PROVIDER_PRIORITY_USER);
  1318. context = gtk_widget_get_style_context(error_box);
  1319. gtk_style_context_add_provider(context,
  1320. GTK_STYLE_PROVIDER(provider),
  1321. GTK_STYLE_PROVIDER_PRIORITY_USER);
  1322. int result = ini_parse(conffile, config_ini_handler, NULL);
  1323. if (result == -1) {
  1324. g_printerr("Config file not found\n");
  1325. return 1;
  1326. } else if (result == -2) {
  1327. g_printerr("Could not allocate memory to parse config file\n");
  1328. return 1;
  1329. } else if (result != 0) {
  1330. g_printerr("Could not parse config file\n");
  1331. return 1;
  1332. }
  1333. if (find_media_fd() == -1) {
  1334. g_printerr("Could not find the media node\n");
  1335. show_error("Could not find the media node");
  1336. goto failed;
  1337. }
  1338. if (find_cameras() == -1) {
  1339. g_printerr("Could not find the cameras\n");
  1340. show_error("Could not find the cameras");
  1341. goto failed;
  1342. }
  1343. setup_rear();
  1344. int fd = open(dev_name, O_RDWR);
  1345. if (fd == -1) {
  1346. g_printerr("Error opening video device: %s\n", dev_name);
  1347. show_error("Error opening the video device");
  1348. goto failed;
  1349. }
  1350. video_fd = fd;
  1351. if(init_device(fd) < 0){
  1352. goto failed;
  1353. }
  1354. start_capturing(fd);
  1355. failed:
  1356. printf("window show\n");
  1357. gtk_widget_show(window);
  1358. g_idle_add((GSourceFunc)get_frame, NULL);
  1359. gtk_main();
  1360. return 0;
  1361. }