#include "HandleRtsp.h"


HandleRtsp::HandleRtsp(const QString & respUrl,QSemaphore& semaphore,QObject *parent )
    :QThread(parent),respUrl(respUrl),semaphore(semaphore),stopFlag(false)
{
    frameCounter.store(63);

}
HandleRtsp::~HandleRtsp(){
    qInfo()<<QString("HandleResp %1 stopFlag").arg(respUrl);

    stopFlag=true;
    wait();
}
void HandleRtsp::setFrameCounter(int frameCounter){
    this->frameCounter.store(frameCounter);
}
bool HandleRtsp::getFrameCounterStatus(){
    return isFrameCounter;
}

//void HandleRtsp::run(){
//    semaphore.acquire();
//    std::string r_url = respUrl.toStdString();
//    cv::VideoCapture cvCapture;
//    cvCapture.set(cv::CAP_PROP_FPS, 30);


//    int durationInSeconds = 600; // 视频片段时长为10分钟
//    qDebug() << QString::fromStdString(r_url);;

//    if(!cvCapture.open(r_url, cv::CAP_FFMPEG)){
//        emit streamInterrupted(respUrl);
//        return;
//    }
//    int frameCount;
//    cv::Mat frame;
//    cv::Size frameSize(640, 480);

//    std::time_t t = std::time(nullptr);
//    Common & instace= Common::getInstance();
//    QString video= instace.getVideoOut();
//    video.append("/").append(instace.getTimeString(t)).append(".mkv");
//    std::string outputFileName =video.toStdString();
//    qDebug()<<QString::fromStdString(outputFileName);

//    int frame_width = static_cast<int>(cvCapture.get(cv::CAP_PROP_FRAME_WIDTH));
//      int frame_height = static_cast<int>(cvCapture.get(cv::CAP_PROP_FRAME_HEIGHT));
//      double fps = 30.0; // 可以从cap.get(cv::CAP_PROP_FPS)获取摄像头的帧率
//     // int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); // 使用H.264编码器
//   cv::VideoWriter writer(outputFileName, cv::VideoWriter::fourcc('H', '2', '6', '4'), fps, cv::Size(frame_width, frame_height), true);

//    while (!stopFlag) {
//        if(!cvCapture.read(frame)){
//            qInfo()<<"emit streamInterrupted(respUrl)";
//            emit streamInterrupted(respUrl);
//            break;
//        }

//        if(!frame.empty()){
//            writer.write(frame); // 将帧写入视频文件

//            //默认64
//            if((frameCount && frameCounter.load())==0){
//                cv::Mat frame_bgr;
//                cv::cvtColor(frame, frame_bgr, cv::COLOR_RGB2BGR);
//                emit frameReady(frame_bgr, respUrl);
//            }
//            frameCount++;

//        }
//    }
//    cvCapture.release();
//}
void HandleRtsp::run() {
    cv::VideoCapture cvCapture;
    cvCapture.set(cv::CAP_PROP_FPS, 30);
    auto start = QDateTime::currentDateTime();
    std::string r_url = respUrl.toStdString();
    Common &instance = Common::getInstance();
    if(!cvCapture.open(r_url, cv::CAP_FFMPEG)){
        emit streamInterrupted(respUrl);
        return;
    }
    QString video = instance.getVideoOut();
    std::time_t t = std::time(nullptr);
    video.append("/").append(instance.getTimeString(t)).append(".mkv");
    std::string outputFileName = video.toStdString();
    qDebug() << QString::fromStdString(outputFileName);
    int frame_width = static_cast<int>(cvCapture.get(cv::CAP_PROP_FRAME_WIDTH));
    int frame_height = static_cast<int>(cvCapture.get(cv::CAP_PROP_FRAME_HEIGHT));
    double fps = cvCapture.get(cv::CAP_PROP_FPS);
    int frameCount;
    cv::Mat frame;
    cv::VideoWriter writer(outputFileName, cv::VideoWriter::fourcc('H', '2', '6', '4'), fps, cv::Size(frame_width, frame_height), true);
    while (!stopFlag) {
        if (!cvCapture.read(frame)) {
            qInfo() << "emit streamInterrupted(respUrl)";
            emit streamInterrupted(respUrl);
            break;
        }
        while (true) {
            if (!frame.empty()) {
                writer.write(frame); // 写入视频帧
                if ((frameCount % frameCounter.load()) == 0) { // Assuming you want to emit signals every 64 frames
                    cv::Mat frame_bgr;
                    cv::cvtColor(frame, frame_bgr, cv::COLOR_RGB2BGR);
                    emit frameReady(frame_bgr, respUrl);
                }

                frameCount++;
            }

            auto now =QDateTime::currentDateTime();
            auto elapsed = start.secsTo(now);

            if (elapsed >= 600 || stopFlag) {
                break;
            }
        }

        writer.release();

        if (stopFlag) {
            break;
        }

        start = QDateTime::currentDateTime();
    }

    cvCapture.release(); // 释放摄像头资源
}
