1
#define __STDCPP_WANT_MATH_SPEC_FUNCS__ 1
7
#include <libavcodec/avcodec.h>
8
#include <libavformat/avformat.h>
9
#include <libswscale/swscale.h>
13
const char* filename = "test.mp4";
16
std::ifstream file(filename);
18
std::cout << "File does not exist: " << filename << std::endl;
23
avformat_network_init();
25
AVFormatContext* pFormatContext = nullptr;
26
int ret = avformat_open_input(&pFormatContext, filename, nullptr, nullptr);
29
av_strerror(ret, errbuf, sizeof(errbuf));
30
std::cout << "Error opening video file: " << errbuf << std::endl;
34
if (avformat_find_stream_info(pFormatContext, nullptr) < 0) {
35
std::cout << "Error finding stream information" << std::endl;
39
int videoStreamIndex = av_find_best_stream(pFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
40
if (videoStreamIndex < 0) {
41
std::cout << "No video stream found" << std::endl;
45
AVCodecParameters* pCodecParameters = pFormatContext->streams[videoStreamIndex]->codecpar;
46
AVCodec* pCodec = avcodec_find_decoder(pCodecParameters->codec_id);
47
if (pCodec == nullptr) {
48
std::cout << "Unsupported codec" << std::endl;
52
AVCodecContext* pCodecContext = avcodec_alloc_context3(pCodec);
53
if (avcodec_parameters_to_context(pCodecContext, pCodecParameters) < 0) {
54
std::cout << "Failed to copy codec parameters to codec context" << std::endl;
58
if (avcodec_open2(pCodecContext, pCodec, nullptr) < 0) {
59
std::cout << "Failed to open codec" << std::endl;
63
AVFrame* pFrame = av_frame_alloc();
64
if (pFrame == nullptr) {
65
std::cout << "Failed to allocate frame" << std::endl;
70
while (av_read_frame(pFormatContext, &packet) >= 0) {
71
if (packet.stream_index == videoStreamIndex) {
72
if (avcodec_send_packet(pCodecContext, &packet) < 0) {
73
std::cout << "Error sending packet for decoding" << std::endl;
77
while (avcodec_receive_frame(pCodecContext, pFrame) == 0) {
79
std::cout << "Frame decoded: " << pFrame->width << "x" << pFrame->height << std::endl;
82
av_packet_unref(&packet);
85
av_frame_free(&pFrame);
86
avcodec_free_context(&pCodecContext);
87
avformat_close_input(&pFormatContext);
88
avformat_network_deinit();