blob: 631fceeb14fa804801a82c7a763b1c443c7ed272 [file] [log] [blame]
Michael Schuh5a1a7582019-03-01 13:03:47 -08001#include "aos/vision/image/image_stream.h"
2
3#include <sys/stat.h>
4#include <deque>
5#include <fstream>
6#include <string>
7
8#include "aos/logging/implementations.h"
9#include "aos/logging/logging.h"
10#include "aos/vision/blob/codec.h"
11#include "aos/vision/events/socket_types.h"
12#include "aos/vision/events/udp.h"
13#include "aos/vision/image/reader.h"
14#include "gflags/gflags.h"
15#include "y2019/vision.pb.h"
16
17using ::aos::events::DataSocket;
18using ::aos::events::RXUdpSocket;
19using ::aos::events::TCPServer;
20using ::aos::vision::DataRef;
21using ::aos::vision::Int32Codec;
22using ::aos::monotonic_clock;
23using ::y2019::VisionControl;
24
25DEFINE_string(roborio_ip, "10.9.71.2", "RoboRIO IP Address");
26DEFINE_string(log, "",
27 "If non-empty, log images to the specified prefix with the image "
28 "index appended to the filename");
29DEFINE_bool(single_camera, true, "If true, only use video0");
30DEFINE_int32(camera0_exposure, 600, "Exposure for video0");
31DEFINE_int32(camera1_exposure, 600, "Exposure for video1");
32
33aos::vision::DataRef mjpg_header =
34 "HTTP/1.0 200 OK\r\n"
35 "Server: YourServerName\r\n"
36 "Connection: close\r\n"
37 "Max-Age: 0\r\n"
38 "Expires: 0\r\n"
39 "Cache-Control: no-cache, private\r\n"
40 "Pragma: no-cache\r\n"
41 "Content-Type: multipart/x-mixed-replace; "
42 "boundary=--boundary\r\n\r\n";
43
44struct Frame {
45 std::string data;
46};
47
48inline bool FileExist(const std::string &name) {
49 struct stat buffer;
50 return (stat(name.c_str(), &buffer) == 0);
51}
52
53class BlobLog {
54 public:
55 explicit BlobLog(const char *prefix, const char *extension) {
56 int index = 0;
57 while (true) {
58 std::string file = prefix + std::to_string(index) + extension;
59 if (FileExist(file)) {
60 index++;
61 } else {
62 printf("Logging to file (%s)\n", file.c_str());
63 ofst_.open(file);
64 assert(ofst_.is_open());
65 break;
66 }
67 }
68 }
69
70 ~BlobLog() { ofst_.close(); }
71
72 void WriteLogEntry(DataRef data) { ofst_.write(&data[0], data.size()); }
73
74 private:
75 std::ofstream ofst_;
76};
77
78class UdpClient : public ::aos::events::EpollEvent {
79 public:
80 UdpClient(int port, ::std::function<void(void *, size_t)> callback)
81 : ::aos::events::EpollEvent(RXUdpSocket::SocketBindListenOnPort(port)),
82 callback_(callback) {}
83
84 private:
85 ::std::function<void(void *, size_t)> callback_;
86
87 void ReadEvent() override {
88 char data[1024];
89 size_t received_data_size = Recv(data, sizeof(data));
90 callback_(data, received_data_size);
91 }
92
93 size_t Recv(void *data, int size) {
94 return PCHECK(recv(fd(), static_cast<char *>(data), size, 0));
95 }
96};
97
98// TODO(aschuh & michael) Pull this out.
99template <typename PB>
100class ProtoUdpClient : public UdpClient {
101 public:
102 ProtoUdpClient(int port, ::std::function<void(const PB &)> proto_callback)
103 : UdpClient(port, ::std::bind(&ProtoUdpClient::ReadData, this,
104 ::std::placeholders::_1,
105 ::std::placeholders::_2)),
106 proto_callback_(proto_callback) {}
107
108 private:
109 ::std::function<void(const PB &)> proto_callback_;
110
111 void ReadData(void *data, size_t size) {
112 PB pb;
Brian Silverman05271722019-03-09 16:09:31 -0800113 // TODO(Brian): Do something useful if parsing fails.
Michael Schuh5a1a7582019-03-01 13:03:47 -0800114 pb.ParseFromArray(data, size);
115 proto_callback_(pb);
116 }
117};
118
119class MjpegDataSocket : public aos::events::SocketConnection {
120 public:
121 MjpegDataSocket(aos::events::TCPServerBase *server, int fd)
122 : aos::events::SocketConnection(server, fd) {
123 SetEvents(EPOLLOUT | EPOLLET);
124 }
125
126 ~MjpegDataSocket() { printf("Closed connection on descriptor %d\n", fd()); }
127
128 void DirectEvent(uint32_t events) override {
129 if (events & EPOLLOUT) {
130 NewDataToSend();
131 events &= ~EPOLLOUT;
132 }
133 // Other end hung up. Ditch the connection.
134 if (events & EPOLLHUP) {
135 CloseConnection();
136 events &= ~EPOLLHUP;
137 return;
138 }
139 if (events) {
140 aos::events::EpollEvent::DirectEvent(events);
141 }
142 }
143
144 void ReadEvent() override {
Michael Schuh5a1a7582019-03-01 13:03:47 -0800145 ssize_t count;
146 char buf[512];
147 while (true) {
Brian Silverman05271722019-03-09 16:09:31 -0800148 // Always read everything so epoll won't return immediately.
Michael Schuh5a1a7582019-03-01 13:03:47 -0800149 count = read(fd(), &buf, sizeof buf);
150 if (count <= 0) {
151 if (errno != EAGAIN) {
152 CloseConnection();
153 return;
154 }
155 break;
156 } else if (!ready_to_receive_) {
157 // This 4 should match "\r\n\r\n".length();
158 if (match_i_ >= 4) {
159 printf("reading after last match\n");
160 continue;
161 }
162 for (char c : aos::vision::DataRef(&buf[0], count)) {
163 if (c == "\r\n\r\n"[match_i_]) {
164 ++match_i_;
165 if (match_i_ >= 4) {
166 if (!ready_to_receive_) {
167 ready_to_receive_ = true;
168 RasterHeader();
169 }
170 }
171 } else if (match_i_ != 0) {
172 if (c == '\r') match_i_ = 1;
173 }
174 }
175 }
176 }
177 }
178
179 void RasterHeader() {
180 output_buffer_.push_back(mjpg_header);
181 NewDataToSend();
182 }
183
184 void RasterFrame(std::shared_ptr<Frame> frame) {
185 if (!output_buffer_.empty() || !ready_to_receive_) return;
186 sending_frame_ = frame;
187 aos::vision::DataRef data = frame->data;
188
189 size_t n_written = snprintf(data_header_tmp_, sizeof(data_header_tmp_),
190 "--boundary\r\n"
191 "Content-type: image/jpg\r\n"
192 "Content-Length: %zu\r\n\r\n",
193 data.size());
194 // This should never happen because the buffer should be properly sized.
195 if (n_written == sizeof(data_header_tmp_)) {
196 fprintf(stderr, "wrong sized buffer\n");
197 exit(-1);
198 }
199 LOG(INFO, "Frame size in bytes: data.size() = %zu\n",data.size());
200 output_buffer_.push_back(aos::vision::DataRef(data_header_tmp_, n_written));
201 output_buffer_.push_back(data);
202 output_buffer_.push_back("\r\n\r\n");
203 NewDataToSend();
204 }
205
206 void NewFrame(std::shared_ptr<Frame> frame) { RasterFrame(std::move(frame)); }
207
208 void NewDataToSend() {
209 while (!output_buffer_.empty()) {
210 auto &data = *output_buffer_.begin();
211
212 while (!data.empty()) {
213 int len = send(fd(), data.data(), data.size(), MSG_NOSIGNAL);
214 if (len == -1) {
215 if (errno == EAGAIN) {
216 // Next thinggy will pick this up.
217 return;
218 } else {
219 CloseConnection();
220 return;
221 }
222 } else {
223 data.remove_prefix(len);
224 }
225 }
226 output_buffer_.pop_front();
227 }
228 }
229
230 private:
231 char data_header_tmp_[512];
232 std::shared_ptr<Frame> sending_frame_;
233 std::deque<aos::vision::DataRef> output_buffer_;
234
235 bool ready_to_receive_ = false;
236 void CloseConnection() {
237 loop()->Delete(this);
238 close(fd());
239 delete this;
240 }
241 size_t match_i_ = 0;
242};
243
244class CameraStream : public ::aos::vision::ImageStreamEvent {
245 public:
246 CameraStream(::aos::vision::CameraParams params, const ::std::string &fname,
247 TCPServer<MjpegDataSocket> *tcp_server, bool log,
248 ::std::function<void()> frame_callback)
249 : ImageStreamEvent(fname, params),
250 tcp_server_(tcp_server),
251 frame_callback_(frame_callback) {
252 if (log) {
253 log_.reset(new BlobLog(FLAGS_log.c_str(), ".dat"));
254 }
255 }
256
257 void set_active(bool active) { active_ = active; }
258
259 bool active() const { return active_; }
260
261 void ProcessImage(DataRef data,
262 monotonic_clock::time_point /*monotonic_now*/) {
263 ++sampling;
264 // 20 is the sampling rate.
265 if (sampling == 20) {
266 int tmp_size = data.size() + sizeof(int32_t);
267 char *buf;
268 std::string log_record;
269 log_record.resize(tmp_size, 0);
270 {
271 buf = Int32Codec::Write(&log_record[0], tmp_size);
272 data.copy(buf, data.size());
273 }
274 if (log_) {
275 log_->WriteLogEntry(log_record);
276 }
277 sampling = 0;
278 }
279
280 if (active_) {
281 auto frame = std::make_shared<Frame>(Frame{std::string(data)});
282 tcp_server_->Broadcast(
283 [frame](MjpegDataSocket *event) { event->NewFrame(frame); });
284 }
285 frame_callback_();
286 }
287
288 private:
289 int sampling = 0;
290 TCPServer<MjpegDataSocket> *tcp_server_;
291 ::std::unique_ptr<BlobLog> log_;
292 ::std::function<void()> frame_callback_;
293 bool active_ = false;
294};
295
296int main(int argc, char **argv) {
297 gflags::ParseCommandLineFlags(&argc, &argv, false);
298 ::aos::logging::Init();
299 ::aos::logging::AddImplementation(
300 new ::aos::logging::StreamLogImplementation(stderr));
301 TCPServer<MjpegDataSocket> tcp_server_(80);
302 aos::vision::CameraParams params0;
303 params0.set_exposure(FLAGS_camera0_exposure);
304 params0.set_brightness(-40);
305 params0.set_width(320);
306 // params0.set_fps(10);
307 params0.set_height(240);
308
309 aos::vision::CameraParams params1 = params0;
310 params1.set_exposure(FLAGS_camera1_exposure);
311
312 ::y2019::VisionStatus vision_status;
313 LOG(INFO,
314 "The UDP socket should be on port 5001 to 10.9.71.2 for "
315 "the competition robot.\n");
316 LOG(INFO, "Starting UDP socket on port 5001 to %s\n",
317 FLAGS_roborio_ip.c_str());
318 ::aos::events::ProtoTXUdpSocket<::y2019::VisionStatus> status_socket(
319 FLAGS_roborio_ip.c_str(), 5001);
320
321 ::std::unique_ptr<CameraStream> camera1;
322 ::std::unique_ptr<CameraStream> camera0(new CameraStream(
323 params0, "/dev/video0", &tcp_server_, !FLAGS_log.empty(),
Brian Silverman05271722019-03-09 16:09:31 -0800324 [&camera0, &status_socket, &vision_status]() {
Michael Schuh5a1a7582019-03-01 13:03:47 -0800325 vision_status.set_low_frame_count(vision_status.low_frame_count() + 1);
326 LOG(INFO, "Got a frame cam0\n");
327 if (camera0->active()) {
328 status_socket.Send(vision_status);
329 }
330 }));
331 if (!FLAGS_single_camera) {
332 camera1.reset(new CameraStream(
333 params1, "/dev/video1", &tcp_server_, false,
Brian Silverman05271722019-03-09 16:09:31 -0800334 [&camera1, &status_socket, &vision_status]() {
Michael Schuh5a1a7582019-03-01 13:03:47 -0800335 vision_status.set_high_frame_count(vision_status.high_frame_count() +
336 1);
337 LOG(INFO, "Got a frame cam1\n");
338 if (camera1->active()) {
339 status_socket.Send(vision_status);
340 }
341 }));
342 }
343
344 ProtoUdpClient<VisionControl> udp_client(
345 5000, [&camera0, &camera1](const VisionControl &vision_control) {
346 bool cam0_active = false;
347 if (camera1) {
348 cam0_active = !vision_control.high_video();
349 camera0->set_active(!vision_control.high_video());
350 camera1->set_active(vision_control.high_video());
351 } else {
352 cam0_active = true;
353 camera0->set_active(true);
354 }
355 LOG(INFO, "Got control packet, cam%d active\n", cam0_active ? 0 : 1);
356 });
357
358 // Default to camera0
359 camera0->set_active(true);
360 if (camera1) {
361 camera1->set_active(false);
362 }
363
364 aos::events::EpollLoop loop;
365 loop.Add(&tcp_server_);
366 loop.Add(camera0.get());
367 if (camera1) {
368 loop.Add(camera1.get());
369 }
370 loop.Add(&udp_client);
371
372 printf("Running Camera\n");
373 loop.Run();
374}