AVFormatContext* formatContext = avformat_alloc_context();
if (avformat_open_input(&formatContext, "4k.mp4", NULL, NULL) != 0) {
fprintf(stderr, "Error opening input file.\n");
if (avformat_find_stream_info(formatContext, NULL) < 0) {
fprintf(stderr, "Error finding stream information.\n");
av_dump_format(formatContext, 0, "4k.mp4", 0);
AVCodecContext* codecContext = NULL;
int videoStreamIndex = -1;
for (int i = 0; i < formatContext->nb_streams; i++) {
if (formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
codec = avcodec_find_decoder(formatContext->streams[i]->codecpar->codec_id);
codecContext = avcodec_alloc_context3(codec);
avcodec_parameters_to_context(codecContext, formatContext->streams[i]->codecpar);
avcodec_open2(codecContext, codec, NULL);
AVFrame* frame = av_frame_alloc();
AVFrame* frameRGB = av_frame_alloc();
struct SwsContext* swsContext = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt, codecContext->width, codecContext->height, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
while (av_read_frame(formatContext, &packet) >= 0) {
if (packet.stream_index == videoStreamIndex) {
int response = avcodec_send_packet(codecContext, &packet);
fprintf(stderr, "Error decoding frame.\n");
response = avcodec_receive_frame(codecContext, frame);
if (response == AVERROR(EAGAIN) || response == AVERROR_EOF) {
fprintf(stderr, "Error decoding frame.\n");
av_image_alloc(frameRGB->data, frameRGB->linesize, codecContext->width, codecContext->height, AV_PIX_FMT_YUV420P, 1);
sws_scale(swsContext, (uint8_t const* const*)frame->data, frame->linesize, 0, codecContext->height, frameRGB->data, frameRGB->linesize);
FILE* yuvFile = fopen("4k.yuv", "wb");
fwrite(frameRGB->data[0], 1, codecContext->width * codecContext->height, yuvFile);
fwrite(frameRGB->data[1], 1, codecContext->width * codecContext->height / 4, yuvFile);
fwrite(frameRGB->data[2], 1, codecContext->width * codecContext->height / 4, yuvFile);
av_frame_unref(frameRGB);
av_packet_unref(&packet);
av_frame_free(&frameRGB);
avcodec_free_context(&codecContext);
avformat_close_input(&formatContext);
avformat_free_context(formatContext);
sws_freeContext(swsContext);
