00001 #include "RealCameraSynchronizer.hpp" 00002 00003 namespace virtual_camera { 00004 00005 00006 RealCameraSynchronizer::RealCameraSynchronizer(bool synchronize, 00007 const MutexPtr & syncMutex) { 00008 this->setSynchronization(synchronize); 00009 this->syncMutex = syncMutex; 00010 this->recentCount = 0; 00011 this->mostRecentStamp = ros::Time(0); 00012 this->cameraCount = 0; 00013 } 00014 00015 00016 void RealCameraSynchronizer::setSynchronization(bool mode) { 00017 this->synchronize = mode; 00018 } 00019 00020 00021 bool RealCameraSynchronizer::isSynchronized() { 00022 return this->synchronize; 00023 } 00024 00025 00026 void RealCameraSynchronizer::addCamera(const std::string & topic, 00027 const RealCameraPtr & camera, 00028 const boost::shared_ptr<image_transport::ImageTransport> & it) { 00029 boost::mutex::scoped_lock lock(*(this->syncMutex)); 00030 this->realCamImgSubs.push_back( 00031 it->subscribe(topic, 00032 1, &RealCameraSynchronizer::generalCallback, 00033 this)); 00034 this->camsByFrame[camera->getName()] = camera; 00035 this->cameraCount++; 00036 } 00037 00038 00039 void RealCameraSynchronizer::generalCallback( 00040 const sensor_msgs::ImageConstPtr & image) { 00041 const std::string & camId = image->header.frame_id; 00042 if (this->synchronize) { 00043 this->handleSynchronization(image); 00044 } else { 00045 this->camsByFrame.find(camId)->second->updateImage(image); 00046 } 00047 } 00048 00049 00050 void RealCameraSynchronizer::handleSynchronization( 00051 const sensor_msgs::ImageConstPtr & image) { 00052 boost::mutex::scoped_lock lock(*(this->syncMutex)); 00053 const ros::Time & stamp = image->header.stamp; 00054 this->msgsByFrame[image->header.frame_id] = image; 00055 if (this->mostRecentStamp > ros::Time::now()) { 00056 //because of bag files 00057 this->mostRecentStamp = ros::Time::now(); 00058 } 00059 if (stamp > this->mostRecentStamp) { 00060 this->mostRecentStamp = stamp; 00061 this->recentCount = 1; 00062 }else if (stamp == this->mostRecentStamp) { 00063 this->recentCount++; 00064 if (this->recentCount == this->cameraCount) { 00065 this->pushMessages(); 00066 } 00067 } 00068 } 00069 00070 00071 void RealCameraSynchronizer::pushMessages() { 00072 std::map<std::string, sensor_msgs::ImageConstPtr>::iterator msgIt = 00073 this->msgsByFrame.begin(); 00074 std::map<std::string, RealCameraPtr>::iterator camIt = 00075 this->camsByFrame.begin(); 00076 //taking advantage of the ordering of the maps and the fact that 00077 //both have the same keys. 00078 while (msgIt != this->msgsByFrame.end()) { 00079 camIt->second->updateImage(msgIt->second); 00080 ++camIt; 00081 ++msgIt; 00082 } 00083 } 00084 00085 } 00086 00087