kunlang_video/include/rtmp_manager.hpp

83 lines
2.3 KiB
C++
Raw Normal View History

2025-10-15 15:36:48 +08:00
// rtmp_manager.hpp
2025-10-15 15:03:10 +08:00
#pragma once
#include <gst/gst.h>
2025-10-15 15:01:55 +08:00
#include <algorithm>
#include <atomic>
2025-10-15 08:50:01 +08:00
#include <functional>
2025-10-15 15:33:00 +08:00
#include <future>
2025-10-15 08:57:40 +08:00
#include <memory>
2025-10-15 15:01:55 +08:00
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
2025-10-15 08:50:01 +08:00
#include "app_config.hpp"
2025-10-15 11:27:53 +08:00
#include "mqtt_client_wrapper.hpp"
2025-10-15 15:03:10 +08:00
class RTMPManager
{
2025-10-15 15:01:55 +08:00
public:
2025-10-15 08:50:01 +08:00
enum class StreamResult
{
OK,
PIPELINE_ERROR,
CONNECTION_FAIL,
EOS_RECEIVED,
2025-10-15 14:14:00 +08:00
TIMEOUT,
UNKNOWN
2025-10-15 08:50:01 +08:00
};
struct StreamStatus
{
bool running;
StreamResult last_result;
std::string last_error;
};
2025-10-15 15:01:55 +08:00
struct StreamResultInfo
{
int loc{-1};
std::string url;
int result{1}; // 0 success, 1 fail
std::string reason;
};
2025-10-15 08:50:01 +08:00
using StreamCallback = std::function<void(const std::string &key, StreamStatus status)>;
static void init();
2025-10-15 15:01:55 +08:00
static StreamResultInfo start_camera(const Camera &cam, StreamType type);
static StreamResultInfo stop_camera(const std::string &cam_name, StreamType type);
static void stop_all();
2025-10-14 17:44:59 +08:00
static bool is_streaming(const std::string &cam_name, StreamType type);
static bool is_any_streaming();
static std::string get_stream_url(const std::string &cam_name, StreamType type);
2025-10-15 08:50:01 +08:00
static void set_status_callback(StreamCallback cb);
2025-10-15 15:01:55 +08:00
// Internal helpers
static void update_status(const std::string &key, const StreamStatus &status);
private:
struct StreamContext
{
2025-10-15 08:50:01 +08:00
std::atomic<bool> running{false};
2025-10-15 16:07:36 +08:00
std::atomic<bool> start_result_set{false}; // 新增:保证 promise 只 set 一次
std::thread thread;
2025-10-15 15:33:00 +08:00
std::promise<StreamResultInfo> start_result;
2025-10-15 08:50:01 +08:00
StreamStatus status;
2025-10-15 16:07:36 +08:00
2025-10-15 08:57:40 +08:00
StreamContext() = default;
StreamContext(const StreamContext &) = delete;
StreamContext &operator=(const StreamContext &) = delete;
};
static std::string make_stream_key(const std::string &cam_name, StreamType type);
2025-10-15 14:14:00 +08:00
static GstElement *create_pipeline(const Camera &cam, StreamType type);
2025-10-15 15:36:48 +08:00
static void stream_loop(Camera cam, StreamType type, StreamContext *ctx);
2025-10-15 14:14:00 +08:00
static std::unordered_map<std::string, std::unique_ptr<StreamContext>> streams;
static std::mutex streams_mutex;
static StreamCallback status_callback;
2025-10-15 15:36:48 +08:00
};