#ifndef DECODESTREAM_H
#define DECODESTREAM_H

#include <QDebug>
#include <QList>
#include <QMutex>
#include <QObject>
#include <QQueue>
#include <QThread>

#include "avpacketqueuemanager.h"
#include "ffmpeginclude.h"

class DecodeStream : public QObject {
    Q_OBJECT
public:
    DecodeStream(QObject *parent = nullptr);
    bool init(AVPacketQueueManager *queueManager,
              AVFormatContext *formatContext, int videoIndex);
    bool init(AVPacketQueueManager *queueManager);
    void close();
    AVCodecContext *getCodecContext();
    AVCodecParserContext *getParserContext();
public slots:
    void startDecode();

signals:
    void repaintSignal(AVFrame *frame);  // 重绘
    void startDecodeSignal();
    void sendErrorMessageSignal(QString message, int type);

private:
    bool initObject();  // 初始化对象
    bool initDecoder(AVFormatContext *inputFormatContext,
                     int videoIndex);  // 初始化解码器
    bool initUDPDecoder();
    AVFrame *decodePacket(AVPacket *inputPacket);
    void free();  // 释放

    bool isValidAVFrame(AVFrame *frame);
    bool isValidAVPacket(AVPacket *pkt);

private:
    bool m_start = true;
    int m_videoIndex = 0;
    AVFormatContext *m_formatContext = nullptr;
    AVCodecContext *m_codecContext = nullptr;      // 解码器上下文
    QQueue<AVPacket *> *m_packetsQueue = nullptr;  // 解码前的视频帧队列
    AVFrame *m_frame = nullptr;                    // 解码后的视频帧
    AVFrame *m_frameTemp = nullptr;
    AVPacketQueueManager *m_queueManager = nullptr;
    QMutex m_mutex;

    AVCodecParserContext *m_parser = nullptr;
};

#endif  // DECODESTREAM_H
