.h文件
#pragma once
#include <mutex>
#include <iostream>extern "C"
{
#include "libavcodec/avcodec.h"}
#pragma comment(lib,"avcodec.lib")class XDecode
{
public:XDecode();virtual ~XDecode();virtual bool Open(AVCodecParameters* codecPar, bool isNeedClaerParam = false);virtual void Clear();virtual void Close();virtual bool Send(AVPacket* pkt);virtual AVFrame* Receive();public:bool isAudio = false;protected:AVCodecContext* codec = NULL;std::mutex mux;};
.cpp文件
#include "XDecode.h"using namespace std;XDecode::XDecode()
{}
XDecode::~XDecode()
{}
bool XDecode::Open(AVCodecParameters* codecpar, bool isNeedClaerParam)
{if (!codecpar) return false;this->Close();AVCodec* vcodec = avcodec_find_decoder(codecpar->codec_id);if (!vcodec){if (isNeedClaerParam){avcodec_parameters_free(&codecpar);}cout << "can't find the codec id : " << codecpar->codec_id << endl;return false;}cout << "avcodec_find_decoder(codec_id) : " << codecpar->codec_id << endl;mux.lock();codec = avcodec_alloc_context3(vcodec);avcodec_parameters_to_context(codec, codecpar);if (isNeedClaerParam){avcodec_parameters_free(&codecpar);}codec->thread_count = 4;int re = avcodec_open2(codec, 0, 0);if (re != 0){avcodec_free_context(&codec);mux.unlock();char buf[1024] = { 0 };av_strerror(re, buf, sizeof(buf) - 1);cout << " avcodec_open2 " << "--failed! : " << buf << endl;return false;}cout << "avcodec_open2 " << "--success! " << endl;mux.unlock();return true;
}
void XDecode::Clear()
{mux.lock();if (codec){avcodec_flush_buffers(codec);}mux.unlock();
}
void XDecode::Close()
{mux.lock();if (codec){avcodec_close(codec);avcodec_free_context(&codec);}mux.unlock();
}
bool XDecode::Send(AVPacket* pkt)
{if (!pkt || pkt->size <= 0 || !pkt->data)return false;mux.lock();if (!codec){mux.unlock();return false;}int re = avcodec_send_packet(codec, pkt);mux.unlock();av_packet_free(&pkt);if (re != 0)return false;return true;
}AVFrame* XDecode::Receive()
{mux.lock();if (!codec){mux.unlock();return NULL;}AVFrame* frame = av_frame_alloc();int re = avcodec_receive_frame(codec, frame);mux.unlock(); if (re != 0){av_frame_free(&frame);return NULL;}cout <<"解码后的frame->linesize[0]: " << frame->linesize[0] << std::endl;return frame;
}