ffmpeg使用硬解

FFHeader.h

#ifndef __FFHeader_H__
#define __FFHeader_H__

extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
    //#include "libavfilter/avfilter.h"
#include "libavutil/avutil.h"
#include "libswresample/swresample.h"
#include "libswscale/swscale.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/opt.h"
#include "libavcodec/avfft.h"
#include "libavutil/imgutils.h"
#include "libavutil/pixdesc.h"
#include "libavutil/hwcontext.h"
#include "libavutil/avassert.h"
}

#endif

 

main.cpp

#include <stdio.h>

#include "FFHeader.h"

typedef struct tagHWDev
{
    int hwDevType;
    char hwDevName[48];
}HWDev, * LPHWDev;
typedef struct tagHWDevList
{
    int size;
    HWDev hwDevs[12];
}HWDevList, * LPHWDevList;
int get_vdec_support_hwdevices(LPHWDevList devs) {
    devs->size = 0;
    enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
    while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE) {
        const char* hw_name = av_hwdevice_get_type_name(type);
        printf("hw name:name=%s;type=%d\n", hw_name, type);
        devs->hwDevs[devs->size].hwDevType = (int)type;
        int len = strlen(hw_name);
        memcpy(devs->hwDevs[devs->size].hwDevName, hw_name, len < 48 ? len : 48);
        devs->size++;
    }
    return -1;
}

static AVBufferRef* hw_device_ctx = NULL;
static FILE* output_file = NULL;
static enum AVPixelFormat hw_pix_fmt;
static enum AVPixelFormat get_hw_format(AVCodecContext* ctx,
    const enum AVPixelFormat* pix_fmts)
{
    const enum AVPixelFormat* p;

    for (p = pix_fmts; *p != -1; p++) {
        if (*p == hw_pix_fmt)
            return *p;
    }

    printf("Failed to get HW surface format.\n");
    return AV_PIX_FMT_NONE;
}

static int hw_decoder_init(AVCodecContext* ctx, const enum AVHWDeviceType type)
{
    int err = 0;

    if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type,
        NULL, NULL, 0)) < 0) {
        fprintf(stderr, "Failed to create specified HW device.\n");
        return err;
    }
    ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);

    return err;
}

static int decode_write(AVCodecContext* avctx, AVPacket* packet)
{
    AVFrame* frame = NULL, * sw_frame = NULL;
    AVFrame* tmp_frame = NULL;
    uint8_t* buffer = NULL;
    int size;
    int ret = 0;

    ret = avcodec_send_packet(avctx, packet);
    if (ret < 0) {
        fprintf(stderr, "Error during decoding\n");
        return ret;
    }

    int idx = 0;
    while (1) {
        if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
            fprintf(stderr, "Can not alloc frame\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        ret = avcodec_receive_frame(avctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            fprintf(stderr, "Error while decoding:%d\n", ret);
            av_frame_free(&frame);
            av_frame_free(&sw_frame);
            return 0;
        }
        else if (ret < 0) {
            fprintf(stderr, "Error while decoding\n");
            goto fail;
        }
        
        //sw_frame->format = AV_PIX_FMT_YUV420P;
        if (frame->format == hw_pix_fmt) {
            /* retrieve data from GPU to CPU */
            if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
                fprintf(stderr, "Error transferring the data to system memory\n");
                goto fail;
            }
            tmp_frame = sw_frame;
        }
        else
        {
            tmp_frame = frame;
        }
        printf("获取解码数据成功:%s,,,%d\n", av_get_pix_fmt_name(static_cast<AVPixelFormat>(tmp_frame->format)), tmp_frame->format);
        printf("linesize0:%d,linesize1:%d,linesize2:%d\n", tmp_frame->linesize[0], tmp_frame->linesize[1], tmp_frame->linesize[2]);
        printf("width:%d,height:%d\n", tmp_frame->width, tmp_frame->height);
        // 播放 ffplay -i d:/cap.yuv -pixel_format nv12 -framerate 25 -video_size 640x480
        //for (int j = 0; j < tmp_frame->height; j++)
        //{
        //    fwrite(tmp_frame->data[0] + j * tmp_frame->linesize[0], 1, tmp_frame->width, output_file);
        //}
        //// 写入uv
        //for (int j = 0; j < tmp_frame->height / 2; j++)
        //{
        //    fwrite(tmp_frame->data[1] + j * tmp_frame->linesize[1], 1, tmp_frame->width, output_file);
        //}
        //goto fail;


        size = av_image_get_buffer_size((AVPixelFormat)tmp_frame->format, tmp_frame->width,
            tmp_frame->height, 1);
        buffer = (uint8_t*)av_malloc(size * sizeof(uint8_t));
        if (!buffer) {
            fprintf(stderr, "Can not alloc buffer\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        ret = av_image_copy_to_buffer(buffer, size,
            (const uint8_t* const*)tmp_frame->data,
            (const int*)tmp_frame->linesize, (AVPixelFormat)tmp_frame->format,
            tmp_frame->width, tmp_frame->height, 1);
        if (ret < 0) {
            fprintf(stderr, "Can not copy image to buffer\n");
            goto fail;
        }

        if ((ret = fwrite(buffer, 1, size, output_file)) < 0) {
            fprintf(stderr, "Failed to dump raw data.\n");
            goto fail;
        }

    fail:
        av_frame_free(&frame);
        av_frame_free(&sw_frame);
        av_freep(&buffer);
        if (ret < 0)
            return ret;
    }
}
int start() 
{
    AVFormatContext* input_ctx = NULL;
    int video_stream, ret;
    AVStream* video = NULL;
    AVCodecContext* decoder_ctx = NULL;
    AVCodec* decoder = NULL;
    AVPacket *packet = NULL;
    enum AVHWDeviceType type;
    int i;

    HWDevList devList = { 0 };
    get_vdec_support_hwdevices(&devList);
    if (devList.size > 0)
    {
        //type = av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(AV_HWDEVICE_TYPE_CUDA));
        type = av_hwdevice_find_type_by_name(av_hwdevice_get_type_name((AVHWDeviceType)devList.hwDevs[0].hwDevType));
        if (type == AV_HWDEVICE_TYPE_NONE) {
            fprintf(stderr, "Device type %s is not supported.\n", "cuda");
            fprintf(stderr, "Available device types:");
            while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
                fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
            fprintf(stderr, "\n");
            return -1;
        }
    }
    packet = av_packet_alloc();
    if (!packet) {
        fprintf(stderr, "Failed to allocate AVPacket\n");
        return -1;
    }
    /* open the input file */
    //const char* url = "E:/Video/outputTest.mp4";
    AVDictionary* format_opts = NULL;
    av_dict_set(&format_opts, "stimeout", "2000000", 0); //设置链接超时时间(us)
    av_dict_set(&format_opts, "rtsp_transport", "tcp", 0); //设置推流的方式,默认udp。
    const char* url = "rtsp://admin:a12345678@192.168.1.170:554/cam/realmonitor?channel=1&subtype=0";
    if (avformat_open_input(&input_ctx, url, NULL, &format_opts) != 0) {
        fprintf(stderr, "Cannot open input file '%s'\n", "rtsp");
        return -1;
    }

    if (avformat_find_stream_info(input_ctx, NULL) < 0) {
        fprintf(stderr, "Cannot find input stream information.\n");
        return -1;
    }
    /* find the video stream information */
    ret = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0);
    if (ret < 0) {
        fprintf(stderr, "Cannot find a video stream in the input file\n");
        return -1;
    }
    video_stream = ret;
  //decoder = avcodec_find_decoder(AV_CODEC_ID_H264); //可以立马解
    for (i = 0;; i++) {
        const AVCodecHWConfig* config = avcodec_get_hw_config(decoder, i);
        if (!config) {
            fprintf(stderr, "Decoder %s does not support device type %s.\n",
                decoder->name, av_hwdevice_get_type_name(type));
            return -1;
        }
        if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
            config->device_type == type) {
            hw_pix_fmt = config->pix_fmt;
            break;
        }
    }

    if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
        return AVERROR(ENOMEM);

    video = input_ctx->streams[video_stream];
    if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0)
        return -1;

    decoder_ctx->get_format = get_hw_format;

    if (hw_decoder_init(decoder_ctx, type) < 0)
    {
        return -1;
    }

    if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0) {
        fprintf(stderr, "Failed to open codec for stream #%u\n", video_stream);
        return -1;
    }

    /* open the file to dump raw data */
    remove("./stream.yuv");
    output_file = fopen("./stream.yuv", "w+b");
    int idx = 0;
    remove("./stream.h264");
    FILE* h264_fp = fopen("./stream.h264", "wb+");
    /* actual decoding and dump the raw data */
    while (/*ret >= 0*/ idx++ <= 100) {
        if ((ret = av_read_frame(input_ctx, packet)) < 0)
            break;
        if (video_stream == packet->stream_index) {
            //fwrite(packet->data, 1, packet->size, h264_fp);
            ret = decode_write(decoder_ctx, packet);
            printf("decode_write ret:%d\n", ret);
        }
        av_packet_unref(packet);
    }
    fclose(h264_fp);

    /* flush the decoder */
    ret = decode_write(decoder_ctx, NULL);

    if (output_file)
        fclose(output_file);
    av_packet_free(&packet);
    avcodec_free_context(&decoder_ctx);
    avformat_close_input(&input_ctx);
    av_buffer_unref(&hw_device_ctx);
    printf("end\n");
    return 0;
}

void start2();
int main(int argc, char* argv[])
{
    HWDevList devList = { 0 };
    get_vdec_support_hwdevices(&devList);
    start();
    //start2();
    getchar();
    return 0;
}

void start2()
{
    AVFormatContext* pAVFomatContext = avformat_alloc_context();
    AVCodecContext* pAVCodecContext = nullptr;
    AVFrame* pAVFrame = av_frame_alloc();

    AVDictionary* opt = nullptr;
    //    av_dict_set(&opt,"probesize","4096",0);
    //    av_dict_set(&opt,"buffer_size","1024000",0);
    //    av_dict_set(&opt,"stimeout","5000000",0); //wei miao 5000000
    //    av_dict_set(&opt,"max_delay","0",0);
    av_dict_set(&opt, "rtsp_transport", "udp", 0);
    const char* url = "rtsp://admin:a12345678@192.168.1.170:554/cam/realmonitor?channel=1&subtype=0";
    int result = avformat_open_input(&pAVFomatContext, url, nullptr, nullptr);
    if (result < 0) {
        return;
    }
    result = avformat_find_stream_info(pAVFomatContext, nullptr);
    if (result < 0) {
        return;
    }

    int videoStreamIndex = -1;
    for (int i = 0; i < pAVFomatContext->nb_streams; i++) {
        if (pAVFomatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStreamIndex = i;
            break;
        }
    }

    if (videoStreamIndex == -1) {
        return;
    }

    int vden = 0, vnum = 0, fps;
    if (vden <= 0 || vnum <= 0) {
        fps = 25;
    }
    else {
        fps = vnum / vden;
    }

    pAVCodecContext = pAVFomatContext->streams[videoStreamIndex]->codec;
    int videoWidth = pAVCodecContext->width;
    int videoHeight = pAVCodecContext->height;

    AVCodec* pAVCodec;

    //    pAVCodec = avcodec_find_decoder(pAVCodecContext->codec_id);
    pAVCodec = avcodec_find_decoder_by_name("h264_cuvid"); //查找n卡解码器
   //
pAVCodec = avcodec_find_decoder_by_name("hevc_cuvid");

if (!pAVCodec) { return; } //int numBytes = avpicture_get_size(AV_PIX_FMT_NV12, videoWidth, videoHeight); int numBytes = avpicture_get_size(AV_PIX_FMT_YUV420P, videoWidth, videoHeight); uint8_t* out_buffer = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t)); int y_size = pAVCodecContext->width * pAVCodecContext->height; AVPacket* pAVPacket = (AVPacket*)malloc(sizeof(AVPacket)); av_new_packet(pAVPacket, y_size); av_dump_format(pAVFomatContext, 0, url, 0); result = avcodec_open2(pAVCodecContext, pAVCodec, nullptr); if (result < 0) { return; } remove("./stream.yuv"); output_file = fopen("./stream.yuv", "wb+"); int got_picture = 0; int idx = 0; while (idx++ <= 200) { if (av_read_frame(pAVFomatContext, pAVPacket) < 0) { break; } int r = avcodec_decode_video2(pAVCodecContext, pAVFrame, &got_picture, pAVPacket); printf("------%d\n", got_picture); if (got_picture) { printf("获取解码数据成功:%s,,,%d\n", av_get_pix_fmt_name(static_cast<AVPixelFormat>(pAVFrame->format)), pAVFrame->format); printf("linesize0:%d,linesize1:%d,linesize2:%d\n", pAVFrame->linesize[0], pAVFrame->linesize[1], pAVFrame->linesize[2]); printf("width:%d,height:%d\n", pAVFrame->width, pAVFrame->height); int bytes = 0; {//AV_PIX_FMT_NV12 for (int i = 0; i < videoHeight; i++) { //将y分量拷贝 memcpy(out_buffer + bytes, pAVFrame->data[0] + pAVFrame->linesize[0] * i, videoWidth); bytes += videoWidth; } int uv = videoHeight >> 1; for (int i = 0; i < uv; i++) { //将uv分量拷贝 memcpy(out_buffer + bytes, pAVFrame->data[1] + pAVFrame->linesize[1] * i, videoWidth); bytes += videoWidth; } } fwrite(out_buffer, 1, numBytes, output_file); } av_free_packet(pAVPacket); } fclose(output_file); avcodec_close(pAVCodecContext); avformat_close_input(&pAVFomatContext); av_free(out_buffer); printf("end\n"); }

 

posted @ 2022-12-05 11:20  一夜梦想  阅读(240)  评论(0编辑  收藏  举报