main.c 43 KB

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