RtpOneRoadThread.cpp 10 KB

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