This commit is contained in:
cxh 2025-10-15 11:06:23 +08:00
parent 185d1dd952
commit a955867531

View File

@ -82,12 +82,11 @@ 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 = 1;
const int MAX_RETRIES = 5;
int retry_count = 0;
while (true)
{
// 检查线程是否被标记为停止
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
@ -107,18 +106,18 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
GstBus *bus = gst_element_get_bus(pipeline);
gst_element_set_state(pipeline, GST_STATE_PLAYING);
update_status(key, {true, StreamResult::OK, ""});
LOG_INFO("[RTMP] " + key + " is streaming.");
// 等待 pipeline 状态变为 PLAYING 或错误
bool first_playing = false;
bool stop_flag = false;
GstMessage *msg = nullptr;
while (!stop_flag)
{
GstMessage *msg = gst_bus_timed_pop_filtered(
msg = gst_bus_timed_pop_filtered(
bus, 100 * GST_MSECOND,
static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_EOS));
static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_STATE_CHANGED));
// 每次循环检查 stop 标志
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
@ -144,16 +143,25 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
g_error_free(err);
if (debug)
g_free(debug);
gst_message_unref(msg);
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);
stop_flag = true;
}
else if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_STATE_CHANGED)
{
GstState old_state, new_state, pending;
gst_message_parse_state_changed(msg, &old_state, &new_state, &pending);
if (GST_MESSAGE_SRC(msg) == GST_OBJECT(pipeline) && new_state == GST_STATE_PLAYING && !first_playing)
{
first_playing = true;
update_status(key, {true, StreamResult::OK, ""});
LOG_INFO("[RTMP] " + key + " is streaming.");
}
}
gst_message_unref(msg);
}
@ -163,14 +171,6 @@ void RTMPManager::stream_loop(Camera cam, StreamType type)
gst_object_unref(bus);
gst_object_unref(pipeline);
// 如果线程被 stop_camera 停掉了,不再重试
{
std::lock_guard<std::mutex> lock(streams_mutex);
auto it = streams.find(key);
if (it == streams.end() || !it->second->running.load())
break;
}
if (!stop_flag)
break;