main.c 41 KB

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