kunlang_video/src/rtmp_manager.cpp

340 lines
11 KiB
C++
Raw Normal View History

// rtsp_manager.cpp
#include "rtmp_manager.hpp"
#include "logger.hpp"
#include <chrono>
#include <thread>
2025-10-15 08:50:01 +08:00
#include <iostream>
2025-10-15 10:18:02 +08:00
#include <utility>
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-15 08:50:01 +08:00
RTMPManager::StreamCallback RTMPManager::status_callback = nullptr;
std::string RTMPManager::make_stream_key(const std::string &cam_name, StreamType type)
{
return cam_name + stream_type_suffix(type);
}
void RTMPManager::init()
{
gst_init(nullptr, nullptr);
LOG_INFO("[RTMP] GStreamer initialized.");
}
2025-10-15 08:50:01 +08:00
void RTMPManager::set_status_callback(StreamCallback cb)
{
status_callback = std::move(cb);
}
void RTMPManager::update_status(const std::string &key, const StreamStatus &status)
{
2025-10-15 08:57:40 +08:00
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
if (it != streams.end())
it->second->status = status;
}
2025-10-15 08:50:01 +08:00
if (status_callback)
status_callback(key, status);
}
GstElement *RTMPManager::create_pipeline(const Camera &cam, StreamType type)
{
2025-10-15 10:18:02 +08:00
int width = cam.width, height = cam.height, fps = cam.fps, bitrate = cam.bitrate;
if (type == StreamType::SUB)
{
width = std::max(160, width / 2);
height = std::max(120, height / 2);
fps = std::max(10, fps / 2);
2025-10-14 17:49:26 +08:00
bitrate = std::max(300000, bitrate / 2);
}
2025-10-14 17:49:26 +08:00
std::string stream_name = cam.name + stream_type_suffix(type);
std::string pipeline_str =
"v4l2src device=" + cam.device +
" ! video/x-raw,format=NV12,width=" + std::to_string(width) +
",height=" + std::to_string(height) +
2025-10-15 08:50:01 +08:00
",framerate=" + std::to_string(fps) +
"/1 ! queue max-size-buffers=1 leaky=downstream "
"! mpph264enc bps=" +
std::to_string(bitrate) +
" gop=" + std::to_string(fps) +
2025-10-15 08:50:01 +08:00
" ! h264parse ! flvmux streamable=true name=mux "
"! rtmpsink location=\"rtmp://127.0.0.1/live/" +
stream_name + " live=1\" sync=false";
2025-10-15 08:50:01 +08:00
LOG_INFO("[RTMP] Creating pipeline for '" + stream_name + "': " + pipeline_str);
GError *error = nullptr;
GstElement *pipeline = gst_parse_launch(pipeline_str.c_str(), &error);
if (error)
{
2025-10-15 08:50:01 +08:00
LOG_ERROR("[RTMP] Pipeline parse error: " + std::string(error->message));
g_error_free(error);
return nullptr;
}
return pipeline;
}
2025-10-15 13:09:10 +08:00
void RTMPManager::publish_stream_status(const std::string &cam_name, StreamType type, const std::string &seqNo, bool ok, const std::string &reason)
2025-10-15 11:27:53 +08:00
{
2025-10-15 13:13:29 +08:00
// 找 camera index
2025-10-15 13:09:10 +08:00
int cam_index = -1;
2025-10-15 13:13:29 +08:00
Camera *cam_ptr = nullptr;
2025-10-15 13:09:10 +08:00
for (size_t i = 0; i < g_app_config.cameras.size(); ++i)
{
if (g_app_config.cameras[i].name == cam_name)
{
cam_index = static_cast<int>(i);
2025-10-15 13:13:29 +08:00
cam_ptr = &g_app_config.cameras[i];
2025-10-15 13:09:10 +08:00
break;
}
}
2025-10-15 11:27:53 +08:00
nlohmann::json ch_resp;
2025-10-15 13:09:10 +08:00
ch_resp["loc"] = cam_index;
2025-10-15 13:13:29 +08:00
ch_resp["url"] = ok && cam_ptr ? get_stream_url(cam_ptr->name, type) : "";
2025-10-15 11:27:53 +08:00
ch_resp["result"] = ok ? 0 : 1;
ch_resp["reason"] = reason;
nlohmann::json reply;
reply["type"] = "response";
reply["seqNo"] = seqNo;
reply["data"] = nlohmann::json::array({ch_resp});
mqtt_client->publish(g_app_config.mqtt.topics.video_down, reply.dump());
}
2025-10-15 13:09:10 +08:00
// 修改 stream_loop新增 seqNo 参数
void RTMPManager::stream_loop(Camera cam, StreamType type, const std::string &seqNo)
{
2025-10-15 10:18:02 +08:00
std::string key = make_stream_key(cam.name, type);
2025-10-15 08:50:01 +08:00
LOG_INFO("[RTMP] Stream loop started for " + key);
2025-10-15 11:27:53 +08:00
const int MAX_RETRIES = 3;
2025-10-15 10:42:49 +08:00
int retry_count = 0;
while (true)
{
{
std::lock_guard<std::mutex> lock(streams_mutex);
2025-10-15 08:57:40 +08:00
auto it = streams.find(key);
if (it == streams.end() || !it->second->running.load())
break;
}
2025-10-15 10:42:49 +08:00
GstElement *pipeline = create_pipeline(cam, type);
if (!pipeline)
{
2025-10-15 11:27:53 +08:00
std::string reason = "Failed to create pipeline (device unavailable or resolution unsupported)";
update_status(key, {false, StreamResult::PIPELINE_ERROR, reason});
2025-10-15 13:09:10 +08:00
publish_stream_status(cam.name, type, seqNo, false, reason);
2025-10-15 10:42:49 +08:00
if (++retry_count > MAX_RETRIES)
break;
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
2025-10-15 10:42:49 +08:00
}
GstBus *bus = gst_element_get_bus(pipeline);
gst_element_set_state(pipeline, GST_STATE_PLAYING);
2025-10-15 11:27:53 +08:00
bool first_frame_received = false;
2025-10-15 10:42:49 +08:00
bool stop_flag = false;
2025-10-15 13:31:50 +08:00
const int FIRST_FRAME_TIMEOUT_SEC = 5; // 等待第一帧最大秒数
auto first_frame_start = std::chrono::steady_clock::now();
2025-10-15 10:42:49 +08:00
while (!stop_flag)
{
2025-10-15 11:27:53 +08:00
GstMessage *msg = gst_bus_timed_pop_filtered(
2025-10-15 10:42:49 +08:00
bus, 100 * GST_MSECOND,
2025-10-15 11:06:23 +08:00
static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_STATE_CHANGED));
2025-10-15 10:42:49 +08:00
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
if (it == streams.end() || !it->second->running.load())
{
stop_flag = true;
break;
}
}
2025-10-15 13:31:50 +08:00
if (!first_frame_received)
{
auto elapsed = std::chrono::steady_clock::now() - first_frame_start;
if (std::chrono::duration_cast<std::chrono::seconds>(elapsed).count() > FIRST_FRAME_TIMEOUT_SEC)
{
std::string reason = "No frames received within timeout";
LOG_WARN("[RTMP] " + key + ": " + reason);
update_status(key, {false, StreamResult::TIMEOUT, reason});
publish_stream_status(cam.name, type, seqNo, false, reason);
stop_flag = true;
}
}
2025-10-15 10:42:49 +08:00
if (!msg)
continue;
2025-10-15 11:27:53 +08:00
switch (GST_MESSAGE_TYPE(msg))
{
case GST_MESSAGE_ERROR:
2025-10-15 10:42:49 +08:00
{
GError *err = nullptr;
gchar *debug = nullptr;
gst_message_parse_error(msg, &err, &debug);
std::string err_msg = err ? err->message : "Unknown GStreamer error";
LOG_ERROR("[RTMP] Error in " + key + ": " + err_msg);
update_status(key, {false, StreamResult::CONNECTION_FAIL, err_msg});
2025-10-15 13:09:10 +08:00
publish_stream_status(cam.name, type, seqNo, false, err_msg);
2025-10-15 10:42:49 +08:00
if (err)
g_error_free(err);
if (debug)
g_free(debug);
stop_flag = true;
2025-10-15 11:27:53 +08:00
break;
2025-10-15 10:42:49 +08:00
}
2025-10-15 11:27:53 +08:00
case GST_MESSAGE_EOS:
2025-10-15 10:42:49 +08:00
LOG_WARN("[RTMP] EOS on " + key);
update_status(key, {false, StreamResult::EOS_RECEIVED, "EOS"});
2025-10-15 13:09:10 +08:00
publish_stream_status(cam.name, type, seqNo, false, "EOS received");
2025-10-15 10:42:49 +08:00
stop_flag = true;
2025-10-15 11:27:53 +08:00
break;
case GST_MESSAGE_STATE_CHANGED:
2025-10-15 11:06:23 +08:00
{
2025-10-15 11:27:53 +08:00
GstState old_state, new_state;
gst_message_parse_state_changed(msg, &old_state, &new_state, nullptr);
if (GST_MESSAGE_SRC(msg) == GST_OBJECT(pipeline) && new_state == GST_STATE_PLAYING && !first_frame_received)
2025-10-15 11:06:23 +08:00
{
2025-10-15 11:27:53 +08:00
first_frame_received = true;
LOG_INFO("[RTMP] First frame received for " + key);
2025-10-15 11:06:23 +08:00
update_status(key, {true, StreamResult::OK, ""});
2025-10-15 13:09:10 +08:00
publish_stream_status(cam.name, type, seqNo, true, "Streaming OK");
2025-10-15 11:06:23 +08:00
}
2025-10-15 11:27:53 +08:00
break;
}
2025-10-15 11:06:23 +08:00
}
2025-10-15 10:42:49 +08:00
gst_message_unref(msg);
}
2025-10-15 10:42:49 +08:00
gst_element_set_state(pipeline, GST_STATE_NULL);
if (bus)
gst_object_unref(bus);
gst_object_unref(pipeline);
if (!stop_flag)
break;
if (++retry_count > MAX_RETRIES)
{
2025-10-15 10:42:49 +08:00
LOG_ERROR("[RTMP] " + key + " reached max retries. Giving up.");
break;
}
2025-10-15 10:42:49 +08:00
std::this_thread::sleep_for(std::chrono::seconds(1));
}
2025-10-15 10:30:36 +08:00
update_status(key, {false, StreamResult::UNKNOWN, "Stream loop exited"});
2025-10-15 10:42:49 +08:00
LOG_INFO("[RTMP] Stream loop ended for " + key);
}
2025-10-15 13:09:10 +08:00
// 修改 start_camera新增 seqNo 参数
void RTMPManager::start_camera(const Camera &cam, StreamType type, const std::string &seqNo)
{
std::string key = make_stream_key(cam.name, type);
2025-10-15 10:18:02 +08:00
2025-10-15 13:09:10 +08:00
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
if (it != streams.end() && it->second->running.load())
2025-10-15 08:57:40 +08:00
{
2025-10-15 13:09:10 +08:00
LOG_WARN("[RTMP] " + key + " already streaming.");
// 上报已经在请求状态
publish_stream_status(cam.name, type, seqNo, false, "Already streaming");
return;
2025-10-15 08:57:40 +08:00
}
2025-10-15 13:09:10 +08:00
auto ctx = std::make_unique<StreamContext>();
ctx->running.store(true);
ctx->thread = std::thread([cam, type, seqNo]()
{
stream_loop(cam, type, seqNo); // stream_loop 内部处理 MQTT 上报
});
streams[key] = std::move(ctx);
2025-10-15 08:57:40 +08:00
LOG_INFO("[RTMP] start_camera requested for " + key);
}
2025-10-15 13:09:10 +08:00
void RTMPManager::stop_camera(const std::string &cam_name, StreamType type, const std::string &seqNo)
{
std::string key = make_stream_key(cam_name, type);
2025-10-15 10:18:02 +08:00
std::unique_ptr<StreamContext> ctx;
2025-10-15 10:02:01 +08:00
{
2025-10-15 08:57:40 +08:00
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
if (it == streams.end())
{
LOG_WARN("[RTMP] " + key + " not found.");
2025-10-15 13:09:10 +08:00
// 上报停止失败(未找到)
publish_stream_status(cam_name, type, seqNo, false, "Stream not found");
2025-10-15 08:57:40 +08:00
return;
}
2025-10-15 13:09:10 +08:00
2025-10-15 08:57:40 +08:00
it->second->running.store(false);
2025-10-15 10:18:02 +08:00
ctx = std::move(it->second);
2025-10-15 08:57:40 +08:00
streams.erase(it);
}
2025-10-15 08:39:35 +08:00
2025-10-15 10:18:02 +08:00
if (ctx->thread.joinable())
ctx->thread.join();
2025-10-15 08:50:01 +08:00
update_status(key, {false, StreamResult::OK, "Stopped manually"});
2025-10-15 10:18:02 +08:00
LOG_INFO("[RTMP] stop_camera completed: " + key);
2025-10-15 13:09:10 +08:00
// MQTT 上报手动停止成功
publish_stream_status(cam_name, type, seqNo, true, "Stopped manually");
2025-10-15 08:50:01 +08:00
}
void RTMPManager::stop_all()
{
2025-10-15 10:18:02 +08:00
std::vector<std::unique_ptr<StreamContext>> ctxs;
2025-10-15 08:57:40 +08:00
2025-10-15 08:50:01 +08:00
{
std::lock_guard<std::mutex> lock(streams_mutex);
for (auto &kv : streams)
2025-10-15 08:57:40 +08:00
kv.second->running.store(false);
2025-10-15 10:18:02 +08:00
for (auto &kv : streams)
ctxs.push_back(std::move(kv.second));
streams.clear();
2025-10-15 08:50:01 +08:00
}
2025-10-15 08:57:40 +08:00
2025-10-15 10:18:02 +08:00
for (auto &ctx : ctxs)
if (ctx->thread.joinable())
ctx->thread.join();
2025-10-15 08:57:40 +08:00
LOG_INFO("[RTMP] stop_all completed.");
}
bool RTMPManager::is_streaming(const std::string &cam_name, StreamType type)
{
std::lock_guard<std::mutex> lock(streams_mutex);
2025-10-15 10:18:02 +08:00
auto it = streams.find(make_stream_key(cam_name, type));
2025-10-15 08:57:40 +08:00
return it != streams.end() && it->second->running.load();
}
bool RTMPManager::is_any_streaming()
{
std::lock_guard<std::mutex> lock(streams_mutex);
for (auto &kv : streams)
2025-10-15 08:57:40 +08:00
if (kv.second->running.load())
return true;
return false;
}
std::string RTMPManager::get_stream_url(const std::string &cam_name, StreamType type)
{
2025-10-14 17:49:26 +08:00
return "rtmp://127.0.0.1/live/" + make_stream_key(cam_name, type);
}