kunlang_video/src/rtmp_manager.cpp

376 lines
12 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 <net/if.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>
2025-10-16 10:25:51 +08:00
#include <thread>
2025-10-15 10:18:02 +08:00
2025-10-17 15:52:47 +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;
return (stat(path.c_str(), &st) == 0);
}
2025-10-17 15:26:08 +08:00
// 动态获取指定网卡 IPv4 地址
2025-11-12 17:47:56 +08:00
static std::string get_ip_address(const std::string& ifname)
2025-10-16 13:11:36 +08:00
{
struct ifaddrs *ifaddr, *ifa;
char ip[INET_ADDRSTRLEN] = {0};
if (getifaddrs(&ifaddr) == -1)
{
perror("getifaddrs");
return "";
}
for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == nullptr) continue;
if (ifa->ifa_addr->sa_family == AF_INET && ifname == ifa->ifa_name)
{
2025-11-12 17:47:56 +08:00
void* addr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
2025-10-16 13:11:36 +08:00
if (inet_ntop(AF_INET, addr, ip, sizeof(ip)))
{
freeifaddrs(ifaddr);
return ip;
}
}
}
freeifaddrs(ifaddr);
2025-10-17 15:52:47 +08:00
return "";
2025-10-16 13:11:36 +08:00
}
2025-10-17 15:52:47 +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-10-17 15:52:47 +08:00
// ========== 初始化 ==========
void RTMPManager::init()
{
gst_init(nullptr, nullptr);
2025-10-16 10:25:51 +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-10-17 15:52:47 +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-10-17 16:27:04 +08:00
const int width = cam.width;
const int height = cam.height;
const int fps = cam.fps;
const int bitrate = cam.bitrate;
const std::string stream_name = cam.name + "_main";
2025-10-17 17:31:06 +08:00
const std::string app = "camera";
const std::string location = "rtmp://127.0.0.1:1935/" + app + "/" + stream_name + "?vhost=live";
2025-10-17 16:27:04 +08:00
std::string pipeline_str = "v4l2src name=src device=" + cam.device +
2025-11-12 17:47:56 +08:00
" ! "
"video/x-raw,format=NV12,width=" +
std::to_string(width) + ",height=" + std::to_string(height) +
2025-10-17 16:27:04 +08:00
",framerate=" + std::to_string(fps) +
2025-11-12 17:47:56 +08:00
"/1 ! "
"tee name=t "
2025-11-12 17:53:56 +08:00
// 主分支:编码 + RTMP 推流
"t. ! queue ! "
2025-11-12 17:47:56 +08:00
"mpph264enc bps=" +
2025-10-17 16:27:04 +08:00
std::to_string(bitrate) + " gop=" + std::to_string(fps) +
2025-11-12 17:53:56 +08:00
" ! "
2025-11-12 17:47:56 +08:00
"h264parse ! flvmux streamable=true name=mux "
2025-11-12 17:53:56 +08:00
// 静音音频轨道(避免 RTMP 播放器报错)
"audiotestsrc wave=silence ! audioconvert ! audioresample ! "
"voaacenc ! aacparse ! mux. "
// 输出 RTMP
"mux. ! rtmpsink name=sink location=\"" +
2025-10-17 16:27:04 +08:00
location +
2025-11-12 17:53:56 +08:00
"\" sync=false "
// 第二分支:预留 (AI 分析/录制)
2025-10-17 16:27:04 +08:00
"t. ! queue ! fakesink sync=false";
2025-10-15 15:33:00 +08:00
2025-11-12 17:47:56 +08:00
GError* error = nullptr;
GstElement* pipeline = gst_parse_launch(pipeline_str.c_str(), &error);
2025-10-16 10:25:51 +08:00
if (error)
{
2025-10-17 16:27:04 +08:00
LOG_ERROR(std::string("[RTMP] Pipeline creation failed: ") + error->message);
2025-10-16 10:25:51 +08:00
g_error_free(error);
return nullptr;
2025-10-15 17:01:43 +08:00
}
2025-10-16 10:25:51 +08:00
return pipeline;
}
2025-10-17 15:52:47 +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-10-17 15:26:08 +08:00
while (ctx->running)
2025-10-17 13:36:22 +08:00
{
2025-10-17 16:27:04 +08:00
// 设备是否存在
struct stat st{};
if (stat(cam.device.c_str(), &st) != 0)
2025-10-17 13:36:22 +08:00
{
2025-10-17 15:26:08 +08:00
ctx->status.running = false;
ctx->status.last_error = "Device not found: " + cam.device;
LOG_WARN("[RTMP] " + key + " - " + ctx->status.last_error);
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
2025-10-17 13:36:22 +08:00
}
2025-10-17 16:27:04 +08:00
// 创建管线
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-10-17 15:26:08 +08:00
ctx->status.running = false;
2025-10-17 15:58:54 +08:00
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
gst_element_set_name(pipeline, key.c_str());
2025-11-12 17:47:56 +08:00
GstBus* bus = gst_element_get_bus(pipeline);
2025-10-17 16:14:20 +08:00
2025-10-17 16:27:04 +08:00
// 在 videoconvert 的 src pad 上挂 probe 判断是否有帧流过
2025-10-17 16:14:20 +08:00
bool got_frame = false;
{
2025-11-12 17:47:56 +08:00
GstElement* vc = gst_bin_get_by_name(GST_BIN(pipeline), "vc");
2025-10-17 16:27:04 +08:00
if (vc)
{
2025-11-12 17:47:56 +08:00
GstPad* pad = gst_element_get_static_pad(vc, "src");
2025-10-17 16:27:04 +08:00
if (pad)
{
gst_pad_add_probe(
pad, GST_PAD_PROBE_TYPE_BUFFER,
2025-11-12 17:47:56 +08:00
[](GstPad*, GstPadProbeInfo*, gpointer user_data) -> GstPadProbeReturn
2025-10-17 16:27:04 +08:00
{
2025-11-12 17:47:56 +08:00
*static_cast<bool*>(user_data) = true;
2025-10-17 16:27:04 +08:00
return GST_PAD_PROBE_OK;
},
&got_frame, nullptr);
gst_object_unref(pad);
}
else
{
LOG_WARN("[RTMP] " + key + " - vc has no src pad?");
}
gst_object_unref(vc);
}
else
2025-10-17 16:14:20 +08:00
{
2025-10-17 16:27:04 +08:00
LOG_WARN("[RTMP] " + key + " - cannot find element 'vc' for pad-probe");
2025-10-17 16:14:20 +08:00
}
}
2025-10-17 16:27:04 +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-10-17 16:27:04 +08:00
// 等待进入 PLAYING最长 5s
2025-10-17 16:10:02 +08:00
bool confirmed_running = false;
{
2025-10-17 16:27:04 +08:00
GstState state = GST_STATE_NULL, pending = GST_STATE_NULL;
// 注意第三个参数单位是纳秒5s=5*GST_SECOND
if (gst_element_get_state(pipeline, &state, &pending, 5 * GST_SECOND) == GST_STATE_CHANGE_SUCCESS &&
state == GST_STATE_PLAYING)
2025-10-17 16:10:02 +08:00
{
2025-10-17 16:27:04 +08:00
confirmed_running = true;
2025-10-17 16:10:02 +08:00
ctx->status.running = true;
ctx->status.last_error.clear();
2025-10-17 16:27:04 +08:00
LOG_INFO("[RTMP] " + key + " confirmed PLAYING");
2025-10-17 16:10:02 +08:00
}
else
{
ctx->status.running = false;
ctx->status.last_error = "Pipeline failed to confirm PLAYING";
LOG_WARN("[RTMP] " + key + " - " + ctx->status.last_error);
}
}
if (!confirmed_running)
{
gst_element_set_state(pipeline, GST_STATE_NULL);
if (bus) gst_object_unref(bus);
gst_object_unref(pipeline);
std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_BASE_DELAY_MS));
continue;
}
2025-10-17 16:27:04 +08:00
// 运行中5s 内必须看到帧,否则认定无信号重启
const auto start_t = std::chrono::steady_clock::now();
bool need_restart = false;
2025-10-17 15:58:54 +08:00
while (ctx->running)
2025-10-17 15:52:47 +08:00
{
2025-10-17 16:27:04 +08:00
// 先检查帧
if (!got_frame)
2025-10-17 15:52:47 +08:00
{
2025-10-17 16:27:04 +08:00
auto elapsed =
std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start_t)
.count();
if (elapsed > 5)
{
ctx->status.running = false;
ctx->status.last_error = "No frames detected (no video signal)";
LOG_ERROR("[RTMP] " + key + " - " + ctx->status.last_error);
need_restart = true;
break;
}
}
else
{
// 一旦有帧,保持 running=true
ctx->status.running = true;
ctx->status.last_error.clear();
2025-10-17 15:52:47 +08:00
}
2025-10-16 10:52:51 +08:00
2025-10-17 16:27:04 +08:00
// 监听错误/EOS
2025-11-12 17:47:56 +08:00
GstMessage* msg = gst_bus_timed_pop_filtered(bus, 200 * GST_MSECOND,
2025-10-17 16:27:04 +08:00
(GstMessageType)(GST_MESSAGE_ERROR | GST_MESSAGE_EOS));
2025-10-17 15:26:08 +08:00
if (!msg) continue;
2025-10-16 11:21:18 +08:00
2025-10-17 15:26:08 +08:00
switch (GST_MESSAGE_TYPE(msg))
2025-10-17 08:45:21 +08:00
{
2025-10-17 15:26:08 +08:00
case GST_MESSAGE_ERROR:
2025-10-17 08:45:21 +08:00
{
2025-11-12 17:47:56 +08:00
GError* err = nullptr;
2025-10-17 15:26:08 +08:00
gst_message_parse_error(msg, &err, nullptr);
ctx->status.running = false;
2025-10-17 16:27:04 +08:00
ctx->status.last_error = err ? err->message : "GStreamer error";
2025-10-17 15:26:08 +08:00
LOG_ERROR("[RTMP] " + key + " stream error: " + ctx->status.last_error);
if (err) g_error_free(err);
need_restart = true;
break;
2025-10-17 08:45:21 +08:00
}
2025-10-17 15:26:08 +08:00
case GST_MESSAGE_EOS:
ctx->status.running = false;
2025-10-17 15:58:54 +08:00
ctx->status.last_error = "End of stream (EOS)";
LOG_WARN("[RTMP] " + key + " reached EOS");
2025-10-17 15:26:08 +08:00
need_restart = true;
break;
default:
break;
2025-10-17 08:45:21 +08:00
}
2025-10-17 15:38:19 +08:00
gst_message_unref(msg);
2025-10-17 16:27:04 +08:00
2025-10-17 15:26:08 +08:00
if (need_restart) break;
2025-10-16 10:52:51 +08:00
}
2025-10-16 11:21:18 +08:00
2025-10-17 16:27:04 +08:00
// 收尾
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-10-17 15:26:08 +08:00
if (ctx->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-10-17 15:26:08 +08:00
std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_BASE_DELAY_MS));
2025-10-17 08:45:21 +08:00
}
2025-10-16 10:52:51 +08:00
}
2025-10-17 15:26:08 +08:00
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-10-17 15:52:47 +08:00
// ========== 启停与状态 ==========
2025-10-17 15:58:54 +08:00
void RTMPManager::start_all()
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:58:54 +08:00
LOG_INFO("[RTMP] Starting all record 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;
2025-11-12 17:47:56 +08:00
for (auto& cam : g_app_config.cameras)
2025-10-17 15:58:54 +08:00
{
auto key = make_key(cam.name);
if (streams.find(key) != streams.end())
{
LOG_INFO("[RTMP] Stream already running: " + key);
continue;
}
auto ctx = std::make_unique<StreamContext>();
ctx->running.store(true);
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; // 每路错开 200ms
}
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);
2025-11-12 17:47:56 +08:00
for (auto& kv : streams) kv.second->running.store(false);
for (auto& kv : streams)
2025-10-17 16:00:35 +08:00
if (kv.second->thread.joinable()) kv.second->thread.join();
streams.clear();
}
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));
return (it != streams.end() && it->second->status.running);
}
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");
2025-10-17 17:42:09 +08:00
if (ip.empty()) ip = "127.0.0.1";
return "http://" + ip + ":1985/rtc/v1/whep/?app=camera&stream=" + cam_name + "_main&vhost=live";
2025-10-16 10:25:51 +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-10-17 15:52:47 +08:00
auto key = make_key(cam.name);
ChannelInfo ch;
ch.loc = static_cast<int>(i);
ch.url.clear();
ch.running = false;
ch.reason = "Not started";
auto it = streams.find(key);
if (it != streams.end())
{
2025-11-12 17:47:56 +08:00
auto& status = it->second->status;
2025-10-17 15:52:47 +08:00
ch.running = status.running;
if (status.running)
{
ch.url = get_stream_url(cam.name);
ch.reason.clear();
}
else
{
ch.reason = status.last_error.empty() ? "Unknown error" : status.last_error;
}
}
else
{
ch.reason = "Context missing";
}
result.push_back(ch);
}
2025-10-17 15:26:08 +08:00
return result;
2025-10-17 13:36:22 +08:00
}