muxer_stream_muxer.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. #include "muxer_stream_muxer.h"
  2. #include "../base/base_logger.h"
  3. #include <algorithm>
  4. #include <sstream>
  5. #include <regex>
  6. extern "C" {
  7. #include <libavutil/opt.h>
  8. #include <libavutil/time.h>
  9. #include <libavformat/avio.h>
  10. }
  11. namespace av {
  12. namespace muxer {
  13. using namespace av::base;
  14. StreamMuxer::StreamMuxer() {
  15. Logger::info("StreamMuxer created");
  16. }
  17. StreamMuxer::~StreamMuxer() {
  18. close();
  19. Logger::info("StreamMuxer destroyed");
  20. }
  21. ErrorCode StreamMuxer::initialize(const MuxerParams& params) {
  22. if (!validateParams(params)) {
  23. Logger::error("Invalid stream muxer parameters");
  24. return ErrorCode::INVALID_PARAMETER;
  25. }
  26. streamParams_ = static_cast<const StreamMuxerParams&>(params);
  27. // 重置统计信息
  28. connectionStats_ = ConnectionStats{};
  29. // 设置初始状态
  30. setConnectionState(ConnectionState::DISCONNECTED);
  31. Logger::info("StreamMuxer initialized with URL: {}", streamParams_.url);
  32. return AbstractMuxer::initialize(params);
  33. }
  34. ErrorCode StreamMuxer::start() {
  35. if (state_ != MuxerState::INITIALIZED) {
  36. Logger::error("StreamMuxer not initialized");
  37. return ErrorCode::INVALID_STATE;
  38. }
  39. // 建立连接
  40. ErrorCode result = connect();
  41. if (result != ErrorCode::SUCCESS) {
  42. Logger::error("Failed to connect to stream");
  43. return result;
  44. }
  45. // 启动重连线程
  46. if (streamParams_.enableAutoReconnect) {
  47. shouldStopReconnect_ = false;
  48. reconnectThread_ = std::thread(&StreamMuxer::reconnectThreadFunc, this);
  49. }
  50. // 启动自适应码率监控
  51. if (streamParams_.enableAdaptiveBitrate) {
  52. shouldStopBitrateMonitor_ = false;
  53. bitrateMonitorThread_ = std::thread(&StreamMuxer::monitorNetworkCondition, this);
  54. }
  55. return AbstractMuxer::start();
  56. }
  57. ErrorCode StreamMuxer::stop() {
  58. if (state_ != MuxerState::RUNNING) {
  59. return ErrorCode::SUCCESS;
  60. }
  61. // 停止监控线程
  62. shouldStopBitrateMonitor_ = true;
  63. if (bitrateMonitorThread_.joinable()) {
  64. bitrateMonitorThread_.join();
  65. }
  66. // 停止重连线程
  67. shouldStopReconnect_ = true;
  68. reconnectCondition_.notify_all();
  69. if (reconnectThread_.joinable()) {
  70. reconnectThread_.join();
  71. }
  72. // 断开连接
  73. disconnect();
  74. return AbstractMuxer::stop();
  75. }
  76. ErrorCode StreamMuxer::close() {
  77. stop();
  78. // 清理资源
  79. connectionStats_ = ConnectionStats{};
  80. setConnectionState(ConnectionState::DISCONNECTED);
  81. return AbstractMuxer::close();
  82. }
  83. ErrorCode StreamMuxer::writePacket(AVPacket* packet) {
  84. if (!packet) {
  85. return ErrorCode::INVALID_PARAMETER;
  86. }
  87. if (!isConnected()) {
  88. Logger::warning("Not connected, dropping packet");
  89. return ErrorCode::INVALID_STATE;
  90. }
  91. return processPacket(packet);
  92. }
  93. ErrorCode StreamMuxer::writeFrame(AVFrame* frame, int streamIndex) {
  94. if (!frame || streamIndex < 0) {
  95. return ErrorCode::INVALID_PARAMETER;
  96. }
  97. if (!isConnected()) {
  98. Logger::warning("Not connected, dropping frame");
  99. return ErrorCode::INVALID_STATE;
  100. }
  101. // 将帧编码为包
  102. AVPacket* packet = av_packet_alloc();
  103. if (!packet) {
  104. return ErrorCode::OUT_OF_MEMORY;
  105. }
  106. // 这里需要编码器支持,暂时返回成功
  107. av_packet_free(&packet);
  108. return ErrorCode::SUCCESS;
  109. }
  110. ErrorCode StreamMuxer::flush() {
  111. if (!formatContext_) {
  112. return ErrorCode::INVALID_STATE;
  113. }
  114. int ret = av_write_trailer(formatContext_);
  115. if (ret < 0) {
  116. Logger::error("Failed to write trailer: {}", av_err2str(ret));
  117. return ErrorCode::WRITE_ERROR;
  118. }
  119. return ErrorCode::SUCCESS;
  120. }
  121. ErrorCode StreamMuxer::addStream(const StreamInfo& streamInfo) {
  122. ErrorCode result = AbstractMuxer::addStream(streamInfo);
  123. if (result != ErrorCode::SUCCESS) {
  124. return result;
  125. }
  126. Logger::info("Added stream: type={}, codec={}",
  127. static_cast<int>(streamInfo.type), streamInfo.codecName);
  128. return ErrorCode::SUCCESS;
  129. }
  130. ErrorCode StreamMuxer::connect() {
  131. if (connectionState_ == ConnectionState::CONNECTED) {
  132. return ErrorCode::SUCCESS;
  133. }
  134. setConnectionState(ConnectionState::CONNECTING);
  135. ErrorCode result = establishConnection();
  136. if (result == ErrorCode::SUCCESS) {
  137. setConnectionState(ConnectionState::CONNECTED);
  138. connectionStats_.connectTime = std::chrono::steady_clock::now();
  139. connectionStats_.lastDataTime = connectionStats_.connectTime;
  140. Logger::info("Connected to stream: {}", streamParams_.url);
  141. } else {
  142. setConnectionState(ConnectionState::FAILED);
  143. Logger::error("Failed to connect to stream: {}", streamParams_.url);
  144. }
  145. return result;
  146. }
  147. ErrorCode StreamMuxer::disconnect() {
  148. if (connectionState_ == ConnectionState::DISCONNECTED) {
  149. return ErrorCode::SUCCESS;
  150. }
  151. ErrorCode result = closeConnection();
  152. setConnectionState(ConnectionState::DISCONNECTED);
  153. Logger::info("Disconnected from stream");
  154. return result;
  155. }
  156. ErrorCode StreamMuxer::reconnect() {
  157. Logger::info("Attempting to reconnect...");
  158. setConnectionState(ConnectionState::RECONNECTING);
  159. // 先断开现有连接
  160. closeConnection();
  161. // 等待一段时间
  162. std::this_thread::sleep_for(std::chrono::milliseconds(streamParams_.reconnectDelay));
  163. // 重新连接
  164. ErrorCode result = establishConnection();
  165. if (result == ErrorCode::SUCCESS) {
  166. setConnectionState(ConnectionState::CONNECTED);
  167. connectionStats_.reconnectCount++;
  168. connectionStats_.lastReconnectTime = std::chrono::steady_clock::now();
  169. Logger::info("Reconnected successfully");
  170. } else {
  171. setConnectionState(ConnectionState::FAILED);
  172. Logger::error("Reconnection failed");
  173. }
  174. return result;
  175. }
  176. ConnectionState StreamMuxer::getConnectionState() const {
  177. return connectionState_.load();
  178. }
  179. ConnectionStats StreamMuxer::getConnectionStats() const {
  180. std::lock_guard<std::mutex> lock(connectionMutex_);
  181. return connectionStats_;
  182. }
  183. bool StreamMuxer::isConnected() const {
  184. return connectionState_ == ConnectionState::CONNECTED;
  185. }
  186. ErrorCode StreamMuxer::setUrl(const std::string& url) {
  187. if (state_ != MuxerState::IDLE) {
  188. Logger::error("Cannot change URL while muxer is active");
  189. return ErrorCode::INVALID_STATE;
  190. }
  191. if (!validateUrl(url)) {
  192. Logger::error("Invalid URL: {}", url);
  193. return ErrorCode::INVALID_PARAMETER;
  194. }
  195. streamParams_.url = url;
  196. Logger::info("URL set to: {}", url);
  197. return ErrorCode::SUCCESS;
  198. }
  199. std::string StreamMuxer::getUrl() const {
  200. return streamParams_.url;
  201. }
  202. ErrorCode StreamMuxer::enableAdaptiveBitrate(bool enable) {
  203. adaptiveBitrateEnabled_ = enable;
  204. if (enable && state_ == MuxerState::RUNNING && !bitrateMonitorThread_.joinable()) {
  205. shouldStopBitrateMonitor_ = false;
  206. bitrateMonitorThread_ = std::thread(&StreamMuxer::monitorNetworkCondition, this);
  207. }
  208. Logger::info("Adaptive bitrate {}", enable ? "enabled" : "disabled");
  209. return ErrorCode::SUCCESS;
  210. }
  211. ErrorCode StreamMuxer::setBitrateRange(int minBitrate, int maxBitrate) {
  212. if (minBitrate <= 0 || maxBitrate <= minBitrate) {
  213. return ErrorCode::INVALID_PARAMETER;
  214. }
  215. streamParams_.minBitrate = minBitrate;
  216. streamParams_.maxBitrate = maxBitrate;
  217. Logger::info("Bitrate range set: {} - {} bps", minBitrate, maxBitrate);
  218. return ErrorCode::SUCCESS;
  219. }
  220. ErrorCode StreamMuxer::adjustBitrate(double factor) {
  221. if (factor <= 0.0 || factor > 2.0) {
  222. return ErrorCode::INVALID_PARAMETER;
  223. }
  224. int newBitrate = static_cast<int>(currentBitrate_ * factor);
  225. newBitrate = std::clamp(newBitrate, streamParams_.minBitrate, streamParams_.maxBitrate);
  226. if (newBitrate != currentBitrate_) {
  227. currentBitrate_ = newBitrate;
  228. if (bitrateCallback_) {
  229. bitrateCallback_(newBitrate);
  230. }
  231. Logger::info("Bitrate adjusted to: {} bps", newBitrate);
  232. }
  233. return ErrorCode::SUCCESS;
  234. }
  235. ErrorCode StreamMuxer::setProtocolOption(const std::string& key, const std::string& value) {
  236. streamParams_.protocolOptions[key] = value;
  237. Logger::debug("Protocol option set: {}={}", key, value);
  238. return ErrorCode::SUCCESS;
  239. }
  240. std::string StreamMuxer::getProtocolOption(const std::string& key) const {
  241. auto it = streamParams_.protocolOptions.find(key);
  242. return (it != streamParams_.protocolOptions.end()) ? it->second : "";
  243. }
  244. // 内部实现方法
  245. ErrorCode StreamMuxer::setupOutput() {
  246. // 根据协议设置输出格式
  247. const char* formatName = nullptr;
  248. switch (streamParams_.protocol) {
  249. case StreamProtocol::RTMP:
  250. case StreamProtocol::RTMPS:
  251. formatName = "flv";
  252. break;
  253. case StreamProtocol::UDP:
  254. case StreamProtocol::TCP:
  255. formatName = "mpegts";
  256. break;
  257. case StreamProtocol::HTTP:
  258. case StreamProtocol::HTTPS:
  259. formatName = "hls";
  260. break;
  261. case StreamProtocol::SRT:
  262. case StreamProtocol::RIST:
  263. formatName = "mpegts";
  264. break;
  265. default:
  266. formatName = "flv";
  267. break;
  268. }
  269. // 分配格式上下文
  270. int ret = avformat_alloc_output_context2(&formatContext_, nullptr, formatName, streamParams_.url.c_str());
  271. if (ret < 0) {
  272. Logger::error("Failed to allocate output context: {}", av_err2str(ret));
  273. return ErrorCode::INITIALIZATION_FAILED;
  274. }
  275. // 设置协议特定选项
  276. switch (streamParams_.protocol) {
  277. case StreamProtocol::RTMP:
  278. case StreamProtocol::RTMPS:
  279. return setupRTMP();
  280. case StreamProtocol::UDP:
  281. return setupUDP();
  282. case StreamProtocol::TCP:
  283. return setupTCP();
  284. case StreamProtocol::SRT:
  285. return setupSRT();
  286. default:
  287. break;
  288. }
  289. return ErrorCode::SUCCESS;
  290. }
  291. ErrorCode StreamMuxer::writeHeader() {
  292. if (!formatContext_) {
  293. return ErrorCode::INVALID_STATE;
  294. }
  295. // 打开输出
  296. int ret = avio_open(&formatContext_->pb, streamParams_.url.c_str(), AVIO_FLAG_WRITE);
  297. if (ret < 0) {
  298. Logger::error("Failed to open output: {}", av_err2str(ret));
  299. return ErrorCode::WRITE_ERROR;
  300. }
  301. // 写入头部
  302. ret = avformat_write_header(formatContext_, nullptr);
  303. if (ret < 0) {
  304. Logger::error("Failed to write header: {}", av_err2str(ret));
  305. return ErrorCode::WRITE_ERROR;
  306. }
  307. return ErrorCode::SUCCESS;
  308. }
  309. ErrorCode StreamMuxer::writeTrailer() {
  310. if (!formatContext_) {
  311. return ErrorCode::INVALID_STATE;
  312. }
  313. int ret = av_write_trailer(formatContext_);
  314. if (ret < 0) {
  315. Logger::error("Failed to write trailer: {}", av_err2str(ret));
  316. return ErrorCode::WRITE_ERROR;
  317. }
  318. return ErrorCode::SUCCESS;
  319. }
  320. ErrorCode StreamMuxer::establishConnection() {
  321. // 设置输出
  322. ErrorCode result = setupOutput();
  323. if (result != ErrorCode::SUCCESS) {
  324. return result;
  325. }
  326. // 写入头部
  327. result = writeHeader();
  328. if (result != ErrorCode::SUCCESS) {
  329. return result;
  330. }
  331. return ErrorCode::SUCCESS;
  332. }
  333. ErrorCode StreamMuxer::closeConnection() {
  334. if (formatContext_ && formatContext_->pb) {
  335. // 写入尾部
  336. writeTrailer();
  337. // 关闭输出
  338. avio_closep(&formatContext_->pb);
  339. }
  340. return ErrorCode::SUCCESS;
  341. }
  342. ErrorCode StreamMuxer::setupRTMP() {
  343. if (!formatContext_) {
  344. return ErrorCode::INVALID_STATE;
  345. }
  346. // 设置RTMP选项
  347. AVDictionary* options = nullptr;
  348. // 连接超时
  349. av_dict_set_int(&options, "timeout", streamParams_.connectTimeout * 1000, 0);
  350. // 直播模式
  351. if (streamParams_.rtmpLive) {
  352. av_dict_set(&options, "live", "1", 0);
  353. }
  354. // 缓冲区大小
  355. av_dict_set_int(&options, "buffer_size", streamParams_.sendBufferSize, 0);
  356. // 应用协议选项
  357. for (const auto& option : streamParams_.protocolOptions) {
  358. av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
  359. }
  360. formatContext_->metadata = options;
  361. Logger::debug("RTMP setup completed");
  362. return ErrorCode::SUCCESS;
  363. }
  364. ErrorCode StreamMuxer::setupUDP() {
  365. if (!formatContext_) {
  366. return ErrorCode::INVALID_STATE;
  367. }
  368. // 设置UDP选项
  369. AVDictionary* options = nullptr;
  370. // 缓冲区大小
  371. av_dict_set_int(&options, "buffer_size", streamParams_.sendBufferSize, 0);
  372. // 重用地址
  373. if (streamParams_.reuseAddress) {
  374. av_dict_set(&options, "reuse", "1", 0);
  375. }
  376. // 本地地址和端口
  377. if (!streamParams_.localAddress.empty()) {
  378. av_dict_set(&options, "localaddr", streamParams_.localAddress.c_str(), 0);
  379. }
  380. if (streamParams_.localPort > 0) {
  381. av_dict_set_int(&options, "localport", streamParams_.localPort, 0);
  382. }
  383. // 应用协议选项
  384. for (const auto& option : streamParams_.protocolOptions) {
  385. av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
  386. }
  387. formatContext_->metadata = options;
  388. Logger::debug("UDP setup completed");
  389. return ErrorCode::SUCCESS;
  390. }
  391. ErrorCode StreamMuxer::setupTCP() {
  392. if (!formatContext_) {
  393. return ErrorCode::INVALID_STATE;
  394. }
  395. // 设置TCP选项
  396. AVDictionary* options = nullptr;
  397. // 连接超时
  398. av_dict_set_int(&options, "timeout", streamParams_.connectTimeout * 1000, 0);
  399. // 缓冲区大小
  400. av_dict_set_int(&options, "buffer_size", streamParams_.sendBufferSize, 0);
  401. // 应用协议选项
  402. for (const auto& option : streamParams_.protocolOptions) {
  403. av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
  404. }
  405. formatContext_->metadata = options;
  406. Logger::debug("TCP setup completed");
  407. return ErrorCode::SUCCESS;
  408. }
  409. ErrorCode StreamMuxer::setupSRT() {
  410. if (!formatContext_) {
  411. return ErrorCode::INVALID_STATE;
  412. }
  413. // 设置SRT选项
  414. AVDictionary* options = nullptr;
  415. // 延迟
  416. av_dict_set_int(&options, "latency", streamParams_.srtLatency * 1000, 0);
  417. // 密码
  418. if (!streamParams_.srtPassphrase.empty()) {
  419. av_dict_set(&options, "passphrase", streamParams_.srtPassphrase.c_str(), 0);
  420. }
  421. // 应用协议选项
  422. for (const auto& option : streamParams_.protocolOptions) {
  423. av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
  424. }
  425. formatContext_->metadata = options;
  426. Logger::debug("SRT setup completed");
  427. return ErrorCode::SUCCESS;
  428. }
  429. ErrorCode StreamMuxer::processPacket(AVPacket* packet) {
  430. if (!packet || !formatContext_) {
  431. return ErrorCode::INVALID_PARAMETER;
  432. }
  433. // 发送包
  434. ErrorCode result = sendPacket(packet);
  435. if (result == ErrorCode::SUCCESS) {
  436. // 更新统计信息
  437. updateConnectionStats();
  438. updateBandwidthStats(packet->size);
  439. // 更新包统计
  440. stats_.totalPackets++;
  441. stats_.totalBytes += packet->size;
  442. connectionStats_.packetsSent++;
  443. connectionStats_.bytesSent += packet->size;
  444. connectionStats_.lastDataTime = std::chrono::steady_clock::now();
  445. } else {
  446. stats_.errorCount++;
  447. Logger::warning("Failed to send packet");
  448. }
  449. return result;
  450. }
  451. ErrorCode StreamMuxer::sendPacket(AVPacket* packet) {
  452. if (!packet || !formatContext_) {
  453. return ErrorCode::INVALID_PARAMETER;
  454. }
  455. int ret = av_interleaved_write_frame(formatContext_, packet);
  456. if (ret < 0) {
  457. Logger::error("Failed to write packet: {}", av_err2str(ret));
  458. return ErrorCode::WRITE_ERROR;
  459. }
  460. return ErrorCode::SUCCESS;
  461. }
  462. void StreamMuxer::monitorNetworkCondition() {
  463. Logger::debug("Network condition monitoring started");
  464. while (!shouldStopBitrateMonitor_) {
  465. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  466. if (adaptiveBitrateEnabled_ && isConnected()) {
  467. adjustBitrateBasedOnCondition();
  468. }
  469. }
  470. Logger::debug("Network condition monitoring stopped");
  471. }
  472. void StreamMuxer::adjustBitrateBasedOnCondition() {
  473. // 获取当前网络状态
  474. double currentBandwidth = connectionStats_.currentBandwidth;
  475. double rtt = connectionStats_.rtt;
  476. // 简单的自适应算法
  477. double targetUtilization = 0.8; // 目标带宽利用率
  478. double currentUtilization = (currentBitrate_ > 0) ? (currentBandwidth / currentBitrate_) : 0.0;
  479. if (currentUtilization < targetUtilization * 0.7) {
  480. // 网络状况良好,可以提高码率
  481. adjustBitrate(1.1);
  482. } else if (currentUtilization > targetUtilization * 1.2 || rtt > 200.0) {
  483. // 网络拥塞,降低码率
  484. adjustBitrate(streamParams_.bitrateAdjustFactor);
  485. }
  486. }
  487. void StreamMuxer::reconnectThreadFunc() {
  488. Logger::debug("Reconnect thread started");
  489. int attemptCount = 0;
  490. while (!shouldStopReconnect_) {
  491. std::unique_lock<std::mutex> lock(reconnectMutex_);
  492. // 等待重连请求或停止信号
  493. reconnectCondition_.wait(lock, [this] {
  494. return shouldStopReconnect_ || reconnectRequested_ || shouldReconnect();
  495. });
  496. if (shouldStopReconnect_) {
  497. break;
  498. }
  499. if (shouldReconnect() && attemptCount < streamParams_.maxReconnectAttempts) {
  500. attemptCount++;
  501. Logger::info("Reconnect attempt {}/{}", attemptCount, streamParams_.maxReconnectAttempts);
  502. lock.unlock();
  503. // 计算重连延迟
  504. int delay = calculateReconnectDelay(attemptCount);
  505. std::this_thread::sleep_for(std::chrono::milliseconds(delay));
  506. // 尝试重连
  507. if (reconnect() == ErrorCode::SUCCESS) {
  508. attemptCount = 0; // 重连成功,重置计数
  509. }
  510. lock.lock();
  511. }
  512. reconnectRequested_ = false;
  513. }
  514. Logger::debug("Reconnect thread stopped");
  515. }
  516. bool StreamMuxer::shouldReconnect() const {
  517. ConnectionState state = connectionState_.load();
  518. return (state == ConnectionState::FAILED || state == ConnectionState::DISCONNECTED) &&
  519. streamParams_.enableAutoReconnect;
  520. }
  521. int StreamMuxer::calculateReconnectDelay(int attempt) const {
  522. double delay = streamParams_.reconnectDelay;
  523. for (int i = 1; i < attempt; ++i) {
  524. delay *= streamParams_.reconnectBackoffFactor;
  525. }
  526. return static_cast<int>(std::min(delay, 30000.0)); // 最大30秒
  527. }
  528. void StreamMuxer::updateConnectionStats() {
  529. auto now = std::chrono::steady_clock::now();
  530. // 更新统计信息的时间间隔检查
  531. if (std::chrono::duration<double>(now - lastStatsUpdate_).count() < STATS_UPDATE_INTERVAL) {
  532. return;
  533. }
  534. std::lock_guard<std::mutex> lock(connectionMutex_);
  535. // 计算平均带宽
  536. double totalBandwidth = 0.0;
  537. int validSamples = 0;
  538. for (int i = 0; i < 10; ++i) {
  539. if (bandwidthSamples_[i] > 0) {
  540. totalBandwidth += bandwidthSamples_[i];
  541. validSamples++;
  542. }
  543. }
  544. if (validSamples > 0) {
  545. connectionStats_.averageBandwidth = totalBandwidth / validSamples;
  546. }
  547. lastStatsUpdate_ = now;
  548. }
  549. void StreamMuxer::updateBandwidthStats(size_t bytes) {
  550. auto now = std::chrono::steady_clock::now();
  551. // 更新带宽统计的时间间隔检查
  552. if (std::chrono::duration<double>(now - lastBandwidthUpdate_).count() < BANDWIDTH_UPDATE_INTERVAL) {
  553. return;
  554. }
  555. std::lock_guard<std::mutex> lock(connectionMutex_);
  556. // 计算当前带宽
  557. double timeDiff = std::chrono::duration<double>(now - lastBandwidthUpdate_).count();
  558. if (timeDiff > 0) {
  559. uint64_t bytesDiff = connectionStats_.bytesSent - lastBytesSent_;
  560. double bandwidth = (bytesDiff * 8.0) / timeDiff; // bps
  561. // 更新带宽采样
  562. bandwidthSamples_[bandwidthSampleIndex_] = bandwidth;
  563. bandwidthSampleIndex_ = (bandwidthSampleIndex_ + 1) % 10;
  564. connectionStats_.currentBandwidth = bandwidth;
  565. lastBytesSent_ = connectionStats_.bytesSent;
  566. }
  567. lastBandwidthUpdate_ = now;
  568. }
  569. void StreamMuxer::setConnectionState(ConnectionState state) {
  570. ConnectionState oldState = connectionState_.exchange(state);
  571. if (oldState != state) {
  572. onConnectionStateChanged(state);
  573. }
  574. }
  575. void StreamMuxer::onConnectionStateChanged(ConnectionState state) {
  576. Logger::info("Connection state changed to: {}", static_cast<int>(state));
  577. if (connectionCallback_) {
  578. connectionCallback_(state);
  579. }
  580. // 根据状态变化触发相应操作
  581. if (state == ConnectionState::FAILED && streamParams_.enableAutoReconnect) {
  582. reconnectRequested_ = true;
  583. reconnectCondition_.notify_one();
  584. }
  585. }
  586. bool StreamMuxer::validateParams(const MuxerParams& params) {
  587. if (!AbstractMuxer::validateParams(params)) {
  588. return false;
  589. }
  590. const StreamMuxerParams& streamParams = static_cast<const StreamMuxerParams&>(params);
  591. // 验证URL
  592. if (!validateUrl(streamParams.url)) {
  593. Logger::error("Invalid URL: {}", streamParams.url);
  594. return false;
  595. }
  596. // 验证超时参数
  597. if (streamParams.connectTimeout <= 0 || streamParams.sendTimeout <= 0) {
  598. Logger::error("Invalid timeout parameters");
  599. return false;
  600. }
  601. // 验证重连参数
  602. if (streamParams.maxReconnectAttempts < 0 || streamParams.reconnectDelay < 0) {
  603. Logger::error("Invalid reconnect parameters");
  604. return false;
  605. }
  606. // 验证码率参数
  607. if (streamParams.minBitrate <= 0 || streamParams.maxBitrate <= streamParams.minBitrate) {
  608. Logger::error("Invalid bitrate parameters");
  609. return false;
  610. }
  611. return true;
  612. }
  613. bool StreamMuxer::validateUrl(const std::string& url) const {
  614. if (url.empty()) {
  615. return false;
  616. }
  617. // 简单的URL格式验证
  618. std::regex urlPattern(R"(^(rtmp|rtmps|udp|tcp|http|https|srt|rist)://.*)");
  619. return std::regex_match(url, urlPattern);
  620. }
  621. // 工厂类实现
  622. std::unique_ptr<AbstractMuxer> StreamMuxer::StreamMuxerFactory::createMuxer(MuxerType type) {
  623. if (type == MuxerType::STREAM_MUXER) {
  624. return std::make_unique<StreamMuxer>();
  625. }
  626. return nullptr;
  627. }
  628. bool StreamMuxer::StreamMuxerFactory::isTypeSupported(MuxerType type) const {
  629. return type == MuxerType::STREAM_MUXER;
  630. }
  631. std::vector<MuxerType> StreamMuxer::StreamMuxerFactory::getSupportedTypes() const {
  632. return {MuxerType::STREAM_MUXER};
  633. }
  634. std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createRTMPMuxer(const std::string& url) {
  635. auto muxer = std::make_unique<StreamMuxer>();
  636. StreamMuxerParams params;
  637. params.protocol = StreamProtocol::RTMP;
  638. params.url = url;
  639. params.rtmpLive = true;
  640. if (muxer->initialize(params) == ErrorCode::SUCCESS) {
  641. return muxer;
  642. }
  643. return nullptr;
  644. }
  645. std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createUDPMuxer(const std::string& address, int port) {
  646. auto muxer = std::make_unique<StreamMuxer>();
  647. StreamMuxerParams params;
  648. params.protocol = StreamProtocol::UDP;
  649. params.url = "udp://" + address + ":" + std::to_string(port);
  650. if (muxer->initialize(params) == ErrorCode::SUCCESS) {
  651. return muxer;
  652. }
  653. return nullptr;
  654. }
  655. std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createTCPMuxer(const std::string& address, int port) {
  656. auto muxer = std::make_unique<StreamMuxer>();
  657. StreamMuxerParams params;
  658. params.protocol = StreamProtocol::TCP;
  659. params.url = "tcp://" + address + ":" + std::to_string(port);
  660. if (muxer->initialize(params) == ErrorCode::SUCCESS) {
  661. return muxer;
  662. }
  663. return nullptr;
  664. }
  665. std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createSRTMuxer(const std::string& url) {
  666. auto muxer = std::make_unique<StreamMuxer>();
  667. StreamMuxerParams params;
  668. params.protocol = StreamProtocol::SRT;
  669. params.url = url;
  670. if (muxer->initialize(params) == ErrorCode::SUCCESS) {
  671. return muxer;
  672. }
  673. return nullptr;
  674. }
  675. } // namespace muxer
  676. } // namespace av