sweeper_video/src/rtmp_manager.cpp

430 lines
14 KiB
C++
Raw Normal View History

2025-11-12 17:47:56 +08:00
// rtmp_manager.cpp
#include "rtmp_manager.hpp"
2025-10-15 14:14:00 +08:00
2025-10-16 13:11:36 +08:00
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netinet/in.h>
2025-10-16 14:37:47 +08:00
#include <sys/stat.h>
2025-10-16 13:11:36 +08:00
2025-10-16 10:25:51 +08:00
#include <chrono>
2025-10-16 13:11:36 +08:00
#include <cstring>
2026-01-20 13:47:30 +08:00
#include <memory>
2025-10-16 10:25:51 +08:00
#include <thread>
2025-10-15 10:18:02 +08:00
2026-01-20 13:47:30 +08:00
std::atomic<bool> RTMPManager::g_live_enabled{false};
2025-12-29 14:24:40 +08:00
// =======================================================
// 工具函数
// =======================================================
2025-11-12 17:47:56 +08:00
static bool device_exists(const std::string& path)
2025-10-17 15:52:47 +08:00
{
struct stat st;
2025-12-29 14:24:40 +08:00
return stat(path.c_str(), &st) == 0;
2025-10-17 15:52:47 +08:00
}
2025-12-29 14:24:40 +08:00
// 获取指定网卡 IPv4
2025-12-29 14:26:42 +08:00
std::string get_ip_address(const std::string& ifname)
2025-10-16 13:11:36 +08:00
{
2025-12-29 14:24:40 +08:00
struct ifaddrs* ifaddr = nullptr;
if (getifaddrs(&ifaddr) != 0) return "";
2025-10-16 13:11:36 +08:00
2025-12-29 14:24:40 +08:00
char ip[INET_ADDRSTRLEN] = {0};
for (auto* ifa = ifaddr; ifa; ifa = ifa->ifa_next)
2025-10-16 13:11:36 +08:00
{
2025-12-29 14:24:40 +08:00
if (!ifa->ifa_addr) continue;
2025-10-16 13:11:36 +08:00
if (ifa->ifa_addr->sa_family == AF_INET && ifname == ifa->ifa_name)
{
2025-12-29 14:24:40 +08:00
auto* addr = &reinterpret_cast<sockaddr_in*>(ifa->ifa_addr)->sin_addr;
inet_ntop(AF_INET, addr, ip, sizeof(ip));
break;
2025-10-16 13:11:36 +08:00
}
}
freeifaddrs(ifaddr);
2025-12-29 14:24:40 +08:00
return ip;
2025-10-16 13:11:36 +08:00
}
2025-12-29 14:24:40 +08:00
// =======================================================
// 静态成员
// =======================================================
2025-10-15 08:57:40 +08:00
std::unordered_map<std::string, std::unique_ptr<RTMPManager::StreamContext>> RTMPManager::streams;
std::mutex RTMPManager::streams_mutex;
2025-12-29 14:24:40 +08:00
// =======================================================
// 初始化
// =======================================================
void RTMPManager::init()
{
gst_init(nullptr, nullptr);
2025-12-29 14:24:40 +08:00
LOG_INFO("[RTMP] GStreamer initialized");
}
2025-11-12 17:47:56 +08:00
std::string RTMPManager::make_key(const std::string& name) { return name + "_main"; }
2025-10-15 08:50:01 +08:00
2025-12-29 14:24:40 +08:00
// =======================================================
// 创建推流管线(稳定版)
// =======================================================
2025-11-12 17:47:56 +08:00
GstElement* RTMPManager::create_pipeline(const Camera& cam)
2025-10-16 10:25:51 +08:00
{
2025-12-29 14:24:40 +08:00
const std::string stream = cam.name + "_main";
2025-10-17 17:31:06 +08:00
const std::string app = "camera";
2025-11-12 18:10:16 +08:00
2025-12-29 14:24:40 +08:00
const std::string live_rtmp = "rtmp://36.153.162.171:19435/" + app + "/" + stream + "?vhost=live";
2026-01-20 13:47:30 +08:00
const std::string record_rtmp = "rtmp://127.0.0.1:2935/" + app + "/" + stream + "?vhost=record";
2025-12-29 14:36:48 +08:00
std::string pipeline_str = "v4l2src name=src device=" + cam.device +
2025-12-29 14:13:37 +08:00
" io-mode=dmabuf "
2026-01-20 14:14:50 +08:00
"! video/x-raw,format=NV12,width=1920,height=1080,framerate=" +
2025-12-29 15:09:37 +08:00
std::to_string(cam.fps) +
"/1 "
"! videoscale "
2026-01-20 13:47:30 +08:00
"! video/x-raw,width=" +
2025-12-29 14:36:48 +08:00
std::to_string(cam.width) + ",height=" + std::to_string(cam.height) +
2026-01-20 14:14:50 +08:00
" ! queue max-size-buffers=2 leaky=downstream "
"! mpph264enc rc-mode=cbr bps=" +
std::to_string(cam.bitrate) + " gop=" + std::to_string(cam.fps) +
" header-mode=each-idr profile=baseline "
2025-12-29 14:24:40 +08:00
"! h264parse config-interval=1 "
2026-01-20 13:47:30 +08:00
"! tee name=t "
2026-01-20 14:14:50 +08:00
// ========= 录像(永远启用)============
"t. ! queue max-size-buffers=8 leaky=downstream "
"! flvmux name=rec_mux streamable=true "
"! rtmpsink name=rec_sink location=\"" +
2026-01-20 13:47:30 +08:00
record_rtmp +
2026-01-20 14:14:50 +08:00
"\" sync=false async=false drop-on-latency=true "
2026-01-20 13:47:30 +08:00
2026-01-20 14:14:50 +08:00
// ========= livevalve 控制)===========
"t. ! queue max-size-buffers=8 leaky=downstream "
2026-01-20 13:47:30 +08:00
"! valve name=live_valve drop=true "
2026-01-20 14:14:50 +08:00
"! queue max-size-buffers=8 leaky=downstream "
"! flvmux name=live_mux streamable=true "
"! rtmpsink name=live_sink location=\"" +
live_rtmp + "\" sync=false async=false drop-on-latency=true ";
GError* err = nullptr;
GstElement* pipeline = gst_parse_launch(pipeline_str.c_str(), &err);
if (err)
2025-10-16 10:25:51 +08:00
{
2026-01-20 14:14:50 +08:00
LOG_ERROR("[RTMP] Pipeline creation failed: " + std::string(err->message));
g_error_free(err);
2025-10-16 10:25:51 +08:00
return nullptr;
2025-10-15 17:01:43 +08:00
}
2025-12-29 14:24:40 +08:00
2025-10-16 10:25:51 +08:00
return pipeline;
}
2025-12-29 14:24:40 +08:00
// =======================================================
// 主推流线程
// =======================================================
2025-11-12 17:47:56 +08:00
void RTMPManager::stream_loop(Camera cam, StreamContext* ctx)
2025-10-16 10:25:51 +08:00
{
2025-10-17 16:27:04 +08:00
const std::string key = make_key(cam.name);
2025-11-12 17:57:20 +08:00
2025-11-24 10:07:27 +08:00
while (ctx->thread_running)
2025-10-17 13:36:22 +08:00
{
2025-12-29 14:24:40 +08:00
// 1. 设备存在性
if (!device_exists(cam.device))
2025-10-17 13:36:22 +08:00
{
2025-12-29 14:24:40 +08:00
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
ctx->status.running = false;
ctx->status.last_error = "Device not found: " + cam.device;
}
LOG_WARN("[RTMP] " + key + " - device not found");
2025-10-17 15:26:08 +08:00
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
2025-10-17 13:36:22 +08:00
}
2025-12-29 14:24:40 +08:00
// 2. 创建 pipeline
2025-11-12 17:47:56 +08:00
GstElement* pipeline = create_pipeline(cam);
2025-10-17 15:26:08 +08:00
if (!pipeline)
2025-10-17 13:36:22 +08:00
{
2025-12-29 14:24:40 +08:00
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
ctx->status.running = false;
ctx->status.last_error = "Pipeline creation failed";
}
2025-10-17 15:26:08 +08:00
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
2025-10-17 13:36:22 +08:00
}
2025-10-17 16:14:20 +08:00
2026-01-20 13:47:30 +08:00
// 2.1 获取 live_valve用于 MQTT 控制)
GstElement* live_valve = gst_bin_get_by_name(GST_BIN(pipeline), "live_valve");
if (!live_valve)
{
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
ctx->status.running = false;
ctx->status.last_error = "live_valve not found";
}
LOG_ERROR("[RTMP] " + key + " - live_valve not found");
gst_object_unref(pipeline);
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
}
// 保存到 ctx
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
if (ctx->live_valve) gst_object_unref(ctx->live_valve);
ctx->live_valve = live_valve; // ⚠️ live_valve 引用交给 ctx 管理
}
g_object_set(G_OBJECT(ctx->live_valve), "drop", g_live_enabled.load() ? FALSE : TRUE, nullptr);
2025-12-29 14:24:40 +08:00
GstBus* bus = gst_element_get_bus(pipeline);
2025-10-17 16:14:20 +08:00
2025-10-17 15:58:54 +08:00
LOG_INFO("[RTMP] Starting stream: " + key);
2025-10-17 16:27:04 +08:00
gst_element_set_state(pipeline, GST_STATE_PLAYING);
2025-10-17 15:38:19 +08:00
2025-12-29 14:24:40 +08:00
// 3. 等待进入 PLAYING
GstState state = GST_STATE_NULL;
if (gst_element_get_state(pipeline, &state, nullptr, 5 * GST_SECOND) == GST_STATE_CHANGE_SUCCESS &&
2025-11-12 17:57:20 +08:00
state == GST_STATE_PLAYING)
2025-10-17 16:10:02 +08:00
{
2025-11-24 10:07:27 +08:00
std::lock_guard<std::mutex> lk(ctx->status_mutex);
2025-11-12 17:57:20 +08:00
ctx->status.running = true;
ctx->status.last_error.clear();
LOG_INFO("[RTMP] " + key + " confirmed PLAYING");
}
else
{
2025-11-24 10:07:27 +08:00
std::lock_guard<std::mutex> lk(ctx->status_mutex);
2025-11-12 17:57:20 +08:00
ctx->status.running = false;
2025-12-29 14:24:40 +08:00
ctx->status.last_error = "Failed to reach PLAYING";
LOG_ERROR("[RTMP] " + key + " failed to PLAY");
goto cleanup;
2025-10-17 16:10:02 +08:00
}
2025-12-29 14:24:40 +08:00
// 4. 正常运行:只监听 ERROR / EOS
2025-11-24 10:07:27 +08:00
while (ctx->thread_running)
2025-10-17 15:52:47 +08:00
{
2025-12-29 14:24:40 +08:00
GstMessage* msg = gst_bus_timed_pop_filtered(
bus, 300 * GST_MSECOND, static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_EOS));
if (!msg)
2025-10-17 16:27:04 +08:00
{
2025-12-29 14:24:40 +08:00
// 心跳pipeline 没死就认为在跑
2025-11-24 10:07:27 +08:00
std::lock_guard<std::mutex> lk(ctx->status_mutex);
2025-10-17 16:27:04 +08:00
ctx->status.running = true;
2025-12-29 14:24:40 +08:00
continue;
2025-10-17 15:52:47 +08:00
}
2025-10-16 10:52:51 +08:00
2025-12-29 14:24:40 +08:00
if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_ERROR)
2025-10-17 08:45:21 +08:00
{
2025-12-29 14:24:40 +08:00
GError* err = nullptr;
gst_message_parse_error(msg, &err, nullptr);
2025-10-17 08:45:21 +08:00
{
2025-11-24 10:07:27 +08:00
std::lock_guard<std::mutex> lk(ctx->status_mutex);
2025-10-17 15:26:08 +08:00
ctx->status.running = false;
2025-12-29 14:24:40 +08:00
ctx->status.last_error = err ? err->message : "Unknown GStreamer error";
2025-10-17 08:45:21 +08:00
}
2025-12-29 14:24:40 +08:00
LOG_ERROR("[RTMP] " + key + " ERROR: " + (err ? err->message : "unknown"));
if (err) g_error_free(err);
gst_message_unref(msg);
break;
}
if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS)
{
2025-11-24 10:07:27 +08:00
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
2025-10-17 15:26:08 +08:00
ctx->status.running = false;
2025-12-29 14:24:40 +08:00
ctx->status.last_error = "EOS";
2025-11-24 10:07:27 +08:00
}
2025-12-29 14:24:40 +08:00
LOG_WARN("[RTMP] " + key + " EOS");
gst_message_unref(msg);
break;
2025-10-17 08:45:21 +08:00
}
2025-10-17 16:27:04 +08:00
2025-12-29 14:24:40 +08:00
gst_message_unref(msg);
2025-10-16 10:52:51 +08:00
}
2025-10-16 11:21:18 +08:00
2025-12-29 14:24:40 +08:00
cleanup:
2026-01-20 13:47:30 +08:00
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
if (ctx->live_valve)
{
gst_object_unref(ctx->live_valve);
ctx->live_valve = nullptr;
}
}
2025-10-17 15:26:08 +08:00
gst_element_set_state(pipeline, GST_STATE_NULL);
2025-10-17 15:58:54 +08:00
if (bus) gst_object_unref(bus);
2025-10-17 15:26:08 +08:00
gst_object_unref(pipeline);
2025-10-16 12:53:41 +08:00
2025-11-24 10:07:27 +08:00
if (ctx->thread_running)
2025-10-17 08:45:21 +08:00
{
2025-10-17 16:27:04 +08:00
LOG_WARN("[RTMP] Restarting " + key + " in 3s...");
2025-12-29 14:24:40 +08:00
std::this_thread::sleep_for(std::chrono::seconds(3));
2025-10-17 08:45:21 +08:00
}
2025-10-16 10:52:51 +08:00
}
2025-11-24 10:07:27 +08:00
{
std::lock_guard<std::mutex> lk(ctx->status_mutex);
ctx->status.running = false;
}
2025-10-17 15:58:54 +08:00
LOG_INFO("[RTMP] Stream thread exited for " + key);
2025-10-16 10:52:51 +08:00
}
2025-12-29 14:24:40 +08:00
// =======================================================
// 启停管理
// =======================================================
2025-10-17 15:58:54 +08:00
void RTMPManager::start_all()
2025-10-16 10:25:51 +08:00
{
2025-12-29 14:24:40 +08:00
LOG_INFO("[RTMP] Starting enabled streams...");
2025-10-16 10:25:51 +08:00
std::lock_guard<std::mutex> lock(streams_mutex);
2025-10-17 15:58:54 +08:00
int delay_ms = 0;
for (const auto& cam : g_app_config.cameras)
2025-10-17 15:58:54 +08:00
{
if (!cam.enabled)
{
LOG_INFO("[RTMP] Skip disabled camera: " + cam.name);
continue;
}
2025-12-29 14:24:40 +08:00
const auto key = make_key(cam.name);
if (streams.count(key)) continue;
2025-10-17 15:58:54 +08:00
auto ctx = std::make_unique<StreamContext>();
2025-11-24 10:07:27 +08:00
ctx->thread_running.store(true);
2025-10-17 15:58:54 +08:00
ctx->thread = std::thread(
[cam, ptr = ctx.get(), delay_ms]()
{
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
stream_loop(cam, ptr);
});
streams.emplace(key, std::move(ctx));
delay_ms += 200;
2025-10-17 15:58:54 +08:00
}
2025-10-16 10:25:51 +08:00
}
2025-10-17 16:00:35 +08:00
void RTMPManager::stop_all()
{
std::lock_guard<std::mutex> lock(streams_mutex);
2026-01-20 13:47:30 +08:00
for (auto& kv : streams)
{
kv.second->thread_running.store(false);
std::lock_guard<std::mutex> lk(kv.second->status_mutex);
if (kv.second->live_valve)
{
gst_object_unref(kv.second->live_valve);
kv.second->live_valve = nullptr;
}
}
2025-12-29 14:24:40 +08:00
2025-11-12 17:47:56 +08:00
for (auto& kv : streams)
2025-10-17 16:00:35 +08:00
if (kv.second->thread.joinable()) kv.second->thread.join();
2025-12-29 14:24:40 +08:00
2025-10-17 16:00:35 +08:00
streams.clear();
}
2025-12-29 14:24:40 +08:00
// =======================================================
// 状态 & URL
// =======================================================
2025-11-12 17:47:56 +08:00
bool RTMPManager::is_streaming(const std::string& cam_name)
2025-10-17 16:00:35 +08:00
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(make_key(cam_name));
2025-11-24 10:07:27 +08:00
if (it == streams.end()) return false;
2025-12-29 14:24:40 +08:00
std::lock_guard<std::mutex> lk(it->second->status_mutex);
return it->second->status.running;
2025-10-17 16:00:35 +08:00
}
2025-11-12 17:47:56 +08:00
std::string RTMPManager::get_stream_url(const std::string& cam_name)
2025-10-16 10:25:51 +08:00
{
2025-10-16 13:11:36 +08:00
std::string ip = get_ip_address("enP2p33s0");
2026-01-07 17:00:02 +08:00
if (ip.empty()) ip = "192.168.4.194";
2025-12-29 14:24:40 +08:00
return "http://" + ip + ":11985/rtc/v1/whep/?app=camera&stream=" + cam_name + "_main&vhost=live";
2025-10-16 10:25:51 +08:00
}
2025-12-29 14:24:40 +08:00
// =======================================================
// 汇总状态
// =======================================================
2025-10-17 15:52:47 +08:00
std::vector<RTMPManager::ChannelInfo> RTMPManager::get_all_channels_status()
2025-10-17 13:36:22 +08:00
{
2025-10-17 15:52:47 +08:00
std::vector<ChannelInfo> result;
2025-10-17 15:26:08 +08:00
std::lock_guard<std::mutex> lock(streams_mutex);
2025-10-17 15:52:47 +08:00
for (size_t i = 0; i < g_app_config.cameras.size(); ++i)
{
2025-11-12 17:47:56 +08:00
const auto& cam = g_app_config.cameras[i];
2025-12-29 14:24:40 +08:00
ChannelInfo ch{};
2025-10-17 15:52:47 +08:00
ch.loc = static_cast<int>(i);
if (!cam.enabled)
{
2025-12-29 14:24:40 +08:00
ch.running = false;
ch.reason = "Disabled by config";
result.push_back(ch);
continue;
}
2025-10-17 15:52:47 +08:00
2025-12-29 14:24:40 +08:00
auto it = streams.find(make_key(cam.name));
2025-10-17 15:52:47 +08:00
if (it != streams.end())
{
2025-12-29 14:24:40 +08:00
std::lock_guard<std::mutex> lk(it->second->status_mutex);
ch.running = it->second->status.running;
ch.reason = it->second->status.last_error;
if (ch.running) ch.url = get_stream_url(cam.name);
2025-10-17 15:52:47 +08:00
}
else
{
2025-12-29 14:24:40 +08:00
ch.running = false;
ch.reason = "Not started";
}
2025-10-17 15:52:47 +08:00
result.push_back(ch);
}
2025-10-17 15:26:08 +08:00
return result;
2025-10-17 13:36:22 +08:00
}
2026-01-20 13:47:30 +08:00
void RTMPManager::set_live_enabled_all(bool enable)
{
std::lock_guard<std::mutex> lock(streams_mutex);
g_live_enabled.store(enable);
for (auto& kv : streams)
{
auto* ctx = kv.second.get();
std::lock_guard<std::mutex> lk(ctx->status_mutex);
if (!ctx->live_valve) continue;
// enable=true → drop=false放行 live
g_object_set(G_OBJECT(ctx->live_valve), "drop", enable ? FALSE : TRUE, nullptr);
}
LOG_INFO(std::string("[RTMP] Live ") + (enable ? "ENABLED" : "DISABLED") + " for all streams");
}
void RTMPManager::set_live_enabled(const std::string& cam_name, bool enable)
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(make_key(cam_name));
if (it == streams.end()) return;
auto* ctx = it->second.get();
std::lock_guard<std::mutex> lk(ctx->status_mutex);
if (!ctx->live_valve) return;
g_object_set(G_OBJECT(ctx->live_valve), "drop", enable ? FALSE : TRUE, nullptr);
LOG_INFO("[RTMP] Live " + std::string(enable ? "ENABLED" : "DISABLED") + " for " + cam_name);
}