-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathAlgChannelDemux.cc
More file actions
307 lines (276 loc) · 11 KB
/
Copy pathAlgChannelDemux.cc
File metadata and controls
307 lines (276 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// AlgChannelDemux — channel demuxer lifecycle and stream distribution.
#include "flow/channel/AlgChannelDemux.h"
#include <algorithm>
#include "flow/channel/VideoEofPolicy.h"
#include "service/detail/ServiceRegistry.h"
#include "service/event/IEventNotifier.h"
#include "service/system/IConfigReadService.h"
#include "service/task/ITaskChannel.h"
#include "util/Log.h"
#include "util/TimeUtil.h"
#include "util/TimingConstants.h"
#include "util/dto/ActionCodes.h"
namespace chrono = std::chrono;
static constexpr const char* kTag = "ChannelDemux ";
namespace cosmo {
AlgChannelDemux::~AlgChannelDemux() {
LOG_INFO("{}:{} Delete", kTag, channel_id_);
ClearLastFrame();
}
AlgChannelDemux::AlgChannelDemux(const std::string& channel_id, const std::string& url)
: AlgDataQueueDistributor(channel_id + " Demux"),
util::Thread(channel_id + " Demux"),
channel_id_(channel_id),
url_(url),
recorder_(std::make_shared<AlgChannelMp4>(channel_id)),
duration_stat_(channel_id + " Demux") {
action_status_ = util::ErrorEnum::ActionReady;
status_.status = service::camera::AlgDemuxStatus::AlgDemuxInit;
status_.timePoint = chrono::steady_clock::now();
LOG_INFO("{}:{} Init", kTag, channel_id_);
}
bool AlgChannelDemux::SetUrl(const std::string& url) {
if (url.empty())
return false;
if (url_ != url) {
LOG_INFO("{}:{} URL changed", kTag, channel_id_);
url_ = url;
is_url_changed_ = true;
video_read_count_ = 0;
ClearLastFrame();
}
return true;
}
bool AlgChannelDemux::SetVideoRepeatCount(int repeat_count) {
if (video_repeat_count_ != repeat_count) {
LOG_INFO("{}:{} VideoRepeatCount Change From {} To {}", kTag, channel_id_, video_repeat_count_,
repeat_count);
video_repeat_count_ = repeat_count;
}
return true;
}
bool AlgChannelDemux::SetForStartTask() {
if ((!IsLiveStream()) && (service::camera::AlgDemuxStatus::AlgDemuxReadEnd == status_.status)) {
video_read_count_ = 0;
is_need_repeat_ = true;
}
return true;
}
void AlgChannelDemux::AddViewerPacketQueue(std::shared_ptr<AsyncQueue<VideoPacketPtr>> async_packet_queue) {
std::lock_guard<std::shared_mutex> lock(demux_mtx_);
if (!async_packet_queue) {
return;
}
auto it = std::find(async_packet_queues_.begin(), async_packet_queues_.end(), async_packet_queue);
if (it == async_packet_queues_.end()) {
async_packet_queues_.push_back(async_packet_queue);
}
}
void AlgChannelDemux::RemoveViewerPacketQueue(
std::shared_ptr<AsyncQueue<VideoPacketPtr>> async_packet_queue) {
std::lock_guard<std::shared_mutex> lock(demux_mtx_);
async_packet_queues_.erase(
std::remove(async_packet_queues_.begin(), async_packet_queues_.end(), async_packet_queue),
async_packet_queues_.end());
}
bool AlgChannelDemux::SetVideoFps(float fps) {
demuxer_.SetForceFps(fps);
return true;
}
bool AlgChannelDemux::SetPollChannel(const std::string& channel_id) {
if (poll_channel_id_ != channel_id) {
LOG_INFO("{}:{} PollChannel Change From {} To {}", kTag, channel_id_, poll_channel_id_, channel_id);
poll_channel_id_ = channel_id;
}
return true;
}
void AlgChannelDemux::Start() {
std::lock_guard<std::mutex> lock(lifecycle_mtx_);
if (is_running_.exchange(true)) {
LOG_INFO("{}:{} Already Running", kTag, channel_id_);
return;
}
ResetDistributor();
if (!start()) {
is_running_ = false;
action_status_ = util::ErrorEnum::ActionStop;
LOG_ERRO("{}:{} Start failed: previous thread still joinable", kTag, channel_id_);
return;
}
action_status_ = util::ErrorEnum::ActionStart;
}
void AlgChannelDemux::Stop() {
std::lock_guard<std::mutex> lock(lifecycle_mtx_);
LOG_INFO("{}:{} Wait To Stop", kTag, channel_id_);
if (!is_running_.exchange(false)) {
LOG_INFO("{}:{} Already Stopped", kTag, channel_id_);
return;
}
stop();
// Reset is_need_repeat_ before CloseStream. Otherwise
// CloseStream → demuxer_.CloseStream(is_need_repeat_=true) skips closing the
// FFmpeg context (repeat mode keeps it open for local files), causing the
// old context to leak on the next OpenStream.
is_need_repeat_ = false;
video_read_count_ = 0;
CloseStream();
ClearLastFrame();
action_status_ = util::ErrorEnum::ActionStop;
}
bool AlgChannelDemux::OpenStream() {
if (url_.size() < 7) {
action_status_ = util::ErrorEnum::DemuxOpenInvalidUrl;
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxInvalidUrl);
return false;
}
// Skip retry for unauthorized status unless URL changed or 30 min elapsed.
if (service::camera::AlgDemuxStatus::AlgDemuxOpenUnauthorized == status_.status) {
if (!is_url_changed_) {
auto now = chrono::steady_clock::now();
if (chrono::duration_cast<chrono::seconds>(now - status_.timePoint).count() < 30 * 60) {
return false;
}
}
}
demuxer_.SetFile(url_);
read_frames_ = 0;
is_url_changed_ = false;
auto ret = demuxer_.OpenStream(is_need_repeat_);
if (util::ErrorEnum::Success != ret) {
if (util::ErrorEnum::DemuxOpenStreamUnauthorized == ret) {
action_status_ = util::ErrorEnum::DemuxOpenStreamUnauthorized;
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxOpenUnauthorized);
} else {
action_status_ = util::ErrorEnum::DemuxOpenStreamFail;
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxOpenFailed);
}
return false;
}
if (util::ErrorEnum::Success != demuxer_.FindStream(is_need_repeat_)) {
action_status_ = util::ErrorEnum::DemuxGetStreamFail;
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxOpenFailed);
return false;
}
recorder_->SetFps(demuxer_.GetFPS());
NotifyOnInfo();
video_read_count_ += 1;
bool was_repeat = is_need_repeat_;
is_need_repeat_ = false;
is_have_report_ = false;
is_opened_ = true;
read_frames_ = 0;
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxOpened);
if (!was_repeat) {
action_status_ = util::ErrorEnum::DemuxStreamStart;
}
// On repeat open, leave action_status_ as Success (set by the last
// frame read before StreamEnd) to avoid a transient gap.
LOG_INFO("{}{} Stream Opened", kTag, channel_id_);
return true;
}
void AlgChannelDemux::CloseStream() {
if (is_opened_) {
is_opened_ = false;
demuxer_.CloseStream(is_need_repeat_);
action_status_ = util::ErrorEnum::DemuxStreamClosed;
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxClosed);
ClearLastFrame();
}
}
void AlgChannelDemux::HandleStream() {
// Return early if stream is not opened or actively reading.
if (!((service::camera::AlgDemuxStatus::AlgDemuxOpened == status_.status) ||
(service::camera::AlgDemuxStatus::AlgDemuxReading == status_.status) ||
(service::camera::AlgDemuxStatus::AlgDemuxReadFailed == status_.status))) {
std::this_thread::sleep_for(timing::kOneSecondInterval);
no_data_count_++;
if (0 == no_data_count_ % 600) {
LOG_INFO("{}:{} No Data Status Is {}", kTag, channel_id_, StatusString(status_.status));
}
return;
}
no_data_count_ = 0;
auto frame_packet = std::make_shared<media::VideoPacket>();
duration_stat_.BeginSample();
auto ret = demuxer_.Demux(frame_packet);
duration_stat_.EndSample();
if (media::ReadFrameStatus::Success != ret) {
if (media::ReadFrameStatus::StreamEnd == ret) {
const bool is_live_stream = IsLiveStream();
const auto disposition =
flow::DecideVideoEof(is_live_stream, video_read_count_, video_repeat_count_);
if (flow::VideoEofDisposition::Reopen == disposition) {
is_need_repeat_ = true;
if (is_live_stream) {
LOG_INFO("{}:{} Live Stream End Need ReOpen Or Request Url", kTag, channel_id_);
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxReadFailed);
action_status_ = util::ErrorEnum::DemuxReadStreamFail;
return;
}
LOG_INFO("{}:{} Stream End Now RepeatCount:{} Max RepeatCount:{}", kTag, channel_id_,
video_read_count_, video_repeat_count_);
// A loop boundary is not terminal. Keep the last Reading state
// and successful action status until OpenStream publishes the
// next Opened/Reading transition.
frame_packet->index = -1;
recorder_->TaskFrame(frame_packet);
return;
}
if (!is_have_report_) {
is_have_report_ = true;
NotifyOnComplete();
}
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxReadEnd);
action_status_ = util::ErrorEnum::DemuxStreamClosed;
frame_packet->index = -1;
recorder_->TaskFrame(frame_packet);
return;
}
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxReadFailed);
action_status_ = util::ErrorEnum::DemuxReadStreamFail;
return;
}
SetStatusInfo(service::camera::AlgDemuxStatus::AlgDemuxReading);
read_frames_++;
AlgDataPtr data = std::make_shared<AlgData>();
data->dataType = AlgDataType::ChannelDataOrig;
data->chanDataOrig.packet = frame_packet;
data->chanDataOrig.fps = demuxer_.GetFPS();
data->firstTimePoint = frame_packet->time_point;
action_status_ = util::ErrorEnum::Success;
if (recorder_) {
recorder_->TaskFrame(frame_packet);
}
{
// Distribute to display viewer.
std::shared_lock<std::shared_mutex> lock(demux_mtx_);
for (const auto& async_packet_queue : async_packet_queues_) {
if (async_packet_queue) {
async_packet_queue->Insert(frame_packet);
}
}
}
{
std::lock_guard<std::shared_mutex> lock(demux_mtx_);
if (frame_packet) {
last_frame_ = frame_packet;
}
}
DistributorData(data);
}
void AlgChannelDemux::NotifyOnComplete() {
if (!service::ServiceRegistry::Instance().Get<service::IConfigReadService>().IsNetworkModel()) {
return;
}
auto tasks =
service::ServiceRegistry::Instance().Get<cosmo::service::ITaskChannel>().GetChannelTasks(channel_id_);
for (const auto& task : tasks) {
CMsgOnCompleteReq req;
CMsgOnCompleteRsp rsp;
req.taskId = task;
LOG_INFO("{}:{} {} Complete", kTag, channel_id_, task);
service::ServiceRegistry::Instance().Get<cosmo::service::IEventNotifier>().NotifyComplete(req, rsp);
}
}
// Stream management — moved to AlgChannelDemuxStream.cc
} // namespace cosmo