You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
			
				
					287 lines
				
				9.8 KiB
			
		
		
			
		
	
	
					287 lines
				
				9.8 KiB
			| 
											3 years ago
										 | #include "system/loggerd/loggerd.h"
 | ||
|  | #include "system/loggerd/video_writer.h"
 | ||
| 
											5 years ago
										 | 
 | ||
|  | ExitHandler do_exit;
 | ||
|  | 
 | ||
| 
											4 years ago
										 | struct LoggerdState {
 | ||
|  |   LoggerState logger = {};
 | ||
|  |   char segment_path[4096];
 | ||
|  |   std::atomic<int> rotate_segment;
 | ||
|  |   std::atomic<double> last_camera_seen_tms;
 | ||
|  |   std::atomic<int> ready_to_rotate;  // count of encoders ready to rotate
 | ||
|  |   int max_waiting = 0;
 | ||
|  |   double last_rotate_tms = 0.;      // last rotate time in ms
 | ||
|  | };
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											4 years ago
										 | void logger_rotate(LoggerdState *s) {
 | ||
| 
											3 years ago
										 |   int segment = -1;
 | ||
|  |   int err = logger_next(&s->logger, LOG_ROOT.c_str(), s->segment_path, sizeof(s->segment_path), &segment);
 | ||
|  |   assert(err == 0);
 | ||
|  |   s->rotate_segment = segment;
 | ||
|  |   s->ready_to_rotate = 0;
 | ||
|  |   s->last_rotate_tms = millis_since_boot();
 | ||
| 
											4 years ago
										 |   LOGW((s->logger.part == 0) ? "logging to %s" : "rotated to %s", s->segment_path);
 | ||
| 
											4 years ago
										 | }
 | ||
|  | 
 | ||
| 
											4 years ago
										 | void rotate_if_needed(LoggerdState *s) {
 | ||
| 
											3 years ago
										 |   // all encoders ready, trigger rotation
 | ||
|  |   bool all_ready = s->ready_to_rotate == s->max_waiting;
 | ||
| 
											4 years ago
										 | 
 | ||
| 
											3 years ago
										 |   // fallback logic to prevent extremely long segments in the case of camera, encoder, etc. malfunctions
 | ||
|  |   bool timed_out = false;
 | ||
| 
											4 years ago
										 |   double tms = millis_since_boot();
 | ||
| 
											3 years ago
										 |   double seg_length_secs = (tms - s->last_rotate_tms) / 1000.;
 | ||
|  |   if ((seg_length_secs > SEGMENT_LENGTH) && !LOGGERD_TEST) {
 | ||
|  |     // TODO: might be nice to put these reasons in the sentinel
 | ||
|  |     if ((tms - s->last_camera_seen_tms) > NO_CAMERA_PATIENCE) {
 | ||
|  |       timed_out = true;
 | ||
|  |       LOGE("no camera packets seen. auto rotating");
 | ||
|  |     } else if (seg_length_secs > SEGMENT_LENGTH*1.2) {
 | ||
|  |       timed_out = true;
 | ||
|  |       LOGE("segment too long. auto rotating");
 | ||
|  |     }
 | ||
|  |   }
 | ||
|  | 
 | ||
|  |   if (all_ready || timed_out) {
 | ||
| 
											4 years ago
										 |     logger_rotate(s);
 | ||
| 
											4 years ago
										 |   }
 | ||
|  | }
 | ||
|  | 
 | ||
| 
											4 years ago
										 | struct RemoteEncoder {
 | ||
|  |   std::unique_ptr<VideoWriter> writer;
 | ||
| 
											3 years ago
										 |   int encoderd_segment_offset;
 | ||
|  |   int current_segment = -1;
 | ||
| 
											4 years ago
										 |   std::vector<Message *> q;
 | ||
|  |   int dropped_frames = 0;
 | ||
|  |   bool recording = false;
 | ||
| 
											3 years ago
										 |   bool marked_ready_to_rotate = false;
 | ||
|  |   bool seen_first_packet = false;
 | ||
| 
											4 years ago
										 | };
 | ||
|  | 
 | ||
|  | int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct RemoteEncoder &re) {
 | ||
|  |   const LogCameraInfo &cam_info = (name == "driverEncodeData") ? cameras_logged[1] :
 | ||
|  |     ((name == "wideRoadEncodeData") ? cameras_logged[2] :
 | ||
|  |     ((name == "qRoadEncodeData") ? qcam_info : cameras_logged[0]));
 | ||
|  |   int bytes_count = 0;
 | ||
|  | 
 | ||
|  |   // extract the message
 | ||
| 
											3 years ago
										 |   capnp::FlatArrayMessageReader cmsg(kj::ArrayPtr<capnp::word>((capnp::word *)msg->getData(), msg->getSize() / sizeof(capnp::word)));
 | ||
| 
											4 years ago
										 |   auto event = cmsg.getRoot<cereal::Event>();
 | ||
|  |   auto edata = (name == "driverEncodeData") ? event.getDriverEncodeData() :
 | ||
|  |     ((name == "wideRoadEncodeData") ? event.getWideRoadEncodeData() :
 | ||
|  |     ((name == "qRoadEncodeData") ? event.getQRoadEncodeData() : event.getRoadEncodeData()));
 | ||
|  |   auto idx = edata.getIdx();
 | ||
|  |   auto flags = idx.getFlags();
 | ||
|  | 
 | ||
| 
											3 years ago
										 |   // encoderd can have started long before loggerd
 | ||
|  |   if (!re.seen_first_packet) {
 | ||
|  |     re.seen_first_packet = true;
 | ||
|  |     re.encoderd_segment_offset = idx.getSegmentNum();
 | ||
|  |     LOGD("%s: has encoderd offset %d", name.c_str(), re.encoderd_segment_offset);
 | ||
|  |   }
 | ||
|  |   int offset_segment_num = idx.getSegmentNum() - re.encoderd_segment_offset;
 | ||
|  | 
 | ||
|  |   if (offset_segment_num == s->rotate_segment) {
 | ||
|  |     // loggerd is now on the segment that matches this packet
 | ||
|  | 
 | ||
|  |     // if this is a new segment, we close any possible old segments, move to the new, and process any queued packets
 | ||
|  |     if (re.current_segment != s->rotate_segment) {
 | ||
|  |       if (re.recording) {
 | ||
|  |         re.writer.reset();
 | ||
|  |         re.recording = false;
 | ||
| 
											4 years ago
										 |       }
 | ||
| 
											3 years ago
										 |       re.current_segment = s->rotate_segment;
 | ||
|  |       re.marked_ready_to_rotate = false;
 | ||
|  |       // we are in this segment now, process any queued messages before this one
 | ||
|  |       if (!re.q.empty()) {
 | ||
|  |         for (auto &qmsg: re.q) {
 | ||
|  |           bytes_count += handle_encoder_msg(s, qmsg, name, re);
 | ||
|  |         }
 | ||
|  |         re.q.clear();
 | ||
| 
											4 years ago
										 |       }
 | ||
|  |     }
 | ||
|  | 
 | ||
| 
											3 years ago
										 |     // if we aren't recording yet, try to start, since we are in the correct segment
 | ||
|  |     if (!re.recording) {
 | ||
|  |       if (flags & V4L2_BUF_FLAG_KEYFRAME) {
 | ||
|  |         // only create on iframe
 | ||
|  |         if (re.dropped_frames) {
 | ||
|  |           // this should only happen for the first segment, maybe
 | ||
|  |           LOGW("%s: dropped %d non iframe packets before init", name.c_str(), re.dropped_frames);
 | ||
|  |           re.dropped_frames = 0;
 | ||
|  |         }
 | ||
|  |         // if we aren't actually recording, don't create the writer
 | ||
|  |         if (cam_info.record) {
 | ||
|  |           re.writer.reset(new VideoWriter(s->segment_path,
 | ||
|  |             cam_info.filename, idx.getType() != cereal::EncodeIndex::Type::FULL_H_E_V_C,
 | ||
|  |             cam_info.frame_width, cam_info.frame_height, cam_info.fps, idx.getType()));
 | ||
|  |           // write the header
 | ||
|  |           auto header = edata.getHeader();
 | ||
|  |           re.writer->write((uint8_t *)header.begin(), header.size(), idx.getTimestampEof()/1000, true, false);
 | ||
|  |         }
 | ||
|  |         re.recording = true;
 | ||
|  |       } else {
 | ||
|  |         // this is a sad case when we aren't recording, but don't have an iframe
 | ||
|  |         // nothing we can do but drop the frame
 | ||
|  |         delete msg;
 | ||
|  |         ++re.dropped_frames;
 | ||
|  |         return bytes_count;
 | ||
|  |       }
 | ||
| 
											4 years ago
										 |     }
 | ||
| 
											3 years ago
										 | 
 | ||
|  |     // we have to be recording if we are here
 | ||
|  |     assert(re.recording);
 | ||
|  | 
 | ||
|  |     // if we are actually writing the video file, do so
 | ||
| 
											4 years ago
										 |     if (re.writer) {
 | ||
|  |       auto data = edata.getData();
 | ||
|  |       re.writer->write((uint8_t *)data.begin(), data.size(), idx.getTimestampEof()/1000, false, flags & V4L2_BUF_FLAG_KEYFRAME);
 | ||
|  |     }
 | ||
|  | 
 | ||
|  |     // put it in log stream as the idx packet
 | ||
|  |     MessageBuilder bmsg;
 | ||
|  |     auto evt = bmsg.initEvent(event.getValid());
 | ||
|  |     evt.setLogMonoTime(event.getLogMonoTime());
 | ||
|  |     if (name == "driverEncodeData") { evt.setDriverEncodeIdx(idx); }
 | ||
|  |     if (name == "wideRoadEncodeData") { evt.setWideRoadEncodeIdx(idx); }
 | ||
|  |     if (name == "qRoadEncodeData") { evt.setQRoadEncodeIdx(idx); }
 | ||
|  |     if (name == "roadEncodeData") { evt.setRoadEncodeIdx(idx); }
 | ||
|  |     auto new_msg = bmsg.toBytes();
 | ||
|  |     logger_log(&s->logger, (uint8_t *)new_msg.begin(), new_msg.size(), true);   // always in qlog?
 | ||
|  |     bytes_count += new_msg.size();
 | ||
|  | 
 | ||
| 
											3 years ago
										 |     // free the message, we used it
 | ||
|  |     delete msg;
 | ||
|  |   } else if (offset_segment_num > s->rotate_segment) {
 | ||
|  |     // encoderd packet has a newer segment, this means encoderd has rolled over
 | ||
|  |     if (!re.marked_ready_to_rotate) {
 | ||
|  |       re.marked_ready_to_rotate = true;
 | ||
|  |       ++s->ready_to_rotate;
 | ||
|  |       LOGD("rotate %d -> %d ready %d/%d for %s",
 | ||
|  |         s->rotate_segment.load(), offset_segment_num,
 | ||
|  |         s->ready_to_rotate.load(), s->max_waiting, name.c_str());
 | ||
|  |     }
 | ||
|  |     // queue up all the new segment messages, they go in after the rotate
 | ||
|  |     re.q.push_back(msg);
 | ||
|  |   } else {
 | ||
|  |     LOGE("%s: encoderd packet has a older segment!!! idx.getSegmentNum():%d s->rotate_segment:%d re.encoderd_segment_offset:%d",
 | ||
|  |       name.c_str(), idx.getSegmentNum(), s->rotate_segment.load(), re.encoderd_segment_offset);
 | ||
|  |     // free the message, it's useless. this should never happen
 | ||
|  |     // actually, this can happen if you restart encoderd
 | ||
|  |     re.encoderd_segment_offset = -s->rotate_segment.load();
 | ||
| 
											4 years ago
										 |     delete msg;
 | ||
|  |   }
 | ||
|  | 
 | ||
|  |   return bytes_count;
 | ||
|  | }
 | ||
|  | 
 | ||
| 
											4 years ago
										 | void loggerd_thread() {
 | ||
| 
											5 years ago
										 |   // setup messaging
 | ||
| 
											5 years ago
										 |   typedef struct QlogState {
 | ||
| 
											4 years ago
										 |     std::string name;
 | ||
| 
											5 years ago
										 |     int counter, freq;
 | ||
| 
											4 years ago
										 |     bool encoder;
 | ||
| 
											5 years ago
										 |   } QlogState;
 | ||
| 
											4 years ago
										 |   std::unordered_map<SubSocket*, QlogState> qlog_states;
 | ||
| 
											4 years ago
										 |   std::unordered_map<SubSocket*, struct RemoteEncoder> remote_encoders;
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											4 years ago
										 |   std::unique_ptr<Context> ctx(Context::create());
 | ||
|  |   std::unique_ptr<Poller> poller(Poller::create());
 | ||
| 
											5 years ago
										 | 
 | ||
|  |   // subscribe to all socks
 | ||
| 
											6 years ago
										 |   for (const auto& it : services) {
 | ||
| 
											4 years ago
										 |     const bool encoder = strcmp(it.name+strlen(it.name)-strlen("EncodeData"), "EncodeData") == 0;
 | ||
| 
											4 years ago
										 |     if (!it.should_log && !encoder) continue;
 | ||
| 
											4 years ago
										 |     LOGD("logging %s (on port %d)", it.name, it.port);
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											4 years ago
										 |     SubSocket * sock = SubSocket::create(ctx.get(), it.name);
 | ||
| 
											5 years ago
										 |     assert(sock != NULL);
 | ||
|  |     poller->registerSocket(sock);
 | ||
| 
											4 years ago
										 |     qlog_states[sock] = {
 | ||
|  |       .name = it.name,
 | ||
|  |       .counter = 0,
 | ||
|  |       .freq = it.decimation,
 | ||
| 
											4 years ago
										 |       .encoder = encoder,
 | ||
| 
											4 years ago
										 |     };
 | ||
| 
											6 years ago
										 |   }
 | ||
|  | 
 | ||
| 
											4 years ago
										 |   LoggerdState s;
 | ||
| 
											5 years ago
										 |   // init logger
 | ||
| 
											4 years ago
										 |   logger_init(&s.logger, true);
 | ||
| 
											4 years ago
										 |   logger_rotate(&s);
 | ||
| 
											4 years ago
										 |   Params().put("CurrentRoute", s.logger.route_name);
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											5 years ago
										 |   // init encoders
 | ||
| 
											4 years ago
										 |   s.last_camera_seen_tms = millis_since_boot();
 | ||
| 
											4 years ago
										 |   for (const auto &cam : cameras_logged) {
 | ||
| 
											3 years ago
										 |     s.max_waiting++;
 | ||
|  |     if (cam.has_qcamera) { s.max_waiting++; }
 | ||
| 
											5 years ago
										 |   }
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											4 years ago
										 |   uint64_t msg_count = 0, bytes_count = 0;
 | ||
|  |   double start_ts = millis_since_boot();
 | ||
| 
											6 years ago
										 |   while (!do_exit) {
 | ||
| 
											5 years ago
										 |     // poll for new messages on all sockets
 | ||
| 
											5 years ago
										 |     for (auto sock : poller->poll(1000)) {
 | ||
| 
											4 years ago
										 |       if (do_exit) break;
 | ||
|  | 
 | ||
| 
											5 years ago
										 |       // drain socket
 | ||
| 
											4 years ago
										 |       int count = 0;
 | ||
| 
											4 years ago
										 |       QlogState &qs = qlog_states[sock];
 | ||
|  |       Message *msg = nullptr;
 | ||
|  |       while (!do_exit && (msg = sock->receive(true))) {
 | ||
|  |         const bool in_qlog = qs.freq != -1 && (qs.counter++ % qs.freq == 0);
 | ||
| 
											4 years ago
										 | 
 | ||
|  |         if (qs.encoder) {
 | ||
| 
											4 years ago
										 |           s.last_camera_seen_tms = millis_since_boot();
 | ||
| 
											4 years ago
										 |           bytes_count += handle_encoder_msg(&s, msg, qs.name, remote_encoders[sock]);
 | ||
|  |         } else {
 | ||
|  |           logger_log(&s.logger, (uint8_t *)msg->getData(), msg->getSize(), in_qlog);
 | ||
|  |           bytes_count += msg->getSize();
 | ||
|  |           delete msg;
 | ||
|  |         }
 | ||
| 
											5 years ago
										 | 
 | ||
| 
											4 years ago
										 |         rotate_if_needed(&s);
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											4 years ago
										 |         if ((++msg_count % 1000) == 0) {
 | ||
|  |           double seconds = (millis_since_boot() - start_ts) / 1000.0;
 | ||
|  |           LOGD("%lu messages, %.2f msg/sec, %.2f KB/sec", msg_count, msg_count / seconds, bytes_count * 0.001 / seconds);
 | ||
| 
											5 years ago
										 |         }
 | ||
| 
											4 years ago
										 | 
 | ||
|  |         count++;
 | ||
| 
											4 years ago
										 |         if (count >= 200) {
 | ||
| 
											4 years ago
										 |           LOGD("large volume of '%s' messages", qs.name.c_str());
 | ||
| 
											4 years ago
										 |           break;
 | ||
|  |         }
 | ||
| 
											5 years ago
										 |       }
 | ||
|  |     }
 | ||
| 
											6 years ago
										 |   }
 | ||
|  | 
 | ||
| 
											5 years ago
										 |   LOGW("closing logger");
 | ||
| 
											4 years ago
										 |   logger_close(&s.logger, &do_exit);
 | ||
| 
											5 years ago
										 | 
 | ||
| 
											4 years ago
										 |   if (do_exit.power_failure) {
 | ||
| 
											5 years ago
										 |     LOGE("power failure");
 | ||
|  |     sync();
 | ||
| 
											4 years ago
										 |     LOGE("sync done");
 | ||
| 
											5 years ago
										 |   }
 | ||
|  | 
 | ||
| 
											5 years ago
										 |   // messaging cleanup
 | ||
| 
											4 years ago
										 |   for (auto &[sock, qs] : qlog_states) delete sock;
 | ||
| 
											6 years ago
										 | }
 | ||
| 
											4 years ago
										 | 
 | ||
|  | int main(int argc, char** argv) {
 | ||
| 
											3 years ago
										 |   if (!Hardware::PC()) {
 | ||
| 
											4 years ago
										 |     int ret;
 | ||
|  |     ret = util::set_core_affinity({0, 1, 2, 3});
 | ||
|  |     assert(ret == 0);
 | ||
|  |     // TODO: why does this impact camerad timings?
 | ||
|  |     //ret = util::set_realtime_priority(1);
 | ||
|  |     //assert(ret == 0);
 | ||
|  |   }
 | ||
|  | 
 | ||
|  |   loggerd_thread();
 | ||
|  | 
 | ||
|  |   return 0;
 | ||
| 
											3 years ago
										 | }
 |