blob: 8ee82f3621e5024411dee311d35848af2ee62ab1 [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"
Tyler Chatowe0241452019-03-08 21:07:50 -080015#include "y2019/image_streamer/flip_image.h"
Michael Schuh5a1a7582019-03-01 13:03:47 -080016#include "y2019/vision.pb.h"
17
18using ::aos::events::DataSocket;
19using ::aos::events::RXUdpSocket;
20using ::aos::events::TCPServer;
21using ::aos::vision::DataRef;
22using ::aos::vision::Int32Codec;
23using ::aos::monotonic_clock;
24using ::y2019::VisionControl;
25
26DEFINE_string(roborio_ip, "10.9.71.2", "RoboRIO IP Address");
27DEFINE_string(log, "",
28 "If non-empty, log images to the specified prefix with the image "
29 "index appended to the filename");
30DEFINE_bool(single_camera, true, "If true, only use video0");
31DEFINE_int32(camera0_exposure, 600, "Exposure for video0");
32DEFINE_int32(camera1_exposure, 600, "Exposure for video1");
33
34aos::vision::DataRef mjpg_header =
35 "HTTP/1.0 200 OK\r\n"
36 "Server: YourServerName\r\n"
37 "Connection: close\r\n"
38 "Max-Age: 0\r\n"
39 "Expires: 0\r\n"
40 "Cache-Control: no-cache, private\r\n"
41 "Pragma: no-cache\r\n"
42 "Content-Type: multipart/x-mixed-replace; "
43 "boundary=--boundary\r\n\r\n";
44
45struct Frame {
46 std::string data;
47};
48
49inline bool FileExist(const std::string &name) {
50 struct stat buffer;
51 return (stat(name.c_str(), &buffer) == 0);
52}
53
54class BlobLog {
55 public:
56 explicit BlobLog(const char *prefix, const char *extension) {
57 int index = 0;
58 while (true) {
59 std::string file = prefix + std::to_string(index) + extension;
60 if (FileExist(file)) {
61 index++;
62 } else {
63 printf("Logging to file (%s)\n", file.c_str());
64 ofst_.open(file);
65 assert(ofst_.is_open());
66 break;
67 }
68 }
69 }
70
71 ~BlobLog() { ofst_.close(); }
72
73 void WriteLogEntry(DataRef data) { ofst_.write(&data[0], data.size()); }
74
75 private:
76 std::ofstream ofst_;
77};
78
79class UdpClient : public ::aos::events::EpollEvent {
80 public:
81 UdpClient(int port, ::std::function<void(void *, size_t)> callback)
82 : ::aos::events::EpollEvent(RXUdpSocket::SocketBindListenOnPort(port)),
83 callback_(callback) {}
84
85 private:
86 ::std::function<void(void *, size_t)> callback_;
87
88 void ReadEvent() override {
89 char data[1024];
90 size_t received_data_size = Recv(data, sizeof(data));
91 callback_(data, received_data_size);
92 }
93
94 size_t Recv(void *data, int size) {
95 return PCHECK(recv(fd(), static_cast<char *>(data), size, 0));
96 }
97};
98
99// TODO(aschuh & michael) Pull this out.
100template <typename PB>
101class ProtoUdpClient : public UdpClient {
102 public:
103 ProtoUdpClient(int port, ::std::function<void(const PB &)> proto_callback)
104 : UdpClient(port, ::std::bind(&ProtoUdpClient::ReadData, this,
105 ::std::placeholders::_1,
106 ::std::placeholders::_2)),
107 proto_callback_(proto_callback) {}
108
109 private:
110 ::std::function<void(const PB &)> proto_callback_;
111
112 void ReadData(void *data, size_t size) {
113 PB pb;
114 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 {
145 // Ignore reads, but don't leave them pending.
146 ssize_t count;
147 char buf[512];
148 while (true) {
149 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 }
Tyler Chatowe0241452019-03-08 21:07:50 -0800199 LOG(INFO, "Frame size in bytes: data.size() = %zu\n", data.size());
Michael Schuh5a1a7582019-03-01 13:03:47 -0800200 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
Tyler Chatowe0241452019-03-08 21:07:50 -0800259 void set_flip(bool flip) { flip_ = flip; }
260
Michael Schuh5a1a7582019-03-01 13:03:47 -0800261 bool active() const { return active_; }
262
263 void ProcessImage(DataRef data,
264 monotonic_clock::time_point /*monotonic_now*/) {
265 ++sampling;
266 // 20 is the sampling rate.
267 if (sampling == 20) {
268 int tmp_size = data.size() + sizeof(int32_t);
269 char *buf;
270 std::string log_record;
271 log_record.resize(tmp_size, 0);
272 {
273 buf = Int32Codec::Write(&log_record[0], tmp_size);
274 data.copy(buf, data.size());
275 }
276 if (log_) {
277 log_->WriteLogEntry(log_record);
278 }
279 sampling = 0;
280 }
281
Tyler Chatowe0241452019-03-08 21:07:50 -0800282 std::string image_out;
283
284 if (flip_) {
285 unsigned int out_size = image_buffer_out_.size();
286 flip_image(data.data(), data.size(), &image_buffer_out_[0], &out_size);
287 image_out.assign(&image_buffer_out_[0], &image_buffer_out_[out_size]);
288 } else {
289 image_out = std::string(data);
290 }
291
Michael Schuh5a1a7582019-03-01 13:03:47 -0800292 if (active_) {
Tyler Chatowe0241452019-03-08 21:07:50 -0800293 auto frame = std::make_shared<Frame>(Frame{image_out});
Michael Schuh5a1a7582019-03-01 13:03:47 -0800294 tcp_server_->Broadcast(
295 [frame](MjpegDataSocket *event) { event->NewFrame(frame); });
296 }
297 frame_callback_();
298 }
299
300 private:
301 int sampling = 0;
302 TCPServer<MjpegDataSocket> *tcp_server_;
303 ::std::unique_ptr<BlobLog> log_;
304 ::std::function<void()> frame_callback_;
305 bool active_ = false;
Tyler Chatowe0241452019-03-08 21:07:50 -0800306 bool flip_ = false;
307 std::array<JOCTET, 100000> image_buffer_out_;
Michael Schuh5a1a7582019-03-01 13:03:47 -0800308};
309
310int main(int argc, char **argv) {
311 gflags::ParseCommandLineFlags(&argc, &argv, false);
312 ::aos::logging::Init();
313 ::aos::logging::AddImplementation(
314 new ::aos::logging::StreamLogImplementation(stderr));
315 TCPServer<MjpegDataSocket> tcp_server_(80);
316 aos::vision::CameraParams params0;
317 params0.set_exposure(FLAGS_camera0_exposure);
318 params0.set_brightness(-40);
319 params0.set_width(320);
320 // params0.set_fps(10);
321 params0.set_height(240);
322
323 aos::vision::CameraParams params1 = params0;
324 params1.set_exposure(FLAGS_camera1_exposure);
325
326 ::y2019::VisionStatus vision_status;
327 LOG(INFO,
328 "The UDP socket should be on port 5001 to 10.9.71.2 for "
329 "the competition robot.\n");
330 LOG(INFO, "Starting UDP socket on port 5001 to %s\n",
331 FLAGS_roborio_ip.c_str());
332 ::aos::events::ProtoTXUdpSocket<::y2019::VisionStatus> status_socket(
333 FLAGS_roborio_ip.c_str(), 5001);
334
335 ::std::unique_ptr<CameraStream> camera1;
336 ::std::unique_ptr<CameraStream> camera0(new CameraStream(
337 params0, "/dev/video0", &tcp_server_, !FLAGS_log.empty(),
338 [&camera0, &camera1, &status_socket, &vision_status]() {
339 vision_status.set_low_frame_count(vision_status.low_frame_count() + 1);
340 LOG(INFO, "Got a frame cam0\n");
341 if (camera0->active()) {
342 status_socket.Send(vision_status);
343 }
344 }));
345 if (!FLAGS_single_camera) {
346 camera1.reset(new CameraStream(
347 params1, "/dev/video1", &tcp_server_, false,
348 [&camera0, &camera1, &status_socket, &vision_status]() {
349 vision_status.set_high_frame_count(vision_status.high_frame_count() +
350 1);
351 LOG(INFO, "Got a frame cam1\n");
352 if (camera1->active()) {
353 status_socket.Send(vision_status);
354 }
355 }));
356 }
357
358 ProtoUdpClient<VisionControl> udp_client(
359 5000, [&camera0, &camera1](const VisionControl &vision_control) {
360 bool cam0_active = false;
Tyler Chatowe0241452019-03-08 21:07:50 -0800361 camera0->set_flip(vision_control.flip_image());
Michael Schuh5a1a7582019-03-01 13:03:47 -0800362 if (camera1) {
Tyler Chatowe0241452019-03-08 21:07:50 -0800363 camera1->set_flip(vision_control.flip_image());
Michael Schuh5a1a7582019-03-01 13:03:47 -0800364 cam0_active = !vision_control.high_video();
365 camera0->set_active(!vision_control.high_video());
366 camera1->set_active(vision_control.high_video());
367 } else {
368 cam0_active = true;
369 camera0->set_active(true);
370 }
371 LOG(INFO, "Got control packet, cam%d active\n", cam0_active ? 0 : 1);
372 });
373
374 // Default to camera0
375 camera0->set_active(true);
376 if (camera1) {
377 camera1->set_active(false);
378 }
379
380 aos::events::EpollLoop loop;
381 loop.Add(&tcp_server_);
382 loop.Add(camera0.get());
383 if (camera1) {
384 loop.Add(camera1.get());
385 }
386 loop.Add(&udp_client);
387
388 printf("Running Camera\n");
389 loop.Run();
390}