RtpOneRoadThread.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #include "RtpOneRoadThread.h"
  2. #include "spdlog.h"
  3. RTPOneRoadThread::RTPOneRoadThread(RecordThreadInfo_t& threadInfo)
  4. : BaseRecordThread(threadInfo),
  5. m_eventLoop()
  6. {
  7. m_logger = spdlog::get("RTPServer");
  8. if(m_logger == nullptr)
  9. {
  10. fmt::print("RTPServer 日志记录器未初始化,请先初始化日志记录器");
  11. return;
  12. }
  13. m_logBase = fmt::format("录音通道: {}:{}", m_threadInfo.cardRoadInfo.strSoundCardName.toStdString(),
  14. m_threadInfo.cardRoadInfo.roadInfo.nRoadNum);
  15. }
  16. RTPOneRoadThread::~RTPOneRoadThread()
  17. {
  18. }
  19. /**
  20. * @brief 停止线程
  21. */
  22. void RTPOneRoadThread::stopThread()
  23. {
  24. if(m_sendTimer.isActive())
  25. {
  26. m_sendTimer.stop();
  27. }
  28. if(m_eventLoop.isRunning())
  29. {
  30. m_eventLoop.quit();
  31. m_eventLoop.processEvents(QEventLoop::AllEvents, 10);
  32. }
  33. while(m_isRunning.load())
  34. {
  35. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  36. }
  37. }
  38. /* 设置数据 */
  39. bool RTPOneRoadThread::setData(const AudioSrcData& srcData)
  40. {
  41. /* UDP会话列表是空的,就不接收数据了 */
  42. if(!m_isRecvData.load())
  43. {
  44. return true;
  45. }
  46. AudioSrcData* data = new AudioSrcData(srcData);
  47. if(data == nullptr)
  48. {
  49. return false;
  50. }
  51. m_ringQueue.push(data);
  52. return false;
  53. }
  54. /* 添加一个UDP会话 */
  55. bool RTPOneRoadThread::addUdpSession(const RtpSendClientInfo_t& udpSession)
  56. {
  57. /* 检查是否已有相同的会话,这里只需要检查IP和端口即可,会话ID和名称在这里没什么用 */
  58. for(const auto& session : m_listClients)
  59. {
  60. if(session.clientIP == udpSession.clientIP && session.clientPort == udpSession.clientPort)
  61. {
  62. SPDLOG_LOGGER_DEBUG(m_logger, "{} 已存在相同的UDP会话: {}:{}", m_logBase, udpSession.clientIP.toStdString(), udpSession.clientPort);
  63. return false;
  64. }
  65. }
  66. SPDLOG_LOGGER_INFO(m_logger, "{} 添加UDP会话: {}:{}", m_logBase, udpSession.clientIP.toStdString(), udpSession.clientPort);
  67. /* 绑定UDP本地端口 */
  68. if(m_localPort < 0)
  69. {
  70. m_udpState = eUDPState::eUDP_Init;
  71. m_localIP = udpSession.localIP;
  72. m_localPort = udpSession.localPort;
  73. }
  74. m_lockUdpSockets.lock();
  75. m_listClients.append(udpSession);
  76. m_lockUdpSockets.unlock();
  77. return true;
  78. }
  79. /* 删除一个会话 */
  80. bool RTPOneRoadThread::removeUdpSession(QString clientIP, quint16 clientPort)
  81. {
  82. std::lock_guard<std::mutex> lock(m_lockUdpSockets);
  83. for(auto it = m_listClients.begin(); it != m_listClients.end(); ++it)
  84. {
  85. if(it->clientIP == clientIP && it->clientPort == clientPort)
  86. {
  87. // if(it->udpSocket != nullptr)
  88. // {
  89. // it->udpSocket->close();
  90. // delete it->udpSocket;
  91. // it->udpSocket = nullptr;
  92. // }
  93. SPDLOG_LOGGER_INFO(m_logger, "{} 删除UDP会话: {}:{}", m_logBase, it->clientIP.toStdString(), it->clientPort);
  94. // 从列表中删除该会话
  95. m_listClients.erase(it);
  96. break;
  97. }
  98. }
  99. /* 如果列表为空,就不再接收数据 */
  100. if(m_listClients.isEmpty())
  101. {
  102. /* 清空环形队列 */
  103. while(m_ringQueue.QueueSize() > 0)
  104. {
  105. auto data = m_ringQueue.front_pop_noBlock();
  106. if(data != nullptr)
  107. {
  108. delete data;
  109. data = nullptr;
  110. }
  111. }
  112. m_udpState = eUDPState::eUDP_Closed;
  113. SPDLOG_LOGGER_DEBUG(m_logger, "{} UDP会话列表为空,不再接收音频原始数据", m_logBase);
  114. }
  115. return true;
  116. }
  117. /* 发送数据的线程函数 */
  118. void RTPOneRoadThread::task()
  119. {
  120. SPDLOG_LOGGER_INFO(m_logger, "➢ {} 开启RTP发送数据线程 ", m_logBase);
  121. if(!initData())
  122. {
  123. SPDLOG_LOGGER_ERROR(m_logger, "{} 初始化数据失败", m_logBase);
  124. return;
  125. }
  126. m_sendTimer.setTimerType(Qt::PreciseTimer);
  127. m_sendTimer.setSingleShot(false); // 设置为循环定时器
  128. m_sendTimer.setInterval(10); // 每10毫秒发送一次数据
  129. QEventLoop::connect(&m_sendTimer, &QTimer::timeout, this, &RTPOneRoadThread::do_timerSendData);
  130. m_sendTimer.start();
  131. m_isRunning.store(true); // 设置为运行状态
  132. /* 将线程控制权交给Qt的事件循环 */
  133. m_eventLoop.exec();
  134. /* 清空数据 */
  135. clearData();
  136. m_isRunning.store(false);
  137. SPDLOG_LOGGER_WARN(m_logger, "➢ {} RTP发送数据线程结束 ", m_logBase);
  138. }
  139. /* 初始化数据 */
  140. bool RTPOneRoadThread::initData()
  141. {
  142. m_listClients.clear();
  143. m_isRecvData.store(false);
  144. m_ringQueue.setQueueCapacity(60);
  145. m_ringQueue.setDefaultValue(nullptr);
  146. return true;
  147. }
  148. /* 清除数据*/
  149. void RTPOneRoadThread::clearData()
  150. {
  151. m_isRecvData.store(false); // 设置为不接收数据状态
  152. /* 清空UDP会话列表 */
  153. std::lock_guard<std::mutex> lock(m_lockUdpSockets);
  154. // for(auto& session : m_listClients)
  155. // {
  156. // if(session.udpSocket != nullptr)
  157. // {
  158. // session.udpSocket->close();
  159. // delete session.udpSocket;
  160. // session.udpSocket = nullptr;
  161. // }
  162. // }
  163. m_listClients.clear();
  164. /* 清空环形队列 */
  165. while(m_ringQueue.QueueSize() > 0)
  166. {
  167. auto data = m_ringQueue.front_pop_noBlock();
  168. if(data != nullptr)
  169. {
  170. delete data;
  171. data = nullptr;
  172. }
  173. }
  174. }
  175. /* 处理UDP状态 */
  176. bool RTPOneRoadThread::processUdpState()
  177. {
  178. if(m_udpSocket == nullptr)
  179. {
  180. m_udpSocket = new QUdpSocket();
  181. if(m_udpSocket == nullptr)
  182. {
  183. SPDLOG_LOGGER_ERROR(m_logger, "{} 创建UDP套接字失败", m_logBase);
  184. return false;
  185. }
  186. m_udpSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); // 设置低延迟选项
  187. connect(m_udpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(do_udpError(QAbstractSocket::SocketError)));
  188. }
  189. if(m_udpState == eUDPState::eUDP_Init)
  190. {
  191. if(!m_udpSocket->bind(QHostAddress(m_localIP)))
  192. {
  193. SPDLOG_LOGGER_ERROR(m_logger, "{} 绑定UDP套接字失败: {}:{}", m_logBase, m_localIP.toStdString(), m_udpSocket->localPort());
  194. return false;
  195. }
  196. SPDLOG_LOGGER_INFO(m_logger, "{} 绑定UDP套接字到本地IP: {}:{}", m_logBase,
  197. m_udpSocket->localAddress().toString().toStdString(), m_udpSocket->localPort());
  198. /* 设置为接收数据状态 */
  199. m_isRecvData.store(true);
  200. m_udpState = eUDPState::eUDP_Opened;
  201. }
  202. else if(m_udpState == eUDPState::eUDP_Closed)
  203. {
  204. /* 关闭接收 */
  205. m_isRecvData.store(false);
  206. /* 关闭UDP占用的本地端口 */
  207. if(m_udpSocket != nullptr)
  208. {
  209. m_udpSocket->close();
  210. }
  211. m_udpState = eUDPState::eUDP_None;
  212. /* 清空连接信息 */
  213. m_listClients.clear();
  214. m_localIP.clear();
  215. m_localPort = -1;
  216. emit signal_udpClosed(m_threadInfo.cardRoadInfo.nSoundCardNum,
  217. m_threadInfo.cardRoadInfo.roadInfo.nRoadNum, m_localPort);
  218. }
  219. return true;
  220. }
  221. /**
  222. * @brief 发送数据,先获取一个缓冲区的数据,获取到后就遍历所有的UDP会话,将这个缓冲区所有的数据都发送出去
  223. * 然后紧接着获取第二个缓冲区的数据,也一起发送出去
  224. *
  225. * @return true
  226. * @return false
  227. */
  228. bool RTPOneRoadThread::sendData()
  229. {
  230. while(m_ringQueue.QueueSize() > 0)
  231. {
  232. // SPDLOG_LOGGER_TRACE(m_logger, "{} 发送音频数据", m_logBase);
  233. auto data = m_ringQueue.front_pop_noBlock();
  234. if(data == nullptr)
  235. {
  236. continue;
  237. }
  238. if(data->isEmpty())
  239. {
  240. delete data;
  241. continue;
  242. }
  243. std::lock_guard<std::mutex> lock(m_lockUdpSockets);
  244. /* 遍历所有的UDP会话,发送数据 */
  245. for(const auto& session : m_listClients)
  246. {
  247. // if(session.udpSocket == nullptr || !session.udpSocket->isValid())
  248. // {
  249. // SPDLOG_LOGGER_WARN(m_logger, "{} 无效的UDP套接字: {}:{}", m_logBase, session.clientIP.toStdString(), session.clientPort);
  250. // continue;
  251. // }
  252. // qint64 bytesSent = session.udpSocket->writeDatagram(data->pData, data->dataSize,
  253. // QHostAddress(session.clientIP), session.clientPort);
  254. qint64 bytesSent = m_udpSocket->writeDatagram(QByteArray(reinterpret_cast<const char*>(data->pData), data->dataSize),
  255. QHostAddress(session.clientIP), session.clientPort);
  256. if(bytesSent == -1)
  257. {
  258. SPDLOG_LOGGER_ERROR(m_logger, "{} 发送数据失败: {}:{}", m_logBase, session.clientIP.toStdString(), session.clientPort);
  259. } else
  260. {
  261. SPDLOG_LOGGER_TRACE(m_logger, "{} 发送数据成功: {}:{}, 本地IP: {}:{}, 大小: {}", m_logBase,
  262. session.clientIP.toStdString(), session.clientPort,
  263. m_udpSocket->localAddress().toString().toStdString(), m_udpSocket->localPort(), bytesSent);
  264. }
  265. }
  266. /* 发送完数据后,删除这个数据 */
  267. delete data;
  268. data = nullptr;
  269. }
  270. return true;
  271. }
  272. /* 定时发送数据 */
  273. void RTPOneRoadThread::do_timerSendData()
  274. {
  275. if(m_udpState == eUDPState::eUDP_None)
  276. {
  277. return;
  278. }
  279. processUdpState();
  280. /* 发送数据 */
  281. sendData();
  282. }
  283. /* UDP错误槽函数 */
  284. void RTPOneRoadThread::do_udpError(QAbstractSocket::SocketError socketError)
  285. {
  286. auto senderSocket = qobject_cast<QUdpSocket*>(sender());
  287. // SPDLOG_LOGGER_ERROR(m_logger, "{} UDP套接字错误: {}", m_logBase, static_cast<int>(socketError));
  288. /* 这里可以根据需要处理不同的错误 */
  289. if(socketError == QAbstractSocket::SocketError::SocketTimeoutError)
  290. {
  291. SPDLOG_LOGGER_WARN(m_logger, "{} UDP连接超时", m_logBase);
  292. } else
  293. {
  294. SPDLOG_LOGGER_ERROR(m_logger, "{} UDP套接字发生错误: {}", m_logBase, static_cast<int>(socketError));
  295. }
  296. /* 获取UDP远程连接的IP和端口 */
  297. if(senderSocket != nullptr)
  298. {
  299. QString remoteIP = senderSocket->peerAddress().toString();
  300. quint16 remotePort = senderSocket->peerPort();
  301. /* 从队列中移除这个会话 */
  302. removeUdpSession(remoteIP, remotePort);
  303. }
  304. }