日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?ffmpeg硬件解碼的實現方法_C 語言

作者:殺神李 ? 更新時間: 2022-10-21 編程語言

什么是硬件解碼

普通解碼是利用cpu去解碼也就是軟件解碼 硬件解碼就是利用gpu去解碼

為什么要使用硬件解碼

首先最大的好處 快硬解播放出來的視頻較為流暢,并且能夠延長移動設備播放視頻的時間; 而軟解由于軟解加大CPU工作負荷,會占用過多的移動CPU資源,如果CPU能力不足,則軟件也將受到影響 最主要就是一個字 快

怎樣使用硬件解碼

ffmpeg內部為我們提供了友好的接口去實現硬件解碼

注意事項

ffmpeg內部有很多編解碼器 并不是所有的編解碼器都支持硬件解碼 并且就算支持硬件解碼的編解碼器也不一定能支持你的顯卡 也就是說在使用硬件解碼時我們首先要去判斷這個解碼器是否支持在這個平臺對這個顯卡進行硬件編解碼 不然是無法使用的

對顯卡廠家SDK進行封裝和集成,實現部分的硬件編解碼

其次在ffmpeg中軟件編解碼器可以實現相關硬解加速。如在h264解碼器中可以使用cuda 加速,qsv加速,dxva2 加速,d3d11va加速,opencl加速等。cuda qsv等就是不同公司推出的針對gpu編程的工具包

AV_CODEC_ID_H264;代表是h264編解碼器。而name代表某一個編碼器或解碼器。通常我們使用avcodec_find_decoder(ID)和avcodec_find_encoder(ID)來解碼器和編碼器。默認采用的軟件編解碼。如果我們需要使用硬件編解碼,采用avcodec_find_encoder_by_name(name)和avcodec_find_decoder_by_name(name)來指定編碼器。其他代碼流程與軟件編解碼一致。

	//codec = avcodec_find_decoder(AV_CODEC_ID_H264);
	codec = avcodec_find_decoder_by_name("h264_cuvid");
	if (!codec) {
		fprintf(stderr, "Codec not found\n");
		exit(1);
	}

通過id找到的可能并不是你預期中的編解碼器 通過name找到的一定是你想要的

下面是ffmpeg官方的硬件解碼例子 我加上了中文注釋方便理解

#include <stdio.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext.h>
#include <libavutil/opt.h>
#include <libavutil/avassert.h>
#include <libavutil/imgutils.h>
static AVBufferRef *hw_device_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt;
static FILE *output_file = NULL;
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 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;
	}
	fprintf(stderr, "Failed to get HW surface format.\n");
	return AV_PIX_FMT_NONE;
}
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;
	}
	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) {
			av_frame_free(&frame);
			av_frame_free(&sw_frame);
			return 0;
		}
		else if (ret < 0) {
			fprintf(stderr, "Error while decoding\n");
			goto fail;
		}
		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;
		size = av_image_get_buffer_size(tmp_frame->format, tmp_frame->width,
			tmp_frame->height, 1);
		buffer = av_malloc(size);
		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, 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 main(int argc, char *argv[])
{
	AVFormatContext *input_ctx = NULL;
	int video_stream, ret;
	AVStream *video = NULL;
	AVCodecContext *decoder_ctx = NULL;
	AVCodec *decoder = NULL;
	AVPacket packet;
	enum AVHWDeviceType type;
	int i;
	if (argc < 4) {
		fprintf(stderr, "Usage: %s <device type> <input file> <output file>\n", argv[0]);
		return -1;
	}
	//通過你傳入的名字來找到對應的硬件解碼類型
	type = av_hwdevice_find_type_by_name(argv[1]);
	if (type == AV_HWDEVICE_TYPE_NONE) {
		fprintf(stderr, "Device type %s is not supported.\n", argv[1]);
		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;
	}
	/* open the input file */
	if (avformat_open_input(&input_ctx, argv[2], NULL, NULL) != 0) {
		fprintf(stderr, "Cannot open input file '%s'\n", argv[2]);
		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;
	//去遍歷所有編解碼器支持的硬件解碼配置 如果和之前你指定的是一樣的 那么就可以繼續執行了 不然就找不到
	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 */
	output_file = fopen(argv[3], "w+");
	/* actual decoding and dump the raw data */
	while (ret >= 0) {
		if ((ret = av_read_frame(input_ctx, &packet)) < 0)
			break;
		if (video_stream == packet.stream_index)
			ret = decode_write(decoder_ctx, &packet);
		av_packet_unref(&packet);
	}
	/* flush the decoder */
	packet.data = NULL;
	packet.size = 0;
	ret = decode_write(decoder_ctx, &packet);
	av_packet_unref(&packet);
	if (output_file)
		fclose(output_file);
	avcodec_free_context(&decoder_ctx);
	avformat_close_input(&input_ctx);
	av_buffer_unref(&hw_device_ctx);
	return 0;
}

關鍵函數解析

enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name);

通過傳入的參數查找對應的硬件類型 其中 AVHWDeviceType值如下

const AVCodecHWConfig *avcodec_get_hw_config(const AVCodec *codec, int index);

拿到編解碼器支持的硬件配置比如硬件支持的像素格式等等

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;
	}
	fprintf(stderr, "Failed to get HW surface format.\n");
	return AV_PIX_FMT_NONE;
}

這是一個回調函數,它的作用就是告訴解碼器codec自己的目標像素格式是什么。在上一步驟獲取到了硬解碼器codec可以支持的目標格式之后,就通過這個回調函數告知給codec

  • fmt是這個解碼器codec支持的像素格式,且按照質量優劣進行排序;
  • 如果沒有特別的需要,這個步驟是可以省略的。內部默認會使用“native”的格式。

int av_hwdevice_ctx_create(AVBufferRef **pdevice_ref, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int flags)

這個函數的作用是,創建硬件設備相關的上下文信息AVHWDeviceContext,包括分配內存資源、對硬件設備進行初始化。

準備好硬件設備上下文AVHWDeviceContext后,需要把這個信息綁定到AVCodecContext,就可以像軟解一樣的流程執行解碼操作了。綁定操作如下

注意這里硬件設備信息上下文是通過AVBuffer來存儲的引用 并不是實體

int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags)

這個函數是負責在cpu內存和硬件內存(原文是hw surface)之間做數據交換的。也就是說,它不但可以把數據從硬件surface上搬回系統內存,反向操作也支持;甚至可以直接在硬件內存之間做數據交互。

原文鏈接:https://blog.csdn.net/qq_16401691/article/details/125672624

欄目分類
最近更新