main.c 30 KB

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