How to get current image when using libcamera cpp?

I’ve been trying to use libcamera_cpp_demo but I want to save the latest image when triggered.
I have tried changing the buffer to 1 but the saved image is the third in a row as compared to the latest image.
Is there any alternative way of doing it?

#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

#include "LibCamera.h"

using namespace cv;

int main() {
    time_t start_time = time(0);
    int frame_count = 0;
    LibCamera cam_0;
    uint32_t width = 1280;
    uint32_t height = 720;
    uint32_t stride;
    char key_0, key_1;

    int ret = cam_0.initCamera();

    cam_0.configureStill(width, height, formats::RGB888, 1, 0);

    ControlList controls_;
    int64_t frame_time = 1000000 / 30;
    // Set frame rate
	controls_.set(controls::FrameDurationLimits, libcamera::Span<const int64_t, 2>({ frame_time, frame_time }));
    // Adjust the brightness of the output images, in the range -1.0 to 1.0
    controls_.set(controls::Brightness, 0.5);
    // Adjust the contrast of the output image, where 1.0 = normal contrast
    controls_.set(controls::Contrast, 1.5);
    // Set the exposure time
    controls_.set(controls::ExposureTime, 1000);

    // controls_.set(controls::AnalogueGain, 1);

    // cam_0.set(controls_);


    // if (!ret_0 ) {
        bool flag, flag_1;
        LibcameraOutData frameData, frameData_1;

        cam_0.startCamera();
        int i = 1;

        while (true) {
            

            namedWindow("libcamera-demo", WINDOW_NORMAL);
            // imshow("libcamera-demo", im);

            key_0 = waitKey(1);
            if (key_0 == 'q') {
                printf("captured");
                flag = cam_0.readFrame(&frameData);                
                Mat im(height, width, CV_8UC3, frameData.imageData);
                imwrite(std::to_string(i)+".jpg", im);
                cam_0.returnFrameBuffer(frameData);
                i++;
            } 

        }

        
        destroyAllWindows();
        cam_0.stopCamera();
    // }
    cam_0.closeCamera();
    // cm.reset();
    return 0;
}

@karatuno

This is a single-threaded example, various operations may not allow you to get accurate data.
You can try multithreading and buffers.