main.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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. } else if (strcmp(value, "BGGR8") == 0) {
  800. cc->fmt = V4L2_PIX_FMT_SBGGR8;
  801. cc->mbus = MEDIA_BUS_FMT_SBGGR8_1X8;
  802. } else if (strcmp(value, "GRBG8") == 0) {
  803. cc->fmt = V4L2_PIX_FMT_SGRBG8;
  804. } else if (strcmp(value, "GBRG8") == 0) {
  805. cc->fmt = V4L2_PIX_FMT_SGBRG8;
  806. } else {
  807. g_printerr("Unsupported pixelformat %s\n", value);
  808. exit(1);
  809. }
  810. } else if (strcmp(name, "driver") == 0) {
  811. strcpy(cc->dev_name, value);
  812. } else if (strcmp(name, "colormatrix") == 0) {
  813. sscanf(value, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
  814. cc->colormatrix+0,
  815. cc->colormatrix+1,
  816. cc->colormatrix+2,
  817. cc->colormatrix+3,
  818. cc->colormatrix+4,
  819. cc->colormatrix+5,
  820. cc->colormatrix+6,
  821. cc->colormatrix+7,
  822. cc->colormatrix+8
  823. );
  824. } else if (strcmp(name, "forwardmatrix") == 0) {
  825. sscanf(value, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
  826. cc->forwardmatrix+0,
  827. cc->forwardmatrix+1,
  828. cc->forwardmatrix+2,
  829. cc->forwardmatrix+3,
  830. cc->forwardmatrix+4,
  831. cc->forwardmatrix+5,
  832. cc->forwardmatrix+6,
  833. cc->forwardmatrix+7,
  834. cc->forwardmatrix+8
  835. );
  836. } else if (strcmp(name, "whitelevel") == 0) {
  837. cc->whitelevel = strtoint(value, NULL, 10);
  838. } else if (strcmp(name, "blacklevel") == 0) {
  839. cc->blacklevel = strtoint(value, NULL, 10);
  840. } else if (strcmp(name, "focallength") == 0) {
  841. cc->focallength = strtof(value, NULL);
  842. } else if (strcmp(name, "cropfactor") == 0) {
  843. cc->cropfactor = strtof(value, NULL);
  844. } else if (strcmp(name, "fnumber") == 0) {
  845. cc->fnumber = strtod(value, NULL);
  846. } else if (strcmp(name, "iso-min") == 0) {
  847. cc->iso_min = strtod(value, NULL);
  848. } else if (strcmp(name, "iso-max") == 0) {
  849. cc->iso_max = strtod(value, NULL);
  850. } else {
  851. g_printerr("Unknown key '%s' in [%s]\n", name, section);
  852. exit(1);
  853. }
  854. } else if (strcmp(section, "device") == 0) {
  855. if (strcmp(name, "csi") == 0) {
  856. media_drv_name = strdup(value);
  857. } else if (strcmp(name, "make") == 0) {
  858. exif_make = strdup(value);
  859. } else if (strcmp(name, "model") == 0) {
  860. exif_model = strdup(value);
  861. } else {
  862. g_printerr("Unknown key '%s' in [device]\n", name);
  863. exit(1);
  864. }
  865. } else {
  866. g_printerr("Unknown section '%s' in config file\n", section);
  867. exit(1);
  868. }
  869. return 1;
  870. }
  871. int
  872. find_dev_node(int maj, int min, char *fnbuf)
  873. {
  874. DIR *d;
  875. struct dirent *dir;
  876. struct stat info;
  877. d = opendir("/dev");
  878. while ((dir = readdir(d)) != NULL) {
  879. sprintf(fnbuf, "/dev/%s", dir->d_name);
  880. stat(fnbuf, &info);
  881. if (!S_ISCHR(info.st_mode)) {
  882. continue;
  883. }
  884. if (major(info.st_rdev) == maj && minor(info.st_rdev) == min) {
  885. return 0;
  886. }
  887. }
  888. return -1;
  889. }
  890. int
  891. setup_rear()
  892. {
  893. struct media_link_desc link = {0};
  894. // Disable the interface<->front link
  895. link.flags = 0;
  896. link.source.entity = front_cam.entity_id;
  897. link.source.index = 0;
  898. link.sink.entity = interface_entity_id;
  899. link.sink.index = 0;
  900. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  901. g_printerr("Could not disable front camera link\n");
  902. return -1;
  903. }
  904. // Enable the interface<->rear link
  905. link.flags = MEDIA_LNK_FL_ENABLED;
  906. link.source.entity = rear_cam.entity_id;
  907. link.source.index = 0;
  908. link.sink.entity = interface_entity_id;
  909. link.sink.index = 0;
  910. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  911. g_printerr("Could not enable rear camera link\n");
  912. return -1;
  913. }
  914. current = rear_cam;
  915. // Find camera node
  916. init_sensor(current.dev, current.width, current.height, current.mbus, current.rate);
  917. return 0;
  918. }
  919. int
  920. setup_front()
  921. {
  922. struct media_link_desc link = {0};
  923. // Disable the interface<->rear link
  924. link.flags = 0;
  925. link.source.entity = rear_cam.entity_id;
  926. link.source.index = 0;
  927. link.sink.entity = interface_entity_id;
  928. link.sink.index = 0;
  929. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  930. g_printerr("Could not disable rear camera link\n");
  931. return -1;
  932. }
  933. // Enable the interface<->rear link
  934. link.flags = MEDIA_LNK_FL_ENABLED;
  935. link.source.entity = front_cam.entity_id;
  936. link.source.index = 0;
  937. link.sink.entity = interface_entity_id;
  938. link.sink.index = 0;
  939. if (xioctl(media_fd, MEDIA_IOC_SETUP_LINK, &link) < 0) {
  940. g_printerr("Could not enable front camera link\n");
  941. return -1;
  942. }
  943. current = front_cam;
  944. // Find camera node
  945. init_sensor(current.dev, current.width, current.height, current.mbus, current.rate);
  946. return 0;
  947. }
  948. int
  949. find_cameras()
  950. {
  951. struct media_entity_desc entity = {0};
  952. int ret;
  953. int found = 0;
  954. while (1) {
  955. entity.id = entity.id | MEDIA_ENT_ID_FLAG_NEXT;
  956. ret = xioctl(media_fd, MEDIA_IOC_ENUM_ENTITIES, &entity);
  957. if (ret < 0) {
  958. break;
  959. }
  960. if (strncmp(entity.name, front_cam.dev_name, strlen(front_cam.dev_name)) == 0) {
  961. front_cam.entity_id = entity.id;
  962. find_dev_node(entity.dev.major, entity.dev.minor, front_cam.dev);
  963. printf("Found front cam, is %s at %s\n", entity.name, front_cam.dev);
  964. found++;
  965. }
  966. if (strncmp(entity.name, rear_cam.dev_name, strlen(rear_cam.dev_name)) == 0) {
  967. rear_cam.entity_id = entity.id;
  968. find_dev_node(entity.dev.major, entity.dev.minor, rear_cam.dev);
  969. printf("Found rear cam, is %s at %s\n", entity.name, rear_cam.dev);
  970. found++;
  971. }
  972. if (entity.type == MEDIA_ENT_F_IO_V4L) {
  973. interface_entity_id = entity.id;
  974. find_dev_node(entity.dev.major, entity.dev.minor, dev_name);
  975. printf("Found v4l2 interface node at %s\n", dev_name);
  976. }
  977. }
  978. if (found < 2) {
  979. return -1;
  980. }
  981. return 0;
  982. }
  983. int
  984. find_media_fd()
  985. {
  986. DIR *d;
  987. struct dirent *dir;
  988. int fd;
  989. char fnbuf[261];
  990. struct media_device_info mdi = {0};
  991. d = opendir("/dev");
  992. while ((dir = readdir(d)) != NULL) {
  993. if (strncmp(dir->d_name, "media", 5) == 0) {
  994. sprintf(fnbuf, "/dev/%s", dir->d_name);
  995. fd = open(fnbuf, O_RDWR);
  996. xioctl(fd, MEDIA_IOC_DEVICE_INFO, &mdi);
  997. if (strcmp(mdi.driver, media_drv_name) == 0) {
  998. printf("Found media device: %s (%s)\n", fnbuf, mdi.driver);
  999. media_fd = fd;
  1000. return 0;
  1001. }
  1002. close(fd);
  1003. }
  1004. }
  1005. g_printerr("Could not find /dev/media* node matching '%s'\n", media_drv_name);
  1006. return 1;
  1007. }
  1008. void
  1009. on_open_last_clicked(GtkWidget *widget, gpointer user_data)
  1010. {
  1011. char uri[270];
  1012. GError *error = NULL;
  1013. if(strlen(last_path) == 0) {
  1014. return;
  1015. }
  1016. sprintf(uri, "file://%s", last_path);
  1017. if(!g_app_info_launch_default_for_uri(uri, NULL, &error)){
  1018. g_printerr("Could not launch image viewer: %s\n", error->message);
  1019. }
  1020. }
  1021. void
  1022. on_open_directory_clicked(GtkWidget *widget, gpointer user_data)
  1023. {
  1024. char uri[270];
  1025. GError *error = NULL;
  1026. sprintf(uri, "file://%s/Pictures", getenv("HOME"));
  1027. if(!g_app_info_launch_default_for_uri(uri, NULL, &error)){
  1028. g_printerr("Could not launch image viewer: %s\n", error->message);
  1029. }
  1030. }
  1031. void
  1032. on_shutter_clicked(GtkWidget *widget, gpointer user_data)
  1033. {
  1034. char template[] = "/tmp/megapixels.XXXXXX";
  1035. char *tempdir;
  1036. tempdir = mkdtemp(template);
  1037. if (tempdir == NULL) {
  1038. g_printerr("Could not make capture directory %s\n", template);
  1039. exit (EXIT_FAILURE);
  1040. }
  1041. strcpy(burst_dir, tempdir);
  1042. // Disable the autogain/exposure while taking the burst
  1043. v4l2_ctrl_set(current.fd, V4L2_CID_AUTOGAIN, 0);
  1044. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
  1045. capture = burst_length;
  1046. }
  1047. void
  1048. on_preview_tap(GtkWidget *widget, GdkEventButton *event, gpointer user_data)
  1049. {
  1050. if (event->type != GDK_BUTTON_PRESS)
  1051. return;
  1052. // Handle taps on the controls
  1053. if (event->y < 32) {
  1054. if (gtk_widget_is_visible(control_box)) {
  1055. gtk_widget_hide(control_box);
  1056. return;
  1057. } else {
  1058. gtk_widget_show(control_box);
  1059. }
  1060. if (event->x < 60 ) {
  1061. // ISO
  1062. current_control = USER_CONTROL_ISO;
  1063. gtk_label_set_text(GTK_LABEL(control_name), "ISO");
  1064. gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(control_auto), auto_gain);
  1065. gtk_adjustment_set_lower(control_slider, 0.0);
  1066. gtk_adjustment_set_upper(control_slider, (float)current.gain_max);
  1067. gtk_adjustment_set_value(control_slider, (double)gain);
  1068. } else if (event->x > 60 && event->x < 120) {
  1069. // Shutter angle
  1070. current_control = USER_CONTROL_SHUTTER;
  1071. gtk_label_set_text(GTK_LABEL(control_name), "Shutter");
  1072. gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(control_auto), auto_exposure);
  1073. gtk_adjustment_set_lower(control_slider, 1.0);
  1074. gtk_adjustment_set_upper(control_slider, 360.0);
  1075. gtk_adjustment_set_value(control_slider, (double)exposure);
  1076. }
  1077. return;
  1078. }
  1079. // Tapped preview image itself, try focussing
  1080. if (current.has_af_s) {
  1081. v4l2_ctrl_set(current.fd, V4L2_CID_AUTO_FOCUS_STOP, 1);
  1082. v4l2_ctrl_set(current.fd, V4L2_CID_AUTO_FOCUS_START, 1);
  1083. }
  1084. }
  1085. void
  1086. on_error_close_clicked(GtkWidget *widget, gpointer user_data)
  1087. {
  1088. gtk_widget_hide(error_box);
  1089. }
  1090. void
  1091. on_camera_switch_clicked(GtkWidget *widget, gpointer user_data)
  1092. {
  1093. stop_capturing(video_fd);
  1094. close(current.fd);
  1095. if (current_is_rear == 1) {
  1096. setup_front();
  1097. current_is_rear = 0;
  1098. } else {
  1099. setup_rear();
  1100. current_is_rear = 1;
  1101. }
  1102. close(video_fd);
  1103. video_fd = open(dev_name, O_RDWR);
  1104. if (video_fd == -1) {
  1105. g_printerr("Error opening video device: %s\n", dev_name);
  1106. return;
  1107. }
  1108. init_device(video_fd);
  1109. start_capturing(video_fd);
  1110. }
  1111. void
  1112. on_settings_btn_clicked(GtkWidget *widget, gpointer user_data)
  1113. {
  1114. gtk_stack_set_visible_child_name(GTK_STACK(main_stack), "settings");
  1115. }
  1116. void
  1117. on_back_clicked(GtkWidget *widget, gpointer user_data)
  1118. {
  1119. gtk_stack_set_visible_child_name(GTK_STACK(main_stack), "main");
  1120. }
  1121. void
  1122. on_control_auto_toggled(GtkToggleButton *widget, gpointer user_data)
  1123. {
  1124. int fd = current.fd;
  1125. switch (current_control) {
  1126. case USER_CONTROL_ISO:
  1127. auto_gain = gtk_toggle_button_get_active(widget);
  1128. if (auto_gain) {
  1129. v4l2_ctrl_set(fd, V4L2_CID_AUTOGAIN, 1);
  1130. } else {
  1131. v4l2_ctrl_set(fd, V4L2_CID_AUTOGAIN, 0);
  1132. gain = v4l2_ctrl_get(fd, V4L2_CID_GAIN);
  1133. gtk_adjustment_set_value(control_slider, (double)gain);
  1134. }
  1135. break;
  1136. case USER_CONTROL_SHUTTER:
  1137. auto_exposure = gtk_toggle_button_get_active(widget);
  1138. if (auto_exposure) {
  1139. v4l2_ctrl_set(fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_AUTO);
  1140. } else {
  1141. v4l2_ctrl_set(fd, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
  1142. exposure = v4l2_ctrl_get(fd, V4L2_CID_EXPOSURE);
  1143. gtk_adjustment_set_value(control_slider, (double)exposure);
  1144. }
  1145. break;
  1146. }
  1147. draw_controls();
  1148. }
  1149. void
  1150. on_control_slider_changed(GtkAdjustment *widget, gpointer user_data)
  1151. {
  1152. double value = gtk_adjustment_get_value(widget);
  1153. switch (current_control) {
  1154. case USER_CONTROL_ISO:
  1155. gain = (int)value;
  1156. v4l2_ctrl_set(current.fd, current.gain_ctrl, gain);
  1157. break;
  1158. case USER_CONTROL_SHUTTER:
  1159. // So far all sensors use exposure time in number of sensor rows
  1160. exposure = (int)(value / 360.0 * current.height);
  1161. v4l2_ctrl_set(current.fd, V4L2_CID_EXPOSURE, exposure);
  1162. break;
  1163. }
  1164. draw_controls();
  1165. }
  1166. int
  1167. find_config(char *conffile)
  1168. {
  1169. char buf[512];
  1170. char *xdg_config_home;
  1171. wordexp_t exp_result;
  1172. FILE *fp;
  1173. // Resolve XDG stuff
  1174. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  1175. xdg_config_home = "~/.config";
  1176. }
  1177. wordexp(xdg_config_home, &exp_result, 0);
  1178. xdg_config_home = strdup(exp_result.we_wordv[0]);
  1179. wordfree(&exp_result);
  1180. if(access("/proc/device-tree/compatible", F_OK) != -1) {
  1181. // Reads to compatible string of the current device tree, looks like:
  1182. // pine64,pinephone-1.2\0allwinner,sun50i-a64\0
  1183. fp = fopen("/proc/device-tree/compatible", "r");
  1184. fgets(buf, 512, fp);
  1185. fclose(fp);
  1186. // Check config/%dt.ini in the current working directory
  1187. sprintf(conffile, "config/%s.ini", buf);
  1188. if(access(conffile, F_OK) != -1) {
  1189. printf("Found config file at %s\n", conffile);
  1190. return 0;
  1191. }
  1192. // Check for a config file in XDG_CONFIG_HOME
  1193. sprintf(conffile, "%s/megapixels/config/%s.ini", xdg_config_home, buf);
  1194. if(access(conffile, F_OK) != -1) {
  1195. printf("Found config file at %s\n", conffile);
  1196. return 0;
  1197. }
  1198. // Check user overridden /etc/megapixels/config/$dt.ini
  1199. sprintf(conffile, "%s/megapixels/config/%s.ini", SYSCONFDIR, buf);
  1200. if(access(conffile, F_OK) != -1) {
  1201. printf("Found config file at %s\n", conffile);
  1202. return 0;
  1203. }
  1204. // Check packaged /usr/share/megapixels/config/$dt.ini
  1205. sprintf(conffile, "%s/megapixels/config/%s.ini", DATADIR, buf);
  1206. if(access(conffile, F_OK) != -1) {
  1207. printf("Found config file at %s\n", conffile);
  1208. return 0;
  1209. }
  1210. printf("%s not found\n", conffile);
  1211. } else {
  1212. printf("Could not read device name from device tree\n");
  1213. }
  1214. // If all else fails, fall back to /etc/megapixels.ini
  1215. sprintf(conffile, "/etc/megapixels.ini");
  1216. if(access(conffile, F_OK) != -1) {
  1217. printf("Found config file at %s\n", conffile);
  1218. return 0;
  1219. }
  1220. return -1;
  1221. }
  1222. int
  1223. find_processor(char *script)
  1224. {
  1225. char *xdg_config_home;
  1226. char filename[] = "postprocess.sh";
  1227. wordexp_t exp_result;
  1228. // Resolve XDG stuff
  1229. if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL) {
  1230. xdg_config_home = "~/.config";
  1231. }
  1232. wordexp(xdg_config_home, &exp_result, 0);
  1233. xdg_config_home = strdup(exp_result.we_wordv[0]);
  1234. wordfree(&exp_result);
  1235. // Check postprocess.h in the current working directory
  1236. sprintf(script, "%s", filename);
  1237. if(access(script, F_OK) != -1) {
  1238. sprintf(script, "./%s", filename);
  1239. printf("Found postprocessor script at %s\n", script);
  1240. return 0;
  1241. }
  1242. // Check for a script in XDG_CONFIG_HOME
  1243. sprintf(script, "%s/megapixels/%s", xdg_config_home, filename);
  1244. if(access(script, F_OK) != -1) {
  1245. printf("Found postprocessor script at %s\n", script);
  1246. return 0;
  1247. }
  1248. // Check user overridden /etc/megapixels/postprocessor.sh
  1249. sprintf(script, "%s/megapixels/%s", SYSCONFDIR, filename);
  1250. if(access(script, F_OK) != -1) {
  1251. printf("Found postprocessor script at %s\n", script);
  1252. return 0;
  1253. }
  1254. // Check packaged /usr/share/megapixels/postprocessor.sh
  1255. sprintf(script, "%s/megapixels/%s", DATADIR, filename);
  1256. if(access(script, F_OK) != -1) {
  1257. printf("Found postprocessor script at %s\n", script);
  1258. return 0;
  1259. }
  1260. return -1;
  1261. }
  1262. int
  1263. main(int argc, char *argv[])
  1264. {
  1265. int ret;
  1266. char conffile[512];
  1267. ret = find_config(conffile);
  1268. if (ret) {
  1269. g_printerr("Could not find any config file\n");
  1270. return ret;
  1271. }
  1272. ret = find_processor(processing_script);
  1273. if (ret) {
  1274. g_printerr("Could not find any post-process script\n");
  1275. return ret;
  1276. }
  1277. setenv("LC_NUMERIC", "C", 1);
  1278. TIFFSetTagExtender(register_custom_tiff_tags);
  1279. gtk_init(&argc, &argv);
  1280. g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", TRUE, NULL);
  1281. GtkBuilder *builder = gtk_builder_new_from_resource("/org/postmarketos/Megapixels/camera.glade");
  1282. GtkWidget *window = GTK_WIDGET(gtk_builder_get_object(builder, "window"));
  1283. GtkWidget *shutter = GTK_WIDGET(gtk_builder_get_object(builder, "shutter"));
  1284. GtkWidget *switch_btn = GTK_WIDGET(gtk_builder_get_object(builder, "switch_camera"));
  1285. GtkWidget *settings_btn = GTK_WIDGET(gtk_builder_get_object(builder, "settings"));
  1286. GtkWidget *settings_back = GTK_WIDGET(gtk_builder_get_object(builder, "settings_back"));
  1287. GtkWidget *error_close = GTK_WIDGET(gtk_builder_get_object(builder, "error_close"));
  1288. GtkWidget *open_last = GTK_WIDGET(gtk_builder_get_object(builder, "open_last"));
  1289. GtkWidget *open_directory = GTK_WIDGET(gtk_builder_get_object(builder, "open_directory"));
  1290. preview = GTK_WIDGET(gtk_builder_get_object(builder, "preview"));
  1291. error_box = GTK_WIDGET(gtk_builder_get_object(builder, "error_box"));
  1292. error_message = GTK_WIDGET(gtk_builder_get_object(builder, "error_message"));
  1293. main_stack = GTK_WIDGET(gtk_builder_get_object(builder, "main_stack"));
  1294. thumb_last = GTK_WIDGET(gtk_builder_get_object(builder, "thumb_last"));
  1295. control_box = GTK_WIDGET(gtk_builder_get_object(builder, "control_box"));
  1296. control_name = GTK_WIDGET(gtk_builder_get_object(builder, "control_name"));
  1297. control_slider = GTK_ADJUSTMENT(gtk_builder_get_object(builder, "control_adj"));
  1298. control_auto = GTK_WIDGET(gtk_builder_get_object(builder, "control_auto"));
  1299. g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  1300. g_signal_connect(shutter, "clicked", G_CALLBACK(on_shutter_clicked), NULL);
  1301. g_signal_connect(error_close, "clicked", G_CALLBACK(on_error_close_clicked), NULL);
  1302. g_signal_connect(switch_btn, "clicked", G_CALLBACK(on_camera_switch_clicked), NULL);
  1303. g_signal_connect(settings_btn, "clicked", G_CALLBACK(on_settings_btn_clicked), NULL);
  1304. g_signal_connect(settings_back, "clicked", G_CALLBACK(on_back_clicked), NULL);
  1305. g_signal_connect(open_last, "clicked", G_CALLBACK(on_open_last_clicked), NULL);
  1306. g_signal_connect(open_directory, "clicked", G_CALLBACK(on_open_directory_clicked), NULL);
  1307. g_signal_connect(preview, "draw", G_CALLBACK(preview_draw), NULL);
  1308. g_signal_connect(preview, "configure-event", G_CALLBACK(preview_configure), NULL);
  1309. gtk_widget_set_events(preview, gtk_widget_get_events(preview) |
  1310. GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK);
  1311. g_signal_connect(preview, "button-press-event", G_CALLBACK(on_preview_tap), NULL);
  1312. g_signal_connect(control_auto, "toggled", G_CALLBACK(on_control_auto_toggled), NULL);
  1313. g_signal_connect(control_slider, "value-changed", G_CALLBACK(on_control_slider_changed), NULL);
  1314. GtkCssProvider *provider = gtk_css_provider_new();
  1315. if (access("camera.css", F_OK) != -1) {
  1316. gtk_css_provider_load_from_path(provider, "camera.css", NULL);
  1317. } else {
  1318. gtk_css_provider_load_from_resource(provider, "/org/postmarketos/Megapixels/camera.css");
  1319. }
  1320. GtkStyleContext *context = gtk_widget_get_style_context(error_box);
  1321. gtk_style_context_add_provider(context,
  1322. GTK_STYLE_PROVIDER(provider),
  1323. GTK_STYLE_PROVIDER_PRIORITY_USER);
  1324. context = gtk_widget_get_style_context(control_box);
  1325. gtk_style_context_add_provider(context,
  1326. GTK_STYLE_PROVIDER(provider),
  1327. GTK_STYLE_PROVIDER_PRIORITY_USER);
  1328. int result = ini_parse(conffile, config_ini_handler, NULL);
  1329. if (result == -1) {
  1330. g_printerr("Config file not found\n");
  1331. return 1;
  1332. } else if (result == -2) {
  1333. g_printerr("Could not allocate memory to parse config file\n");
  1334. return 1;
  1335. } else if (result != 0) {
  1336. g_printerr("Could not parse config file\n");
  1337. return 1;
  1338. }
  1339. if (find_media_fd() == -1) {
  1340. g_printerr("Could not find the media node\n");
  1341. show_error("Could not find the media node");
  1342. goto failed;
  1343. }
  1344. if (find_cameras() == -1) {
  1345. g_printerr("Could not find the cameras\n");
  1346. show_error("Could not find the cameras");
  1347. goto failed;
  1348. }
  1349. setup_rear();
  1350. int fd = open(dev_name, O_RDWR);
  1351. if (fd == -1) {
  1352. g_printerr("Error opening video device: %s\n", dev_name);
  1353. show_error("Error opening the video device");
  1354. goto failed;
  1355. }
  1356. video_fd = fd;
  1357. if(init_device(fd) < 0){
  1358. goto failed;
  1359. }
  1360. start_capturing(fd);
  1361. failed:
  1362. printf("window show\n");
  1363. gtk_widget_show(window);
  1364. g_idle_add((GSourceFunc)get_frame, NULL);
  1365. gtk_main();
  1366. return 0;
  1367. }