This commit is contained in:
cxh 2025-10-15 10:42:49 +08:00
parent 4de32c3487
commit 09ce42aeb6

View File

@ -82,12 +82,26 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
std::string key = make_stream_key(cam.name, type);
LOG_INFO("[RTMP] Stream loop started for " + key);
const int MAX_RETRIES = 5;
int retry_count = 0;
while (true)
{
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
if (it == streams.end() || !it->second->running.load())
break;
}
GstElement *pipeline = create_pipeline(cam, type);
if (!pipeline)
{
update_status(key, {false, StreamResult::PIPELINE_ERROR, "Failed to create pipeline"});
LOG_ERROR("[RTMP] " + key + " pipeline creation failed. Exiting stream loop.");
return;
if (++retry_count > MAX_RETRIES)
break;
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
GstBus *bus = gst_element_get_bus(pipeline);
@ -95,17 +109,25 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
update_status(key, {true, StreamResult::OK, ""});
LOG_INFO("[RTMP] " + key + " is streaming.");
while (true)
bool stop_flag = false;
GstMessage *msg = nullptr;
while (!stop_flag)
{
GstMessage *msg = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE,
// 等待消息,但设置 100ms 超时
msg = gst_bus_timed_pop_filtered(
bus, 100 * GST_MSECOND,
static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_EOS));
{
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;
}
}
if (!msg)
continue;
@ -122,15 +144,13 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
g_error_free(err);
if (debug)
g_free(debug);
gst_message_unref(msg);
break; // 出错立即退出
stop_flag = true;
}
else if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS)
{
LOG_WARN("[RTMP] EOS on " + key);
update_status(key, {false, StreamResult::EOS_RECEIVED, "EOS"});
gst_message_unref(msg);
break; // EOS 退出
stop_flag = true;
}
gst_message_unref(msg);
@ -141,8 +161,21 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
gst_object_unref(bus);
gst_object_unref(pipeline);
LOG_INFO("[RTMP] Stream loop ended for " + key);
if (!stop_flag)
break;
if (++retry_count > MAX_RETRIES)
{
LOG_ERROR("[RTMP] " + key + " reached max retries. Giving up.");
break;
}
LOG_WARN("[RTMP] Reconnecting " + key + " in 1s...");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
update_status(key, {false, StreamResult::UNKNOWN, "Stream loop exited"});
LOG_INFO("[RTMP] Stream loop ended for " + key);
}
void RTMPManager::start_camera(const Camera &cam, StreamType type)