Loading...
Searching...
No Matches
vaapi_encode.c

Perform VAAPI-accelerated encoding.

Perform VAAPI-accelerated encoding. Read input from an NV12 raw file, and write the H.264 encoded data to an output raw file. Usage: vaapi_encode 1920 1080 input.yuv output.h264

/*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @file Intel VAAPI-accelerated encoding API usage example
* @example vaapi_encode.c
*
* Perform VAAPI-accelerated encoding. Read input from an NV12 raw
* file, and write the H.264 encoded data to an output raw file.
* Usage: vaapi_encode 1920 1080 input.yuv output.h264
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <libavcodec/avcodec.h>
#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext.h>
static int width, height;
static AVBufferRef *hw_device_ctx = NULL;
static int set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx)
{
AVBufferRef *hw_frames_ref;
AVHWFramesContext *frames_ctx = NULL;
int err = 0;
if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {
fprintf(stderr, "Failed to create VAAPI frame context.\n");
return -1;
}
frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
frames_ctx->format = AV_PIX_FMT_VAAPI;
frames_ctx->sw_format = AV_PIX_FMT_NV12;
frames_ctx->width = width;
frames_ctx->height = height;
frames_ctx->initial_pool_size = 20;
if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
fprintf(stderr, "Failed to initialize VAAPI frame context."
"Error code: %s\n",av_err2str(err));
av_buffer_unref(&hw_frames_ref);
return err;
}
ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
if (!ctx->hw_frames_ctx)
err = AVERROR(ENOMEM);
av_buffer_unref(&hw_frames_ref);
return err;
}
static int encode_write(AVCodecContext *avctx, AVFrame *frame, FILE *fout)
{
int ret = 0;
AVPacket *enc_pkt;
if (!(enc_pkt = av_packet_alloc()))
return AVERROR(ENOMEM);
if ((ret = avcodec_send_frame(avctx, frame)) < 0) {
fprintf(stderr, "Error code: %s\n", av_err2str(ret));
goto end;
}
while (1) {
ret = avcodec_receive_packet(avctx, enc_pkt);
if (ret)
break;
enc_pkt->stream_index = 0;
ret = fwrite(enc_pkt->data, enc_pkt->size, 1, fout);
av_packet_unref(enc_pkt);
if (!ret) {
ret = AVERROR(errno);
break;
}
}
end:
av_packet_free(&enc_pkt);
ret = ((ret == AVERROR(EAGAIN)) ? 0 : -1);
return ret;
}
int main(int argc, char *argv[])
{
int size, err;
FILE *fin = NULL, *fout = NULL;
AVFrame *sw_frame = NULL, *hw_frame = NULL;
AVCodecContext *avctx = NULL;
const AVCodec *codec = NULL;
const char *enc_name = "h264_vaapi";
if (argc < 5) {
fprintf(stderr, "Usage: %s <width> <height> <input file> <output file>\n", argv[0]);
return -1;
}
width = atoi(argv[1]);
height = atoi(argv[2]);
size = width * height;
if (!(fin = fopen(argv[3], "r"))) {
fprintf(stderr, "Fail to open input file : %s\n", strerror(errno));
return -1;
}
if (!(fout = fopen(argv[4], "w+b"))) {
fprintf(stderr, "Fail to open output file : %s\n", strerror(errno));
err = -1;
goto close;
}
err = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI,
NULL, NULL, 0);
if (err < 0) {
fprintf(stderr, "Failed to create a VAAPI device. Error code: %s\n", av_err2str(err));
goto close;
}
if (!(codec = avcodec_find_encoder_by_name(enc_name))) {
fprintf(stderr, "Could not find encoder.\n");
err = -1;
goto close;
}
if (!(avctx = avcodec_alloc_context3(codec))) {
err = AVERROR(ENOMEM);
goto close;
}
avctx->width = width;
avctx->height = height;
avctx->time_base = (AVRational){1, 25};
avctx->framerate = (AVRational){25, 1};
avctx->sample_aspect_ratio = (AVRational){1, 1};
avctx->pix_fmt = AV_PIX_FMT_VAAPI;
/* set hw_frames_ctx for encoder's AVCodecContext */
if ((err = set_hwframe_ctx(avctx, hw_device_ctx)) < 0) {
fprintf(stderr, "Failed to set hwframe context.\n");
goto close;
}
if ((err = avcodec_open2(avctx, codec, NULL)) < 0) {
fprintf(stderr, "Cannot open video encoder codec. Error code: %s\n", av_err2str(err));
goto close;
}
while (1) {
if (!(sw_frame = av_frame_alloc())) {
err = AVERROR(ENOMEM);
goto close;
}
/* read data into software frame, and transfer them into hw frame */
sw_frame->width = width;
sw_frame->height = height;
sw_frame->format = AV_PIX_FMT_NV12;
if ((err = av_frame_get_buffer(sw_frame, 0)) < 0)
goto close;
if ((err = fread((uint8_t*)(sw_frame->data[0]), size, 1, fin)) <= 0)
break;
if ((err = fread((uint8_t*)(sw_frame->data[1]), size/2, 1, fin)) <= 0)
break;
if (!(hw_frame = av_frame_alloc())) {
err = AVERROR(ENOMEM);
goto close;
}
if ((err = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frame, 0)) < 0) {
fprintf(stderr, "Error code: %s.\n", av_err2str(err));
goto close;
}
if (!hw_frame->hw_frames_ctx) {
err = AVERROR(ENOMEM);
goto close;
}
if ((err = av_hwframe_transfer_data(hw_frame, sw_frame, 0)) < 0) {
fprintf(stderr, "Error while transferring frame data to surface."
"Error code: %s.\n", av_err2str(err));
goto close;
}
if ((err = (encode_write(avctx, hw_frame, fout))) < 0) {
fprintf(stderr, "Failed to encode.\n");
goto close;
}
av_frame_free(&hw_frame);
av_frame_free(&sw_frame);
}
/* flush encoder */
err = encode_write(avctx, NULL, fout);
if (err == AVERROR_EOF)
err = 0;
close:
if (fin)
fclose(fin);
if (fout)
fclose(fout);
av_frame_free(&sw_frame);
av_frame_free(&hw_frame);
avcodec_free_context(&avctx);
av_buffer_unref(&hw_device_ctx);
return err;
}
avcodec.h
Libavcodec external API header.
main
int main(int argc, char *argv[])
Definition avio_list_dir.c:119
width
static int width
Definition demux_decode.c:40
height
static int height
Definition demux_decode.c:40
frame
static AVFrame * frame
Definition demux_decode.c:54
avcodec_open2
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
avcodec_alloc_context3
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
avcodec_find_encoder_by_name
const AVCodec * avcodec_find_encoder_by_name(const char *name)
Find a registered encoder with the specified name.
avcodec_free_context
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
avcodec_receive_packet
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
avcodec_send_frame
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
av_packet_free
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
av_buffer_unref
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
av_buffer_ref
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition error.h:57
av_err2str
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
AVERROR
#define AVERROR(e)
Definition error.h:45
av_frame_get_buffer
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
av_frame_alloc
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
hw_device_ctx
static AVBufferRef * hw_device_ctx
Definition hw_decode.c:45
hwcontext.h
av_hwframe_get_buffer
int av_hwframe_get_buffer(AVBufferRef *hwframe_ctx, AVFrame *frame, int flags)
Allocate a new frame attached to the given AVHWFramesContext.
av_hwframe_ctx_alloc
AVBufferRef * av_hwframe_ctx_alloc(AVBufferRef *device_ctx)
Allocate an AVHWFramesContext tied to a given device context.
av_hwframe_ctx_init
int av_hwframe_ctx_init(AVBufferRef *ref)
Finalize the context before use.
av_hwframe_transfer_data
int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags)
Copy data to or from a hw surface.
av_hwdevice_ctx_create
int av_hwdevice_ctx_create(AVBufferRef **device_ctx, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int flags)
Open a device of the specified type and create an AVHWDeviceContext for it.
AV_HWDEVICE_TYPE_VAAPI
@ AV_HWDEVICE_TYPE_VAAPI
Definition hwcontext.h:31
pixdesc.h
AV_PIX_FMT_NV12
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition pixfmt.h:96
AV_PIX_FMT_VAAPI
@ AV_PIX_FMT_VAAPI
Hardware acceleration through VA-API, data[3] contains a VASurfaceID.
Definition pixfmt.h:126
AVBufferRef
A reference to a data buffer.
Definition buffer.h:82
AVBufferRef::data
uint8_t * data
The data buffer.
Definition buffer.h:90
AVCodecContext
main external API structure.
Definition avcodec.h:439
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:639
AVCodecContext::height
int height
Definition avcodec.h:600
AVCodecContext::width
int width
picture width / height.
Definition avcodec.h:600
AVCodecContext::hw_frames_ctx
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
Definition avcodec.h:1465
AVCodecContext::framerate
AVRational framerate
Definition avcodec.h:559
AVCodecContext::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:624
AVCodecContext::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:543
AVCodec
AVCodec.
Definition codec.h:172
AVFrame
This structure describes decoded (raw) audio or video data.
Definition frame.h:427
AVFrame::data
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:448
AVFrame::width
int width
Definition frame.h:499
AVFrame::height
int height
Definition frame.h:499
AVFrame::format
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition frame.h:514
AVHWFramesContext
This struct describes a set or pool of "hardware" frames (i.e.
Definition hwcontext.h:118
AVHWFramesContext::format
enum AVPixelFormat format
The pixel format identifying the underlying HW surface type.
Definition hwcontext.h:200
AVHWFramesContext::sw_format
enum AVPixelFormat sw_format
The pixel format identifying the actual data layout of the hardware frames.
Definition hwcontext.h:213
AVHWFramesContext::initial_pool_size
int initial_pool_size
Initial size of the frame pool.
Definition hwcontext.h:190
AVHWFramesContext::width
int width
The allocated dimensions of the frames in this pool.
Definition hwcontext.h:220
AVHWFramesContext::height
int height
Definition hwcontext.h:220
AVPacket
This structure stores compressed data.
Definition packet.h:565
AVPacket::stream_index
int stream_index
Definition packet.h:590
AVPacket::size
int size
Definition packet.h:589
AVPacket::data
uint8_t * data
Definition packet.h:588
AVRational
Rational number (pair of numerator and denominator).
Definition rational.h:58
encode_write
static int encode_write(AVCodecContext *avctx, AVFrame *frame, FILE *fout)
Definition vaapi_encode.c:71
set_hwframe_ctx
static int set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx)
Definition vaapi_encode.c:41