sleep cap to avoid capture timeout

This commit is contained in:
pigeatgarlic 2026-04-09 00:54:32 +07:00
parent b1ba6838f4
commit ca08cdfbc6
3 changed files with 40 additions and 3 deletions

View File

@ -106,6 +106,10 @@ void encodeThread(safe::mail_t mail, sample_queue_t samples, config_t config, vo
opus_multistream_encoder_ctl(opus.get(), OPUS_SET_BITRATE(stream->bitrate));
opus_multistream_encoder_ctl(opus.get(), OPUS_SET_VBR(0));
auto timer = platf::create_high_precision_timer();
auto packet_duration = std::chrono::milliseconds(config.packetDuration);
auto next_packet_time = std::chrono::steady_clock::now();
auto frame_size = config.packetDuration * stream->sampleRate / 1000;
while (auto sample = samples->pop()) {
buffer_t packet{1400};
@ -121,6 +125,25 @@ void encodeThread(safe::mail_t mail, sample_queue_t samples, config_t config, vo
packet.fake_resize(bytes);
packets->raise(channel_data, std::move(packet));
// Calculate sleep period based on absolute target
next_packet_time += packet_duration;
auto now = std::chrono::steady_clock::now();
if (next_packet_time > now) {
auto duration = next_packet_time - now;
if (duration > 100ms) {
// Safety cap and recover from future jumps
duration = 100ms;
if (next_packet_time - now > 1s) {
next_packet_time = now + 100ms;
}
}
timer->sleep_for(duration);
} else if (now - next_packet_time > 100ms) {
// Reset target if we fall more than 100ms behind to avoid massive bursts
next_packet_time = now;
}
}
}

View File

@ -241,6 +241,9 @@ int main(int argc, char *argv[]) {
do {
uint8_t flags = 0;
auto packet = video_packets->pop();
if (!packet)
break;
last_video_packet_time->store(steady_clock::now().time_since_epoch().count());
auto findex = packet->frame_index();
std::string_view payload{(char *)packet->data(), packet->data_size()};
@ -291,6 +294,9 @@ int main(int argc, char *argv[]) {
while (!process_shutdown_event->peek() && !local_shutdown->peek()) {
do {
auto packet = audio_packets->pop();
if (!packet)
break;
char *ptr = (char *)packet->second.begin();
size_t size = packet->second.size();
uint64_t utimestamp = steady_clock::now().time_since_epoch().count();

View File

@ -1647,9 +1647,17 @@ void encode_run(int &frame_nr, // Store progress of the frame number
auto now = std::chrono::steady_clock::now();
if (next_frame_time > now) {
timer->sleep_for(next_frame_time - now);
} else if (now - next_frame_time > 1s) {
// Reset target if we fall more than 1s behind
auto duration = next_frame_time - now;
if (duration > 100ms) {
// Safety cap and recover from future jumps
duration = 100ms;
if (next_frame_time - now > 1s) {
next_frame_time = now + 100ms;
}
}
timer->sleep_for(duration);
} else if (now - next_frame_time > 100ms) {
// Reset target if we fall more than 100ms behind to avoid massive bursts
next_frame_time = now;
}