git.jasLogic.tech
8d8bee41a57277ebf057c0f9baa13a448cdae0fd
[photobox.git] / src / photobox_photo.c
1 #include "photobox_photo.h"
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 #include <unistd.h>
7 #include <fcntl.h>
8
9 #include <gphoto2/gphoto2.h>
10 #include <gphoto2/gphoto2-camera.h>
11
12 #define perror_inf() fprintf(stderr, "%s:%d: In function %s:\n", __FILE__, \
13 __LINE__, __func__)
14
15 static Camera *camera;
16 static GPContext *context;
17
18 int pb_ph_init(void) {
19 context = gp_context_new();
20 gp_camera_new(&camera);
21
22 int ret = gp_camera_init(camera, context);
23 if (ret != GP_OK) {
24 perror_inf();
25 perror("Failed to initialize camera");
26 return -1;
27 }
28
29 return 0;
30 }
31
32 int pb_ph_capture(pb_ph_buffer *buf) {
33 int ret;
34 CameraFile *file;
35 CameraFilePath camera_file_path;
36
37 ret = gp_camera_capture(camera, GP_CAPTURE_IMAGE, &camera_file_path, context);
38 if (ret != 0) {
39 perror_inf();
40 perror("Failed to capture image");
41 return -1;
42 }
43
44 ret = gp_file_new(&file);
45 if (ret != 0) {
46 perror_inf();
47 perror("Failed to create new file");
48 return -1;
49 }
50
51 ret = gp_camera_file_get(camera, camera_file_path.folder, camera_file_path.name, GP_FILE_TYPE_NORMAL,
52 file, context);
53 if (ret != 0) {
54 perror_inf();
55 perror("Failed to get image");
56 return -1;
57 }
58
59 ret = gp_camera_file_delete(camera, camera_file_path.folder, camera_file_path.name, context);
60 if (ret != 0) {
61 perror_inf();
62 perror("Failed to delete image from camera");
63 return -1;
64 }
65
66 gp_file_get_data_and_size(file, (const char **)&buf->base, &buf->size);
67 if (ret != 0) {
68 perror_inf();
69 perror("Failed to get data and size");
70 return -1;
71 }
72
73 return 0;
74 }
75
76 int pb_ph_capture_file(const char *fn) {
77 int ret, fd;
78 CameraFile *file;
79 CameraFilePath camera_file_path;
80
81 ret = gp_camera_capture(camera, GP_CAPTURE_IMAGE, &camera_file_path, context);
82 if (ret != 0) {
83 perror_inf();
84 perror("Failed to capture image");
85 return -1;
86 }
87
88 fd = open(fn, O_CREAT | O_WRONLY, 0644);
89 if (fd == -1) {
90 perror_inf();
91 perror("Failed to open file");
92 return -1;
93 }
94
95 ret = gp_file_new_from_fd(&file, fd);
96 if (ret != 0) {
97 perror_inf();
98 perror("Failed to create image file");
99 return -1;
100 }
101
102 ret = gp_camera_file_get(camera, camera_file_path.folder, camera_file_path.name, GP_FILE_TYPE_NORMAL,
103 file, context);
104 if (ret != 0) {
105 perror_inf();
106 perror("Failed to get image");
107 return -1;
108 }
109
110 gp_file_free(file);
111
112 ret = gp_camera_file_delete(camera, camera_file_path.folder, camera_file_path.name, context);
113 if (ret != 0) {
114 perror_inf();
115 perror("Failed to delete image from camera");
116 return -1;
117 }
118
119 // close fd? done in gphoto?
120 close(fd);
121
122 return 0;
123 }