如何为 RTSP 捕获创建准确的 C++ 定时器循环

问题描述 投票:0回答:1

所以我试图捕获一个流并将其写入 30 秒的块。我不知道相机的 fps 是多少,所以需要考虑到我只想捕捉 15 fps。

我的问题是,以下结果是 28 秒的块,而不是 30 秒。我怎样才能获得正确的计时?

对 C++ 来说并不是完全陌生,但相当生疏,以前从未做过类似的事情(通常是简单的 I/O 或在入门级游戏开发环境中)

我要么数学不正确,要么我正在做一些导致处理延迟的事情,或者我只是看得太久而错过了一些明显的(可能)

到目前为止我尝试过的:

int frame_count = 0;
double frame_duration = 1.0 / currentCameraConfig.fps;
auto start_time = std::chrono::steady_clock::now();

while (true) {
    cv::Mat frame;

    if (!cap.read(frame)) {
        break;
    }

    frame_count++;

    auto now = std::chrono::steady_clock::now();
    auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(now - start_time).count();

    if (elapsed_time < 30) {
        video_output.write(frame);
        std::cout << "[INFO]: elapsed time " << elapsed_time << std::endl;
        std::cout << "[INFO]: Saving video frame " << frame_count << " at " << currentCameraConfig.fps << " fps....cam " << std::endl;
    }

    if (cv::waitKey(1) == 'q' || elapsed_time >= 30) {
        std::cout << "\n [INFO]: Stopping recording..." << std::endl;
        break;
    }

    auto frame_end_time = std::chrono::steady_clock::now();
    auto frame_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(frame_end_time - now).count();

    int sleep_time = static_cast<int>((frame_duration * 1000) - frame_elapsed);
    if (sleep_time > 0) {
        std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));
    }
}

cap.release();
video_output.release();
std::cout << "Video saved successfully.!" << std::endl;
c++ c++-chrono
1个回答
0
投票

当前代码中经过的时间可能会导致精度损失。

auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(now - start_time).count();

if (elapsed_time < 30) {
    video_output.write(frame);
    std::cout << "[INFO]: elapsed time " << elapsed_time << std::endl;
    std::cout << "[INFO]: Saving video frame " << frame_count << " at " << currentCameraConfig.fps << " fps....cam " << std::endl;
}

尽量将经过的时间以毫秒为单位以保持精度。

auto elapsed_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time).count();

if (elapsed_time_ms < 30000) { // 30000 ms for 30 seconds
    video_output.write(frame);
    std::cout << "[INFO]: elapsed time " << elapsed_time_ms / 1000.0 << " seconds" << std::endl;
    std::cout << "[INFO]: Saving video frame " << frame_count << " at " << currentCameraConfig.fps << " fps....cam " << std::endl;
}

还有一个隐含的问题...如果 currentCameraConfig.fps 设置不正确或者相机以不同的速率捕获帧,这也可能导致时序不匹配。

© www.soinside.com 2019 - 2024. All rights reserved.