main.c 42 KB

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