main.c 44 KB

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