main.c 38 KB

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