kunlang_video/src/rtmp_manager.cpp

238 lines
7.6 KiB
C++
Raw Normal View History

2025-10-16 10:25:51 +08:00
// rtsp_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:26:08 +08:00
// 动态获取指定网卡 IPv4 地址
2025-10-16 13:11:36 +08:00
static std::string get_ip_address(const std::string &ifname)
{
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)
{
void *addr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
if (inet_ntop(AF_INET, addr, ip, sizeof(ip)))
{
freeifaddrs(ifaddr);
return ip;
}
}
}
freeifaddrs(ifaddr);
return ""; // 没找到
}
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:26:08 +08:00
static bool device_exists(const std::string &path)
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:26:08 +08:00
struct stat st;
return (stat(path.c_str(), &st) == 0);
2025-10-16 10:25:51 +08:00
}
void RTMPManager::init()
{
gst_init(nullptr, nullptr);
2025-10-16 10:25:51 +08:00
LOG_INFO("[RTMP] GStreamer initialized.");
}
2025-10-17 15:26:08 +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:26:08 +08:00
GstElement *RTMPManager::create_pipeline(const Camera &cam)
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:26:08 +08:00
int width = cam.width;
int height = cam.height;
int fps = cam.fps;
int bitrate = cam.bitrate;
2025-10-17 15:26:08 +08:00
std::string stream_name = cam.name + "_main";
std::string app = "record";
2025-10-17 13:36:22 +08:00
2025-10-17 15:26:08 +08:00
std::string location = "rtmp://127.0.0.1:1935/" + app + "/" + stream_name + "?vhost=" + app;
2025-10-16 17:11:40 +08:00
2025-10-16 17:58:38 +08:00
std::string pipeline_str = "v4l2src device=" + cam.device + " ! video/x-raw,width=" + std::to_string(width) +
2025-10-16 10:25:51 +08:00
",height=" + std::to_string(height) + ",framerate=" + std::to_string(fps) +
2025-10-17 15:26:08 +08:00
"/1 ! videoconvert ! video/x-raw,format=NV12 "
2025-10-16 10:25:51 +08:00
"! mpph264enc bps=" +
std::to_string(bitrate) + " gop=" + std::to_string(fps) +
2025-10-17 15:26:08 +08:00
" ! h264parse ! flvmux name=mux streamable=true "
2025-10-16 17:58:38 +08:00
"audiotestsrc wave=silence ! audioconvert ! audioresample ! voaacenc ! aacparse ! mux. "
2025-10-17 15:26:08 +08:00
"mux. ! rtmpsink location=\"" +
2025-10-17 14:05:04 +08:00
location + "\" sync=false";
2025-10-15 16:21:25 +08:00
2025-10-17 15:26:08 +08:00
LOG_INFO("[RTMP] Pipeline: " + pipeline_str);
2025-10-15 15:33:00 +08:00
2025-10-16 10:25:51 +08:00
GError *error = nullptr;
GstElement *pipeline = gst_parse_launch(pipeline_str.c_str(), &error);
if (error)
{
2025-10-17 15:26:08 +08:00
LOG_ERROR("[RTMP] Pipeline creation failed: " + std::string(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:26:08 +08:00
void RTMPManager::stream_loop(Camera cam, StreamContext *ctx)
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:26:08 +08:00
std::string key = make_key(cam.name);
2025-10-17 13:36:22 +08:00
2025-10-17 15:26:08 +08:00
while (ctx->running)
2025-10-17 13:36:22 +08:00
{
2025-10-17 15:26:08 +08:00
if (!device_exists(cam.device))
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 15:26:08 +08:00
GstElement *pipeline = create_pipeline(cam);
if (!pipeline)
2025-10-17 13:36:22 +08:00
{
2025-10-17 15:26:08 +08:00
ctx->status.running = false;
ctx->status.last_error = "Failed to create pipeline";
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
2025-10-17 13:36:22 +08:00
}
2025-10-16 10:52:51 +08:00
2025-10-17 15:26:08 +08:00
GstBus *bus = gst_element_get_bus(pipeline);
gst_element_set_state(pipeline, GST_STATE_PLAYING);
2025-10-17 15:38:19 +08:00
// -------- 等待状态切换结果 --------
GstStateChangeReturn ret = gst_element_get_state(pipeline, nullptr, nullptr, 3 * GST_SECOND);
if (ret != GST_STATE_CHANGE_SUCCESS)
{
ctx->status.running = false;
ctx->status.last_error = "Pipeline failed to reach PLAYING";
LOG_ERROR("[RTMP] " + key + " failed to start (no video signal?)");
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(bus);
gst_object_unref(pipeline);
std::this_thread::sleep_for(std::chrono::seconds(3));
continue;
}
2025-10-17 15:26:08 +08:00
ctx->status.running = true;
ctx->status.last_error.clear();
LOG_INFO("[RTMP] Started stream for " + key);
2025-10-16 10:52:51 +08:00
2025-10-17 15:38:19 +08:00
// -------- 主循环 --------
2025-10-17 15:26:08 +08:00
bool need_restart = false;
while (ctx->running)
2025-10-16 10:52:51 +08:00
{
2025-10-17 15:26:08 +08:00
GstMessage *msg = gst_bus_timed_pop_filtered(bus, 500 * GST_MSECOND,
(GstMessageType)(GST_MESSAGE_ERROR | GST_MESSAGE_EOS));
2025-10-16 10:52:51 +08:00
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-10-17 15:26:08 +08:00
GError *err = nullptr;
gst_message_parse_error(msg, &err, nullptr);
ctx->status.running = false;
ctx->status.last_error = err ? err->message : "Unknown GStreamer error";
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;
ctx->status.last_error = "End of stream";
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 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 15:26:08 +08:00
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(bus);
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 15:26:08 +08:00
LOG_WARN("[RTMP] Restarting " + key + " in 3s...");
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-16 10:52:51 +08:00
}
2025-10-17 15:26:08 +08:00
void RTMPManager::start_all()
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:26:08 +08:00
LOG_INFO("[RTMP] Starting all record streams...");
std::lock_guard<std::mutex> lock(streams_mutex);
for (auto &cam : g_app_config.cameras)
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:26:08 +08:00
auto key = make_key(cam.name);
auto ctx = std::make_unique<StreamContext>();
ctx->running.store(true);
ctx->thread = std::thread([cam, ptr = ctx.get()]() { stream_loop(cam, ptr); });
streams.emplace(key, std::move(ctx));
2025-10-16 10:25:51 +08:00
}
}
2025-10-17 15:26:08 +08:00
void RTMPManager::stop_all()
2025-10-16 10:25:51 +08:00
{
std::lock_guard<std::mutex> lock(streams_mutex);
2025-10-17 15:26:08 +08:00
for (auto &kv : streams) kv.second->running.store(false);
for (auto &kv : streams)
if (kv.second->thread.joinable()) kv.second->thread.join();
streams.clear();
2025-10-16 10:25:51 +08:00
}
2025-10-17 15:26:08 +08:00
bool RTMPManager::is_streaming(const std::string &cam_name)
2025-10-16 10:25:51 +08:00
{
std::lock_guard<std::mutex> lock(streams_mutex);
2025-10-17 15:26:08 +08:00
auto it = streams.find(make_key(cam_name));
return (it != streams.end() && it->second->status.running);
2025-10-16 10:25:51 +08:00
}
2025-10-17 15:26:08 +08:00
std::string RTMPManager::get_stream_url(const std::string &cam_name)
2025-10-16 10:25:51 +08:00
{
2025-10-17 15:26:08 +08:00
// 优先动态检测网卡 IP失败则使用固定值
2025-10-16 13:11:36 +08:00
std::string ip = get_ip_address("enP2p33s0");
2025-10-17 15:26:08 +08:00
if (ip.empty()) ip = "127.0.0.1"; // 或用动态获取网卡 IP
return "http://" + ip + ":1985/rtc/v1/whep/?app=record&stream=" + cam_name + "_main";
2025-10-16 10:25:51 +08:00
}
2025-10-17 13:36:22 +08:00
2025-10-17 15:26:08 +08:00
std::vector<std::pair<std::string, bool>> RTMPManager::get_all_status()
2025-10-17 13:36:22 +08:00
{
2025-10-17 15:26:08 +08:00
std::vector<std::pair<std::string, bool>> result;
std::lock_guard<std::mutex> lock(streams_mutex);
for (auto &kv : streams) result.emplace_back(kv.first, kv.second->status.running);
return result;
2025-10-17 13:36:22 +08:00
}