muxer_stream_muxer.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #ifndef AV_MUXER_STREAM_MUXER_H
  2. #define AV_MUXER_STREAM_MUXER_H
  3. #include "muxer_abstract_muxer.h"
  4. #include <string>
  5. #include <memory>
  6. #include <thread>
  7. #include <queue>
  8. #include <condition_variable>
  9. #include <atomic>
  10. #include <chrono>
  11. extern "C" {
  12. #include <libavformat/avformat.h>
  13. #include <libavcodec/avcodec.h>
  14. #include <libavutil/avutil.h>
  15. }
  16. namespace av {
  17. namespace muxer {
  18. // 流协议类型
  19. enum class StreamProtocol {
  20. RTMP = 0, // RTMP协议
  21. RTMPS, // RTMPS协议
  22. UDP, // UDP协议
  23. TCP, // TCP协议
  24. HTTP, // HTTP协议
  25. HTTPS, // HTTPS协议
  26. SRT, // SRT协议
  27. RIST // RIST协议
  28. };
  29. // 连接状态
  30. enum class ConnectionState {
  31. DISCONNECTED = 0, // 未连接
  32. CONNECTING, // 连接中
  33. CONNECTED, // 已连接
  34. RECONNECTING, // 重连中
  35. FAILED // 连接失败
  36. };
  37. // 流复用器参数
  38. struct StreamMuxerParams : public MuxerParams {
  39. StreamProtocol protocol = StreamProtocol::RTMP;
  40. std::string url; // 推流URL
  41. // 连接参数
  42. int connectTimeout = 5000; // 连接超时(毫秒)
  43. int sendTimeout = 5000; // 发送超时(毫秒)
  44. int receiveTimeout = 5000; // 接收超时(毫秒)
  45. // 重连参数
  46. bool enableAutoReconnect = true; // 启用自动重连
  47. int maxReconnectAttempts = 5; // 最大重连次数
  48. int reconnectDelay = 2000; // 重连延迟(毫秒)
  49. double reconnectBackoffFactor = 1.5; // 重连退避因子
  50. // 缓冲参数
  51. int sendBufferSize = 1024 * 1024; // 发送缓冲区大小
  52. int receiveBufferSize = 1024 * 1024; // 接收缓冲区大小
  53. // 质量控制
  54. bool enableAdaptiveBitrate = false; // 启用自适应码率
  55. int minBitrate = 500000; // 最小码率(bps)
  56. int maxBitrate = 5000000; // 最大码率(bps)
  57. double bitrateAdjustFactor = 0.8; // 码率调整因子
  58. // 协议特定参数
  59. std::map<std::string, std::string> protocolOptions; // 协议选项
  60. // RTMP特定参数
  61. std::string rtmpApp; // RTMP应用名
  62. std::string rtmpStreamKey; // RTMP流密钥
  63. bool rtmpLive = true; // RTMP直播模式
  64. // UDP/TCP特定参数
  65. std::string localAddress; // 本地地址
  66. int localPort = 0; // 本地端口
  67. bool reuseAddress = true; // 重用地址
  68. // SRT特定参数
  69. int srtLatency = 120; // SRT延迟(毫秒)
  70. std::string srtPassphrase; // SRT密码
  71. StreamMuxerParams() : MuxerParams(MuxerType::STREAM_MUXER) {}
  72. };
  73. // 连接统计信息
  74. struct ConnectionStats {
  75. ConnectionState state = ConnectionState::DISCONNECTED;
  76. std::chrono::steady_clock::time_point connectTime;
  77. std::chrono::steady_clock::time_point lastDataTime;
  78. // 网络统计
  79. uint64_t bytesSent = 0; // 已发送字节数
  80. uint64_t bytesReceived = 0; // 已接收字节数
  81. uint64_t packetsSent = 0; // 已发送包数
  82. uint64_t packetsLost = 0; // 丢失包数
  83. // 性能统计
  84. double currentBandwidth = 0.0; // 当前带宽(bps)
  85. double averageBandwidth = 0.0; // 平均带宽(bps)
  86. double rtt = 0.0; // 往返时间(毫秒)
  87. double jitter = 0.0; // 抖动(毫秒)
  88. // 重连统计
  89. int reconnectCount = 0; // 重连次数
  90. std::chrono::steady_clock::time_point lastReconnectTime;
  91. };
  92. // 流复用器类
  93. class StreamMuxer : public AbstractMuxer {
  94. public:
  95. StreamMuxer();
  96. ~StreamMuxer() override;
  97. // 基础接口实现
  98. ErrorCode initialize(const MuxerParams& params) override;
  99. ErrorCode start() override;
  100. ErrorCode stop() override;
  101. ErrorCode close() override;
  102. // 写入接口实现
  103. ErrorCode writePacket(AVPacket* packet) override;
  104. ErrorCode writeFrame(AVFrame* frame, int streamIndex) override;
  105. ErrorCode flush() override;
  106. // 流管理实现
  107. ErrorCode addStream(const StreamInfo& streamInfo) override;
  108. // 连接管理
  109. ErrorCode connect();
  110. ErrorCode disconnect();
  111. ErrorCode reconnect();
  112. // 状态查询
  113. ConnectionState getConnectionState() const;
  114. ConnectionStats getConnectionStats() const;
  115. bool isConnected() const;
  116. // 流特定接口
  117. ErrorCode setUrl(const std::string& url);
  118. std::string getUrl() const;
  119. // 自适应码率控制
  120. ErrorCode enableAdaptiveBitrate(bool enable);
  121. ErrorCode setBitrateRange(int minBitrate, int maxBitrate);
  122. ErrorCode adjustBitrate(double factor);
  123. // 协议选项
  124. ErrorCode setProtocolOption(const std::string& key, const std::string& value);
  125. std::string getProtocolOption(const std::string& key) const;
  126. // 回调设置
  127. using ConnectionCallback = std::function<void(ConnectionState)>;
  128. using BitrateCallback = std::function<void(int)>; // 新码率
  129. void setConnectionCallback(ConnectionCallback callback) { connectionCallback_ = callback; }
  130. void setBitrateCallback(BitrateCallback callback) { bitrateCallback_ = callback; }
  131. // 工厂类
  132. class StreamMuxerFactory : public MuxerFactory {
  133. public:
  134. std::unique_ptr<AbstractMuxer> createMuxer(MuxerType type) override;
  135. bool isTypeSupported(MuxerType type) const override;
  136. std::vector<MuxerType> getSupportedTypes() const override;
  137. // 流复用器特定方法
  138. static std::unique_ptr<StreamMuxer> createRTMPMuxer(const std::string& url);
  139. static std::unique_ptr<StreamMuxer> createUDPMuxer(const std::string& address, int port);
  140. static std::unique_ptr<StreamMuxer> createTCPMuxer(const std::string& address, int port);
  141. static std::unique_ptr<StreamMuxer> createSRTMuxer(const std::string& url);
  142. };
  143. protected:
  144. // 内部实现方法
  145. ErrorCode setupOutput() override;
  146. ErrorCode writeHeader() override;
  147. ErrorCode writeTrailer() override;
  148. // 连接管理
  149. ErrorCode establishConnection();
  150. ErrorCode closeConnection();
  151. // 协议特定设置
  152. ErrorCode setupRTMP();
  153. ErrorCode setupUDP();
  154. ErrorCode setupTCP();
  155. ErrorCode setupSRT();
  156. // 包处理
  157. ErrorCode processPacket(AVPacket* packet);
  158. ErrorCode sendPacket(AVPacket* packet);
  159. // 自适应码率
  160. void monitorNetworkCondition();
  161. void adjustBitrateBasedOnCondition();
  162. // 重连逻辑
  163. void reconnectThreadFunc();
  164. bool shouldReconnect() const;
  165. int calculateReconnectDelay(int attempt) const;
  166. // 统计更新
  167. void updateConnectionStats();
  168. void updateBandwidthStats(size_t bytes);
  169. // 状态管理
  170. void setConnectionState(ConnectionState state);
  171. void onConnectionStateChanged(ConnectionState state);
  172. // 参数验证
  173. bool validateParams(const MuxerParams& params) override;
  174. bool validateUrl(const std::string& url) const;
  175. private:
  176. StreamMuxerParams streamParams_;
  177. // 连接状态
  178. std::atomic<ConnectionState> connectionState_{ConnectionState::DISCONNECTED};
  179. ConnectionStats connectionStats_;
  180. mutable std::mutex connectionMutex_;
  181. // 重连控制
  182. std::thread reconnectThread_;
  183. std::atomic<bool> shouldStopReconnect_{false};
  184. std::atomic<bool> reconnectRequested_{false};
  185. std::condition_variable reconnectCondition_;
  186. std::mutex reconnectMutex_;
  187. // 自适应码率
  188. std::atomic<bool> adaptiveBitrateEnabled_{false};
  189. std::atomic<int> currentBitrate_{0};
  190. std::thread bitrateMonitorThread_;
  191. std::atomic<bool> shouldStopBitrateMonitor_{false};
  192. // 网络监控
  193. std::chrono::steady_clock::time_point lastBandwidthUpdate_;
  194. uint64_t lastBytesSent_ = 0;
  195. double bandwidthSamples_[10] = {0}; // 带宽采样窗口
  196. int bandwidthSampleIndex_ = 0;
  197. // 回调函数
  198. ConnectionCallback connectionCallback_;
  199. BitrateCallback bitrateCallback_;
  200. // 性能监控
  201. std::chrono::steady_clock::time_point lastStatsUpdate_;
  202. static constexpr double STATS_UPDATE_INTERVAL = 1.0; // 统计更新间隔(秒)
  203. static constexpr double BANDWIDTH_UPDATE_INTERVAL = 0.5; // 带宽更新间隔(秒)
  204. };
  205. } // namespace muxer
  206. } // namespace av
  207. #endif // AV_MUXER_STREAM_MUXER_H