ffmpeng 读取h264文件
时间: 2023-10-09 22:11:39 浏览: 52
使用ffmpeg h264解码
要使用FFmpeg读取H.264文件,您需要使用FFmpeg的API。以下是一些基本的代码示例,可以帮助您开始:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>
// FFmpeg libraries
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
int main(int argc, char *argv[]) {
AVFormatContext *pFormatCtx = NULL;
AVCodecContext *pCodecCtx = NULL;
AVCodec *pCodec = NULL;
AVPacket packet;
AVFrame *pFrame = NULL;
int i, videoStream, frameFinished;
struct SwsContext *sws_ctx = NULL;
// Open video file
if (avformat_open_input(&pFormatCtx, argv[1], NULL, NULL) != 0) {
printf("Error: Could not open input file.\n");
return -1;
}
// Retrieve stream information
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
printf("Error: Could not find stream information.\n");
return -1;
}
// Find the first video stream
videoStream = -1;
for (i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
break;
}
}
if (videoStream == -1) {
printf("Error: Could not find video stream.\n");
return -1;
}
// Get a pointer to the codec context for the video stream
pCodecCtx = avcodec_alloc_context3(NULL);
if (pCodecCtx == NULL) {
printf("Error: Could not allocate codec context.\n");
return -1;
}
avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[videoStream]->codecpar);
// Find the decoder for the video stream
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
printf("Error: Unsupported codec.\n");
return -1;
}
// Open codec
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
printf("Error: Could not open codec.\n");
return -1;
}
// Allocate video frame
pFrame = av_frame_alloc();
if (pFrame == NULL) {
printf("Error: Could not allocate video frame.\n");
return -1;
}
// Read frames and convert to RGB
while (av_read_frame(pFormatCtx, &packet) >= 0) {
// Is this a packet from the video stream?
if (packet.stream_index == videoStream) {
// Decode video frame
avcodec_send_packet(pCodecCtx, &packet);
while (avcodec_receive_frame(pCodecCtx, pFrame) == 0) {
// Convert the image from its native format to RGB
sws_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB24,
SWS_BILINEAR, NULL, NULL, NULL);
if (sws_ctx == NULL) {
printf("Error: Could not initialize conversion context.\n");
return -1;
}
sws_scale(sws_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
sws_freeContext(sws_ctx);
}
}
av_packet_unref(&packet);
}
// Free resources
av_frame_free(&pFrame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
return 0;
}
```
这个例子假设您已经安装了FFmpeg,并且具有H.264解码器。如果没有,请先安装FFmpeg和H.264解码器。
阅读全文