自学内容网 自学内容网

FFmpeg中结构释放小函数

用于FFmpeg一些结构内存释放问题

#pragma once
#include <iostream>

extern "C"
{
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavutil/avutil.h"
#include "libavutil/frame.h"
#include "libavcodec/packet.h"
}

// 泛化变参模板 ///
template <typename T, typename... Args>
void CleanUp(T* para, Args&&... args)
{
CleanUp(para);
CleanUp(std::forward<Args>(args)...);
}

 特化模板 /
template<>
inline void CleanUp<AVFormatContext*>(AVFormatContext** pp_fmt_ctx) {
if (pp_fmt_ctx && *pp_fmt_ctx) {
avformat_close_input(pp_fmt_ctx);
pp_fmt_ctx = nullptr;
}
}

template<>
inline void CleanUp<AVCodecContext*>(AVCodecContext** pp_codec_cxt) {
if (pp_codec_cxt && *pp_codec_cxt) {
avcodec_free_context(pp_codec_cxt);
pp_codec_cxt = nullptr;
}
}

template<>
inline void CleanUp<AVPacket*>(AVPacket** pp_pkt) {
if (pp_pkt && *pp_pkt) {
av_packet_free(pp_pkt);
pp_pkt = nullptr;
}
}

template<>
inline void CleanUp<AVFrame*>(AVFrame** pp_frame) {
if (pp_frame && *pp_frame) {
av_frame_free(pp_frame);
pp_frame = nullptr;
}
}

template<>
inline void CleanUp<uint8_t*>(uint8_t** u8_buffer) {
if (u8_buffer && *u8_buffer) {
av_freep(*u8_buffer);
u8_buffer = nullptr;
}
}

template<>
inline void CleanUp<FILE*>(FILE** pp_fp) {
if (pp_fp && *pp_fp) {
fclose(*pp_fp);
pp_fp = nullptr;
}
}

测试文件

// 资源释放测试
#include "CDestroyRes.h"
#include "vld.h"
#include <iostream>

extern "C"
{
#include <libavutil/avutil.h>
}
#pragma comment(lib, "avutil.lib")
#pragma comment(lib, "vld.lib")

int main()
{
int n = 100;
while (--n)
{
AVFormatContext* fmt_ctx = avformat_alloc_context();
const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_H264);
AVCodecContext* encoder = avcodec_alloc_context3(codec);
AVPacket* pkt = av_packet_alloc();
AVFrame* frame = av_frame_alloc();
frame->width = 1280;
frame->height = 640;
frame->format = AV_PIX_FMT_ARGB;
av_frame_get_buffer(frame, 0);
CleanUp(&fmt_ctx, &encoder, &pkt, &frame);
}

getchar();
return 0;
}

原文地址:https://blog.csdn.net/ShiXiAoLaNga/article/details/142426944

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!