main.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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_bggr8((const uint8_t *)p, pixels, current.width, current.height, skip, current.blacklevel);
  518. if (current.rotate == 0) {
  519. pixbufrot = pixbuf;
  520. } else if (current.rotate == 90) {
  521. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE);
  522. } else if (current.rotate == 180) {
  523. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_UPSIDEDOWN);
  524. } else if (current.rotate == 270) {
  525. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_CLOCKWISE);
  526. }
  527. // Draw preview image
  528. scale = (double) preview_width / gdk_pixbuf_get_width(pixbufrot);
  529. cr = cairo_create(surface);
  530. cairo_set_source_rgb(cr, 0, 0, 0);
  531. cairo_paint(cr);
  532. cairo_scale(cr, scale, scale);
  533. gdk_cairo_set_source_pixbuf(cr, pixbufrot, 0, 0);
  534. cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_NONE);
  535. cairo_paint(cr);
  536. // Draw controls over preview
  537. cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
  538. cairo_set_source_surface(cr, status_surface, 0, 0);
  539. cairo_paint(cr);
  540. // Queue gtk3 repaint of the preview area
  541. gtk_widget_queue_draw_area(preview, 0, 0, preview_width, preview_height);
  542. cairo_destroy(cr);
  543. g_object_unref(pixbufrot);
  544. g_object_unref(pixbuf);
  545. } else {
  546. capture--;
  547. time(&rawtime);
  548. tim = *(localtime(&rawtime));
  549. strftime(timestamp, 30, "%Y%m%d%H%M%S", &tim);
  550. strftime(datetime, 20, "%Y:%m:%d %H:%M:%S", &tim);
  551. sprintf(fname_target, "%s/Pictures/IMG%s", getenv("HOME"), timestamp);
  552. sprintf(fname, "%s/%d.dng", burst_dir, burst_length - capture);
  553. // Get latest exposure and gain now the auto gain/exposure is disabled while capturing
  554. gain = v4l2_ctrl_get(current.fd, current.gain_ctrl);
  555. exposure = v4l2_ctrl_get(current.fd, V4L2_CID_EXPOSURE);
  556. if(!(tif = TIFFOpen(fname, "w"))) {
  557. printf("Could not open tiff\n");
  558. }
  559. // Define TIFF thumbnail
  560. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 1);
  561. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, current.width >> 4);
  562. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, current.height >> 4);
  563. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  564. TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  565. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
  566. TIFFSetField(tif, TIFFTAG_MAKE, exif_make);
  567. TIFFSetField(tif, TIFFTAG_MODEL, exif_model);
  568. TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
  569. TIFFSetField(tif, TIFFTAG_DATETIME, datetime);
  570. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
  571. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  572. TIFFSetField(tif, TIFFTAG_SOFTWARE, "Megapixels");
  573. TIFFSetField(tif, TIFFTAG_SUBIFD, 1, &sub_offset);
  574. TIFFSetField(tif, TIFFTAG_DNGVERSION, "\001\001\0\0");
  575. TIFFSetField(tif, TIFFTAG_DNGBACKWARDVERSION, "\001\0\0\0");
  576. sprintf(uniquecameramodel, "%s %s", exif_make, exif_model);
  577. TIFFSetField(tif, TIFFTAG_UNIQUECAMERAMODEL, uniquecameramodel);
  578. if(current.colormatrix[0]) {
  579. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, current.colormatrix);
  580. } else {
  581. TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, colormatrix_srgb);
  582. }
  583. if(current.forwardmatrix[0]) {
  584. TIFFSetField(tif, TIFFTAG_FORWARDMATRIX1, 9, current.forwardmatrix);
  585. }
  586. TIFFSetField(tif, TIFFTAG_ASSHOTNEUTRAL, 3, neutral);
  587. TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT1, 21);
  588. // Write black thumbnail, only windows uses this
  589. {
  590. unsigned char *buf = (unsigned char *)calloc(1, (int)current.width >> 4);
  591. for (int row = 0; row < current.height>>4; row++) {
  592. TIFFWriteScanline(tif, buf, row, 0);
  593. }
  594. free(buf);
  595. }
  596. TIFFWriteDirectory(tif);
  597. // Define main photo
  598. TIFFSetField(tif, TIFFTAG_SUBFILETYPE, 0);
  599. TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, current.width);
  600. TIFFSetField(tif, TIFFTAG_IMAGELENGTH, current.height);
  601. TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
  602. TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CFA);
  603. TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
  604. TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  605. TIFFSetField(tif, TIFFTAG_CFAREPEATPATTERNDIM, cfapatterndim);
  606. TIFFSetField(tif, TIFFTAG_CFAPATTERN, "\002\001\001\000"); // BGGR
  607. if(current.whitelevel) {
  608. TIFFSetField(tif, TIFFTAG_WHITELEVEL, 1, &current.whitelevel);
  609. }
  610. if(current.blacklevel) {
  611. TIFFSetField(tif, TIFFTAG_BLACKLEVEL, 1, &current.blacklevel);
  612. }
  613. TIFFCheckpointDirectory(tif);
  614. printf("Writing frame to %s\n", fname);
  615. unsigned char *pLine = (unsigned char*)malloc(current.width);
  616. for(int row = 0; row < current.height; row++){
  617. TIFFWriteScanline(tif, ((uint8_t *)p)+(row*current.width), row, 0);
  618. }
  619. free(pLine);
  620. TIFFWriteDirectory(tif);
  621. // Add an EXIF block to the tiff
  622. TIFFCreateEXIFDirectory(tif);
  623. // 1 = manual, 2 = full auto, 3 = aperture priority, 4 = shutter priority
  624. if (auto_exposure) {
  625. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 2);
  626. } else {
  627. TIFFSetField(tif, EXIFTAG_EXPOSUREPROGRAM, 1);
  628. }
  629. TIFFSetField(tif, EXIFTAG_EXPOSURETIME, (1.0/current.rate) / ((float)current.height / (float)exposure));
  630. isospeed[0] = (uint16_t)remap(gain - 1, 0, current.gain_max, current.iso_min, current.iso_max);
  631. TIFFSetField(tif, EXIFTAG_ISOSPEEDRATINGS, 1, isospeed);
  632. TIFFSetField(tif, EXIFTAG_FLASH, 0);
  633. TIFFSetField(tif, EXIFTAG_DATETIMEORIGINAL, datetime);
  634. TIFFSetField(tif, EXIFTAG_DATETIMEDIGITIZED, datetime);
  635. if(current.fnumber) {
  636. TIFFSetField(tif, EXIFTAG_FNUMBER, current.fnumber);
  637. }
  638. if(current.focallength) {
  639. TIFFSetField(tif, EXIFTAG_FOCALLENGTH, current.focallength);
  640. }
  641. if(current.focallength && current.cropfactor) {
  642. TIFFSetField(tif, EXIFTAG_FOCALLENGTHIN35MMFILM, (short)(current.focallength * current.cropfactor));
  643. }
  644. TIFFWriteCustomDirectory(tif, &exif_offset);
  645. TIFFFreeDirectory(tif);
  646. // Update exif pointer
  647. TIFFSetDirectory(tif, 0);
  648. TIFFSetField(tif, TIFFTAG_EXIFIFD, exif_offset);
  649. TIFFRewriteDirectory(tif);
  650. TIFFClose(tif);
  651. if (capture == 0) {
  652. // Update the thumbnail if this is the last frame
  653. pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, current.width / (skip*2), current.height / (skip*2));
  654. pixels = gdk_pixbuf_get_pixels(pixbuf);
  655. quick_debayer_bggr8((const uint8_t *)p, pixels, current.width, current.height, skip, current.blacklevel);
  656. if (current.rotate == 0) {
  657. pixbufrot = pixbuf;
  658. } else if (current.rotate == 90) {
  659. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE);
  660. } else if (current.rotate == 180) {
  661. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_UPSIDEDOWN);
  662. } else if (current.rotate == 270) {
  663. pixbufrot = gdk_pixbuf_rotate_simple(pixbuf, GDK_PIXBUF_ROTATE_CLOCKWISE);
  664. }
  665. thumb = gdk_pixbuf_scale_simple(pixbufrot, 24, 24, GDK_INTERP_BILINEAR);
  666. gtk_image_set_from_pixbuf(GTK_IMAGE(thumb_last), thumb);
  667. sprintf(last_path, "%s.jpg", fname_target);
  668. if (error != NULL) {
  669. g_printerr("%s\n", error->message);
  670. g_clear_error(&error);
  671. }
  672. g_object_unref(pixbufrot);
  673. g_object_unref(pixbuf);
  674. // Start post-processing the captured burst
  675. g_print("Post process %s to %s.ext\n", burst_dir, fname_target);
  676. sprintf(command, "%s %s %s &", processing_script, burst_dir, fname_target);
  677. system(command);
  678. // Restore the auto exposure and gain if needed
  679. if (auto_exposure) {
  680. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_AUTO);
  681. }
  682. if (auto_gain) {
  683. v4l2_ctrl_set(current.fd, V4L2_CID_AUTOGAIN, 1);
  684. }
  685. }
  686. }
  687. }
  688. static gboolean
  689. preview_draw(GtkWidget *widget, cairo_t *cr, gpointer data)
  690. {
  691. cairo_set_source_surface(cr, surface, 0, 0);
  692. cairo_paint(cr);
  693. return FALSE;
  694. }
  695. static gboolean
  696. preview_configure(GtkWidget *widget, GdkEventConfigure *event)
  697. {
  698. cairo_t *cr;
  699. if (surface)
  700. cairo_surface_destroy(surface);
  701. surface = gdk_window_create_similar_surface(gtk_widget_get_window(widget),
  702. CAIRO_CONTENT_COLOR,
  703. gtk_widget_get_allocated_width(widget),
  704. gtk_widget_get_allocated_height(widget));
  705. preview_width = gtk_widget_get_allocated_width(widget);
  706. preview_height = gtk_widget_get_allocated_height(widget);
  707. cr = cairo_create(surface);
  708. cairo_set_source_rgb(cr, 0, 0, 0);
  709. cairo_paint(cr);
  710. cairo_destroy(cr);
  711. draw_controls();
  712. return TRUE;
  713. }
  714. static int
  715. read_frame(int fd)
  716. {
  717. struct v4l2_buffer buf = {0};
  718. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  719. buf.memory = V4L2_MEMORY_MMAP;
  720. if (xioctl(fd, VIDIOC_DQBUF, &buf) == -1) {
  721. switch (errno) {
  722. case EAGAIN:
  723. return 0;
  724. case EIO:
  725. /* Could ignore EIO, see spec. */
  726. /* fallthrough */
  727. default:
  728. errno_exit("VIDIOC_DQBUF");
  729. break;
  730. }
  731. }
  732. //assert(buf.index < n_buffers);
  733. process_image(buffers[buf.index].start, buf.bytesused);
  734. if (xioctl(fd, VIDIOC_QBUF, &buf) == -1) {
  735. errno_exit("VIDIOC_QBUF");
  736. }
  737. return 1;
  738. }
  739. gboolean
  740. get_frame()
  741. {
  742. if (ready == 0)
  743. return TRUE;
  744. while (1) {
  745. fd_set fds;
  746. struct timeval tv;
  747. int r;
  748. FD_ZERO(&fds);
  749. FD_SET(video_fd, &fds);
  750. /* Timeout. */
  751. tv.tv_sec = 2;
  752. tv.tv_usec = 0;
  753. r = select(video_fd + 1, &fds, NULL, NULL, &tv);
  754. if (r == -1) {
  755. if (EINTR == errno) {
  756. continue;
  757. }
  758. errno_exit("select");
  759. } else if (r == 0) {
  760. fprintf(stderr, "select timeout\\n");
  761. exit(EXIT_FAILURE);
  762. }
  763. if (read_frame(video_fd)) {
  764. break;
  765. }
  766. /* EAGAIN - continue select loop. */
  767. }
  768. return TRUE;
  769. }
  770. int
  771. strtoint(const char *nptr, char **endptr, int base)
  772. {
  773. long x = strtol(nptr, endptr, base);
  774. assert(x <= INT_MAX);
  775. return (int) x;
  776. }
  777. static int
  778. config_ini_handler(void *user, const char *section, const char *name,
  779. const char *value)
  780. {
  781. struct camerainfo *cc;
  782. if (strcmp(section, "rear") == 0 || strcmp(section, "front") == 0) {
  783. if (strcmp(section, "rear") == 0) {
  784. cc = &rear_cam;
  785. } else {
  786. cc = &front_cam;
  787. }
  788. if (strcmp(name, "width") == 0) {
  789. cc->width = strtoint(value, NULL, 10);
  790. } else if (strcmp(name, "height") == 0) {
  791. cc->height = strtoint(value, NULL, 10);
  792. } else if (strcmp(name, "rate") == 0) {
  793. cc->rate = strtoint(value, NULL, 10);
  794. } else if (strcmp(name, "rotate") == 0) {
  795. cc->rotate = strtoint(value, NULL, 10);
  796. } else if (strcmp(name, "fmt") == 0) {
  797. if (strcmp(value, "RGGB8") == 0) {
  798. cc->fmt = V4L2_PIX_FMT_SRGGB8;
  799. cc->mbus = MEDIA_BUS_FMT_SRGGB8_1X8;
  800. } else if (strcmp(value, "BGGR8") == 0) {
  801. cc->fmt = V4L2_PIX_FMT_SBGGR8;
  802. cc->mbus = MEDIA_BUS_FMT_SBGGR8_1X8;
  803. } else if (strcmp(value, "GRBG8") == 0) {
  804. cc->fmt = V4L2_PIX_FMT_SGRBG8;
  805. cc->mbus = MEDIA_BUS_FMT_SGRBG8_1X8;
  806. } else if (strcmp(value, "GBRG8") == 0) {
  807. cc->fmt = V4L2_PIX_FMT_SGBRG8;
  808. cc->mbus = MEDIA_BUS_FMT_SGBRG8_1X8;
  809. } else {
  810. g_printerr("Unsupported pixelformat %s\n", value);
  811. exit(1);
  812. }
  813. } else if (strcmp(name, "driver") == 0) {
  814. strcpy(cc->dev_name, value);
  815. } else if (strcmp(name, "colormatrix") == 0) {
  816. sscanf(value, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
  817. cc->colormatrix+0,
  818. cc->colormatrix+1,
  819. cc->colormatrix+2,
  820. cc->colormatrix+3,
  821. cc->colormatrix+4,
  822. cc->colormatrix+5,
  823. cc->colormatrix+6,
  824. cc->colormatrix+7,
  825. cc->colormatrix+8
  826. );
  827. } else if (strcmp(name, "forwardmatrix") == 0) {
  828. sscanf(value, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
  829. cc->forwardmatrix+0,
  830. cc->forwardmatrix+1,
  831. cc->forwardmatrix+2,
  832. cc->forwardmatrix+3,
  833. cc->forwardmatrix+4,
  834. cc->forwardmatrix+5,
  835. cc->forwardmatrix+6,
  836. cc->forwardmatrix+7,
  837. cc->forwardmatrix+8
  838. );
  839. } else if (strcmp(name, "whitelevel") == 0) {
  840. cc->whitelevel = strtoint(value, NULL, 10);
  841. } else if (strcmp(name, "blacklevel") == 0) {
  842. cc->blacklevel = strtoint(value, NULL, 10);
  843. } else if (strcmp(name, "focallength") == 0) {
  844. cc->focallength = strtof(value, NULL);
  845. } else if (strcmp(name, "cropfactor") == 0) {
  846. cc->cropfactor = strtof(value, NULL);
  847. } else if (strcmp(name, "fnumber") == 0) {
  848. cc->fnumber = strtod(value, NULL);
  849. } else if (strcmp(name, "iso-min") == 0) {
  850. cc->iso_min = strtod(value, NULL);
  851. } else if (strcmp(name, "iso-max") == 0) {
  852. cc->iso_max = strtod(value, NULL);
  853. } else {
  854. g_printerr("Unknown key '%s' in [%s]\n", name, section);
  855. exit(1);
  856. }
  857. } else if (strcmp(section, "device") == 0) {
  858. if (strcmp(name, "csi") == 0) {
  859. media_drv_name = strdup(value);
  860. } else if (strcmp(name, "make") == 0) {
  861. exif_make = strdup(value);
  862. } else if (strcmp(name, "model") == 0) {
  863. exif_model = strdup(value);
  864. } else {
  865. g_printerr("Unknown key '%s' in [device]\n", name);
  866. exit(1);
  867. }
  868. } else {
  869. g_printerr("Unknown section '%s' in config file\n", section);
  870. exit(1);
  871. }
  872. return 1;
  873. }
  874. int
  875. find_dev_node(int maj, int min, char *fnbuf)
  876. {
  877. DIR *d;
  878. struct dirent *dir;
  879. struct stat info;
  880. d = opendir("/dev");
  881. while ((dir = readdir(d)) != NULL) {
  882. sprintf(fnbuf, "/dev/%s", dir->d_name);
  883. stat(fnbuf, &info);
  884. if (!S_ISCHR(info.st_mode)) {
  885. continue;
  886. }
  887. if (major(info.st_rdev) == maj && minor(info.st_rdev) == min) {
  888. return 0;
  889. }
  890. }
  891. return -1;
  892. }
  893. int
  894. setup_rear()
  895. {
  896. struct media_link_desc link = {0};
  897. // Disable the interface<->front link
  898. link.flags = 0;
  899. link.source.entity = front_cam.entity_id;
  900. link.source.index = 0;
  901. link.sink.entity = interface_entity_id;
  902. link.sink.index = 0;
  903. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  904. g_printerr("Could not disable front camera link\n");
  905. return -1;
  906. }
  907. // Enable the interface<->rear link
  908. link.flags = MEDIA_LNK_FL_ENABLED;
  909. link.source.entity = rear_cam.entity_id;
  910. link.source.index = 0;
  911. link.sink.entity = interface_entity_id;
  912. link.sink.index = 0;
  913. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  914. g_printerr("Could not enable rear camera link\n");
  915. return -1;
  916. }
  917. current = rear_cam;
  918. // Find camera node
  919. init_sensor(current.dev, current.width, current.height, current.mbus, current.rate);
  920. return 0;
  921. }
  922. int
  923. setup_front()
  924. {
  925. struct media_link_desc link = {0};
  926. // Disable the interface<->rear link
  927. link.flags = 0;
  928. link.source.entity = rear_cam.entity_id;
  929. link.source.index = 0;
  930. link.sink.entity = interface_entity_id;
  931. link.sink.index = 0;
  932. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  933. g_printerr("Could not disable rear camera link\n");
  934. return -1;
  935. }
  936. // Enable the interface<->rear link
  937. link.flags = MEDIA_LNK_FL_ENABLED;
  938. link.source.entity = front_cam.entity_id;
  939. link.source.index = 0;
  940. link.sink.entity = interface_entity_id;
  941. link.sink.index = 0;
  942. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  943. g_printerr("Could not enable front camera link\n");
  944. return -1;
  945. }
  946. current = front_cam;
  947. // Find camera node
  948. init_sensor(current.dev, current.width, current.height, current.mbus, current.rate);
  949. return 0;
  950. }
  951. int
  952. find_cameras()
  953. {
  954. struct media_entity_desc entity = {0};
  955. int ret;
  956. int found = 0;
  957. while (1) {
  958. entity.id = entity.id | MEDIA_ENT_ID_FLAG_NEXT;
  959. ret = xioctl(media_fd, MEDIA_IOC_ENUM_ENTITIES, &entity);
  960. if (ret < 0) {
  961. break;
  962. }
  963. if (strncmp(entity.name, front_cam.dev_name, strlen(front_cam.dev_name)) == 0) {
  964. front_cam.entity_id = entity.id;
  965. find_dev_node(entity.dev.major, entity.dev.minor, front_cam.dev);
  966. printf("Found front cam, is %s at %s\n", entity.name, front_cam.dev);
  967. found++;
  968. }
  969. if (strncmp(entity.name, rear_cam.dev_name, strlen(rear_cam.dev_name)) == 0) {
  970. rear_cam.entity_id = entity.id;
  971. find_dev_node(entity.dev.major, entity.dev.minor, rear_cam.dev);
  972. printf("Found rear cam, is %s at %s\n", entity.name, rear_cam.dev);
  973. found++;
  974. }
  975. if (entity.type == MEDIA_ENT_F_IO_V4L) {
  976. interface_entity_id = entity.id;
  977. find_dev_node(entity.dev.major, entity.dev.minor, dev_name);
  978. printf("Found v4l2 interface node at %s\n", dev_name);
  979. }
  980. }
  981. if (found < 2) {
  982. return -1;
  983. }
  984. return 0;
  985. }
  986. int
  987. find_media_fd()
  988. {
  989. DIR *d;
  990. struct dirent *dir;
  991. int fd;
  992. char fnbuf[261];
  993. struct media_device_info mdi = {0};
  994. d = opendir("/dev");
  995. while ((dir = readdir(d)) != NULL) {
  996. if (strncmp(dir->d_name, "media", 5) == 0) {
  997. sprintf(fnbuf, "/dev/%s", dir->d_name);
  998. fd = open(fnbuf, O_RDWR);
  999. xioctl(fd, MEDIA_IOC_DEVICE_INFO, &mdi);
  1000. if (strcmp(mdi.driver, media_drv_name) == 0) {
  1001. printf("Found media device: %s (%s)\n", fnbuf, mdi.driver);
  1002. media_fd = fd;
  1003. return 0;
  1004. }
  1005. close(fd);
  1006. }
  1007. }
  1008. g_printerr("Could not find /dev/media* node matching '%s'\n", media_drv_name);
  1009. return 1;
  1010. }
  1011. void
  1012. on_open_last_clicked(GtkWidget *widget, gpointer user_data)
  1013. {
  1014. char uri[270];
  1015. GError *error = NULL;
  1016. if(strlen(last_path) == 0) {
  1017. return;
  1018. }
  1019. sprintf(uri, "file://%s", last_path);
  1020. if(!g_app_info_launch_default_for_uri(uri, NULL, &error)){
  1021. g_printerr("Could not launch image viewer: %s\n", error->message);
  1022. }
  1023. }
  1024. void
  1025. on_open_directory_clicked(GtkWidget *widget, gpointer user_data)
  1026. {
  1027. char uri[270];
  1028. GError *error = NULL;
  1029. sprintf(uri, "file://%s/Pictures", getenv("HOME"));
  1030. if(!g_app_info_launch_default_for_uri(uri, NULL, &error)){
  1031. g_printerr("Could not launch image viewer: %s\n", error->message);
  1032. }
  1033. }
  1034. void
  1035. on_shutter_clicked(GtkWidget *widget, gpointer user_data)
  1036. {
  1037. char template[] = "/tmp/megapixels.XXXXXX";
  1038. char *tempdir;
  1039. tempdir = mkdtemp(template);
  1040. if (tempdir == NULL) {
  1041. g_printerr("Could not make capture directory %s\n", template);
  1042. exit (EXIT_FAILURE);
  1043. }
  1044. strcpy(burst_dir, tempdir);
  1045. // Disable the autogain/exposure while taking the burst
  1046. v4l2_ctrl_set(current.fd, V4L2_CID_AUTOGAIN, 0);
  1047. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
  1048. capture = burst_length;
  1049. }
  1050. void
  1051. on_preview_tap(GtkWidget *widget, GdkEventButton *event, gpointer user_data)
  1052. {
  1053. if (event->type != GDK_BUTTON_PRESS)
  1054. return;
  1055. // Handle taps on the controls
  1056. if (event->y < 32) {
  1057. if (gtk_widget_is_visible(control_box)) {
  1058. gtk_widget_hide(control_box);
  1059. return;
  1060. } else {
  1061. gtk_widget_show(control_box);
  1062. }
  1063. if (event->x < 60 ) {
  1064. // ISO
  1065. current_control = USER_CONTROL_ISO;
  1066. gtk_label_set_text(GTK_LABEL(control_name), "ISO");
  1067. gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(control_auto), auto_gain);
  1068. gtk_adjustment_set_lower(control_slider, 0.0);
  1069. gtk_adjustment_set_upper(control_slider, (float)current.gain_max);
  1070. gtk_adjustment_set_value(control_slider, (double)gain);
  1071. } else if (event->x > 60 && event->x < 120) {
  1072. // Shutter angle
  1073. current_control = USER_CONTROL_SHUTTER;
  1074. gtk_label_set_text(GTK_LABEL(control_name), "Shutter");
  1075. gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(control_auto), auto_exposure);
  1076. gtk_adjustment_set_lower(control_slider, 1.0);
  1077. gtk_adjustment_set_upper(control_slider, 360.0);
  1078. gtk_adjustment_set_value(control_slider, (double)exposure);
  1079. }
  1080. return;
  1081. }
  1082. // Tapped preview image itself, try focussing
  1083. if (current.has_af_s) {
  1084. v4l2_ctrl_set(current.fd, V4L2_CID_AUTO_FOCUS_STOP, 1);
  1085. v4l2_ctrl_set(current.fd, V4L2_CID_AUTO_FOCUS_START, 1);
  1086. }
  1087. }
  1088. void
  1089. on_error_close_clicked(GtkWidget *widget, gpointer user_data)
  1090. {
  1091. gtk_widget_hide(error_box);
  1092. }
  1093. void
  1094. on_camera_switch_clicked(GtkWidget *widget, gpointer user_data)
  1095. {
  1096. stop_capturing(video_fd);
  1097. close(current.fd);
  1098. if (current_is_rear == 1) {
  1099. setup_front();
  1100. current_is_rear = 0;
  1101. } else {
  1102. setup_rear();
  1103. current_is_rear = 1;
  1104. }
  1105. close(video_fd);
  1106. video_fd = open(dev_name, O_RDWR);
  1107. if (video_fd == -1) {
  1108. g_printerr("Error opening video device: %s\n", dev_name);
  1109. return;
  1110. }
  1111. init_device(video_fd);
  1112. start_capturing(video_fd);
  1113. }
  1114. void
  1115. on_settings_btn_clicked(GtkWidget *widget, gpointer user_data)
  1116. {
  1117. gtk_stack_set_visible_child_name(GTK_STACK(main_stack), "settings");
  1118. }
  1119. void
  1120. on_back_clicked(GtkWidget *widget, gpointer user_data)
  1121. {
  1122. gtk_stack_set_visible_child_name(GTK_STACK(main_stack), "main");
  1123. }
  1124. void
  1125. on_control_auto_toggled(GtkToggleButton *widget, gpointer user_data)
  1126. {
  1127. int fd = current.fd;
  1128. switch (current_control) {
  1129. case USER_CONTROL_ISO:
  1130. auto_gain = gtk_toggle_button_get_active(widget);
  1131. if (auto_gain) {
  1132. v4l2_ctrl_set(fd, V4L2_CID_AUTOGAIN, 1);
  1133. } else {
  1134. v4l2_ctrl_set(fd, V4L2_CID_AUTOGAIN, 0);
  1135. gain = v4l2_ctrl_get(fd, V4L2_CID_GAIN);
  1136. gtk_adjustment_set_value(control_slider, (double)gain);
  1137. }
  1138. break;
  1139. case USER_CONTROL_SHUTTER:
  1140. auto_exposure = gtk_toggle_button_get_active(widget);
  1141. if (auto_exposure) {
  1142. v4l2_ctrl_set(fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_AUTO);
  1143. } else {
  1144. v4l2_ctrl_set(fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
  1145. exposure = v4l2_ctrl_get(fd, V4L2_CID_EXPOSURE);
  1146. gtk_adjustment_set_value(control_slider, (double)exposure);
  1147. }
  1148. break;
  1149. }
  1150. draw_controls();
  1151. }
  1152. void
  1153. on_control_slider_changed(GtkAdjustment *widget, gpointer user_data)
  1154. {
  1155. double value = gtk_adjustment_get_value(widget);
  1156. switch (current_control) {
  1157. case USER_CONTROL_ISO:
  1158. gain = (int)value;
  1159. v4l2_ctrl_set(current.fd, current.gain_ctrl, gain);
  1160. break;
  1161. case USER_CONTROL_SHUTTER:
  1162. // So far all sensors use exposure time in number of sensor rows
  1163. exposure = (int)(value / 360.0 * current.height);
  1164. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE, exposure);
  1165. break;
  1166. }
  1167. draw_controls();
  1168. }
  1169. int
  1170. find_config(char *conffile)
  1171. {
  1172. char buf[512];
  1173. char *xdg_config_home;
  1174. wordexp_t exp_result;
  1175. FILE *fp;
  1176. // Resolve XDG stuff
  1177. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  1178. xdg_config_home = "~/.config";
  1179. }
  1180. wordexp(xdg_config_home, &exp_result, 0);
  1181. xdg_config_home = strdup(exp_result.we_wordv[0]);
  1182. wordfree(&exp_result);
  1183. if(access("/proc/device-tree/compatible", F_OK) != -1) {
  1184. // Reads to compatible string of the current device tree, looks like:
  1185. // pine64,pinephone-1.2\0allwinner,sun50i-a64\0
  1186. fp = fopen("/proc/device-tree/compatible", "r");
  1187. fgets(buf, 512, fp);
  1188. fclose(fp);
  1189. // Check config/%dt.ini in the current working directory
  1190. sprintf(conffile, "config/%s.ini", buf);
  1191. if(access(conffile, F_OK) != -1) {
  1192. printf("Found config file at %s\n", conffile);
  1193. return 0;
  1194. }
  1195. // Check for a config file in XDG_CONFIG_HOME
  1196. sprintf(conffile, "%s/megapixels/config/%s.ini", xdg_config_home, buf);
  1197. if(access(conffile, F_OK) != -1) {
  1198. printf("Found config file at %s\n", conffile);
  1199. return 0;
  1200. }
  1201. // Check user overridden /etc/megapixels/config/$dt.ini
  1202. sprintf(conffile, "%s/megapixels/config/%s.ini", SYSCONFDIR, buf);
  1203. if(access(conffile, F_OK) != -1) {
  1204. printf("Found config file at %s\n", conffile);
  1205. return 0;
  1206. }
  1207. // Check packaged /usr/share/megapixels/config/$dt.ini
  1208. sprintf(conffile, "%s/megapixels/config/%s.ini", DATADIR, buf);
  1209. if(access(conffile, F_OK) != -1) {
  1210. printf("Found config file at %s\n", conffile);
  1211. return 0;
  1212. }
  1213. printf("%s not found\n", conffile);
  1214. } else {
  1215. printf("Could not read device name from device tree\n");
  1216. }
  1217. // If all else fails, fall back to /etc/megapixels.ini
  1218. sprintf(conffile, "/etc/megapixels.ini");
  1219. if(access(conffile, F_OK) != -1) {
  1220. printf("Found config file at %s\n", conffile);
  1221. return 0;
  1222. }
  1223. return -1;
  1224. }
  1225. int
  1226. find_processor(char *script)
  1227. {
  1228. char *xdg_config_home;
  1229. char filename[] = "postprocess.sh";
  1230. wordexp_t exp_result;
  1231. // Resolve XDG stuff
  1232. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  1233. xdg_config_home = "~/.config";
  1234. }
  1235. wordexp(xdg_config_home, &exp_result, 0);
  1236. xdg_config_home = strdup(exp_result.we_wordv[0]);
  1237. wordfree(&exp_result);
  1238. // Check postprocess.h in the current working directory
  1239. sprintf(script, "%s", filename);
  1240. if(access(script, F_OK) != -1) {
  1241. sprintf(script, "./%s", filename);
  1242. printf("Found postprocessor script at %s\n", script);
  1243. return 0;
  1244. }
  1245. // Check for a script in XDG_CONFIG_HOME
  1246. sprintf(script, "%s/megapixels/%s", xdg_config_home, filename);
  1247. if(access(script, F_OK) != -1) {
  1248. printf("Found postprocessor script at %s\n", script);
  1249. return 0;
  1250. }
  1251. // Check user overridden /etc/megapixels/postprocessor.sh
  1252. sprintf(script, "%s/megapixels/%s", SYSCONFDIR, filename);
  1253. if(access(script, F_OK) != -1) {
  1254. printf("Found postprocessor script at %s\n", script);
  1255. return 0;
  1256. }
  1257. // Check packaged /usr/share/megapixels/postprocessor.sh
  1258. sprintf(script, "%s/megapixels/%s", DATADIR, filename);
  1259. if(access(script, F_OK) != -1) {
  1260. printf("Found postprocessor script at %s\n", script);
  1261. return 0;
  1262. }
  1263. return -1;
  1264. }
  1265. int
  1266. main(int argc, char *argv[])
  1267. {
  1268. int ret;
  1269. char conffile[512];
  1270. ret = find_config(conffile);
  1271. if (ret) {
  1272. g_printerr("Could not find any config file\n");
  1273. return ret;
  1274. }
  1275. ret = find_processor(processing_script);
  1276. if (ret) {
  1277. g_printerr("Could not find any post-process script\n");
  1278. return ret;
  1279. }
  1280. setenv("LC_NUMERIC", "C", 1);
  1281. TIFFSetTagExtender(register_custom_tiff_tags);
  1282. gtk_init(&argc, &argv);
  1283. g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", TRUE, NULL);
  1284. GtkBuilder *builder = gtk_builder_new_from_resource("/org/postmarketos/Megapixels/camera.glade");
  1285. GtkWidget *window = GTK_WIDGET(gtk_builder_get_object(builder, "window"));
  1286. GtkWidget *shutter = GTK_WIDGET(gtk_builder_get_object(builder, "shutter"));
  1287. GtkWidget *switch_btn = GTK_WIDGET(gtk_builder_get_object(builder, "switch_camera"));
  1288. GtkWidget *settings_btn = GTK_WIDGET(gtk_builder_get_object(builder, "settings"));
  1289. GtkWidget *settings_back = GTK_WIDGET(gtk_builder_get_object(builder, "settings_back"));
  1290. GtkWidget *error_close = GTK_WIDGET(gtk_builder_get_object(builder, "error_close"));
  1291. GtkWidget *open_last = GTK_WIDGET(gtk_builder_get_object(builder, "open_last"));
  1292. GtkWidget *open_directory = GTK_WIDGET(gtk_builder_get_object(builder, "open_directory"));
  1293. preview = GTK_WIDGET(gtk_builder_get_object(builder, "preview"));
  1294. error_box = GTK_WIDGET(gtk_builder_get_object(builder, "error_box"));
  1295. error_message = GTK_WIDGET(gtk_builder_get_object(builder, "error_message"));
  1296. main_stack = GTK_WIDGET(gtk_builder_get_object(builder, "main_stack"));
  1297. thumb_last = GTK_WIDGET(gtk_builder_get_object(builder, "thumb_last"));
  1298. control_box = GTK_WIDGET(gtk_builder_get_object(builder, "control_box"));
  1299. control_name = GTK_WIDGET(gtk_builder_get_object(builder, "control_name"));
  1300. control_slider = GTK_ADJUSTMENT(gtk_builder_get_object(builder, "control_adj"));
  1301. control_auto = GTK_WIDGET(gtk_builder_get_object(builder, "control_auto"));
  1302. g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  1303. g_signal_connect(shutter, "clicked", G_CALLBACK(on_shutter_clicked), NULL);
  1304. g_signal_connect(error_close, "clicked", G_CALLBACK(on_error_close_clicked), NULL);
  1305. g_signal_connect(switch_btn, "clicked", G_CALLBACK(on_camera_switch_clicked), NULL);
  1306. g_signal_connect(settings_btn, "clicked", G_CALLBACK(on_settings_btn_clicked), NULL);
  1307. g_signal_connect(settings_back, "clicked", G_CALLBACK(on_back_clicked), NULL);
  1308. g_signal_connect(open_last, "clicked", G_CALLBACK(on_open_last_clicked), NULL);
  1309. g_signal_connect(open_directory, "clicked", G_CALLBACK(on_open_directory_clicked), NULL);
  1310. g_signal_connect(preview, "draw", G_CALLBACK(preview_draw), NULL);
  1311. g_signal_connect(preview, "configure-event", G_CALLBACK(preview_configure), NULL);
  1312. gtk_widget_set_events(preview, gtk_widget_get_events(preview) |
  1313. GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK);
  1314. g_signal_connect(preview, "button-press-event", G_CALLBACK(on_preview_tap), NULL);
  1315. g_signal_connect(control_auto, "toggled", G_CALLBACK(on_control_auto_toggled), NULL);
  1316. g_signal_connect(control_slider, "value-changed", G_CALLBACK(on_control_slider_changed), NULL);
  1317. GtkCssProvider *provider = gtk_css_provider_new();
  1318. if (access("camera.css", F_OK) != -1) {
  1319. gtk_css_provider_load_from_path(provider, "camera.css", NULL);
  1320. } else {
  1321. gtk_css_provider_load_from_resource(provider, "/org/postmarketos/Megapixels/camera.css");
  1322. }
  1323. GtkStyleContext *context = gtk_widget_get_style_context(error_box);
  1324. gtk_style_context_add_provider(context,
  1325. GTK_STYLE_PROVIDER(provider),
  1326. GTK_STYLE_PROVIDER_PRIORITY_USER);
  1327. context = gtk_widget_get_style_context(control_box);
  1328. gtk_style_context_add_provider(context,
  1329. GTK_STYLE_PROVIDER(provider),
  1330. GTK_STYLE_PROVIDER_PRIORITY_USER);
  1331. int result = ini_parse(conffile, config_ini_handler, NULL);
  1332. if (result == -1) {
  1333. g_printerr("Config file not found\n");
  1334. return 1;
  1335. } else if (result == -2) {
  1336. g_printerr("Could not allocate memory to parse config file\n");
  1337. return 1;
  1338. } else if (result != 0) {
  1339. g_printerr("Could not parse config file\n");
  1340. return 1;
  1341. }
  1342. if (find_media_fd() == -1) {
  1343. g_printerr("Could not find the media node\n");
  1344. show_error("Could not find the media node");
  1345. goto failed;
  1346. }
  1347. if (find_cameras() == -1) {
  1348. g_printerr("Could not find the cameras\n");
  1349. show_error("Could not find the cameras");
  1350. goto failed;
  1351. }
  1352. setup_rear();
  1353. int fd = open(dev_name, O_RDWR);
  1354. if (fd == -1) {
  1355. g_printerr("Error opening video device: %s\n", dev_name);
  1356. show_error("Error opening the video device");
  1357. goto failed;
  1358. }
  1359. video_fd = fd;
  1360. if(init_device(fd) < 0){
  1361. goto failed;
  1362. }
  1363. start_capturing(fd);
  1364. failed:
  1365. printf("window show\n");
  1366. gtk_widget_show(window);
  1367. g_idle_add((GSourceFunc)get_frame, NULL);
  1368. gtk_main();
  1369. return 0;
  1370. }