ffmpeg mp4转h264 cpp代码
时间: 2023-10-09 09:05:10 浏览: 170
以下是使用 FFmpeg 将 MP4 文件转换为 H.264 编码的 CPP 代码示例:
```cpp
extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}
int main(int argc, char *argv[])
{
AVFormatContext *pFormatCtx = NULL;
AVCodecContext *pCodecCtxOrig = NULL, *pCodecCtx = NULL;
AVCodec *pCodec = NULL;
AVFrame *pFrame = NULL;
AVPacket packet;
int i, videoStream;
struct SwsContext *sws_ctx = NULL;
// Open the input file
if (avformat_open_input(&pFormatCtx, argv[1], NULL, NULL) != 0)
return -1;
// Retrieve stream information
if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
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)
return -1;
// Get a pointer to the codec context for the video stream
pCodecCtxOrig = pFormatCtx->streams[videoStream]->codec;
pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id);
if (pCodec == NULL)
return -1;
// Copy context
pCodecCtx = avcodec_alloc_context3(pCodec);
if (avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0)
return -1;
// Open codec
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
return -1;
// Allocate video frame
pFrame = av_frame_alloc();
if (pFrame == NULL)
return -1;
// Read frames and save to file
while (av_read_frame(pFormatCtx, &packet) >= 0)
{
// Is this a packet from the video stream?
if (packet.stream_index == videoStream)
{
// Decode video frame
int ret = avcodec_send_packet(pCodecCtx, &packet);
if (ret < 0)
break;
while (ret >= 0)
{
ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
break;
else if (ret < 0)
break;
// Convert the image from its native format to RGB
sws_ctx = sws_getCachedContext(sws_ctx, pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL);
if (!sws_ctx)
return -1;
uint8_t *buffer = (uint8_t *)malloc(pCodecCtx->width * pCodecCtx->height * 3);
if (!buffer)
return -1;
uint8_t *pBuffer[1] = {buffer};
int linesize[1] = {3 * pCodecCtx->width};
int h = sws_scale(sws_ctx, (uint8_t const *const *)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pBuffer, linesize);
if (h > 0)
{
// Write the RGB image to file
FILE *fp = fopen("output.rgb", "ab");
if (fp != NULL)
{
fwrite(buffer, 1, pCodecCtx->width * pCodecCtx->height * 3, fp);
fclose(fp);
}
}
free(buffer);
}
}
// Free the packet that was allocated by av_read_frame
av_packet_unref(&packet);
}
// Free the RGB image
sws_freeContext(sws_ctx);
// Free the YUV frame
av_frame_free(&pFrame);
// Close the codec
avcodec_close(pCodecCtx);
// Close the video file
avformat_close_input(&pFormatCtx);
return 0;
}
```
这段代码将 MP4 文件中的 H.264 视频帧解码为 YUV 格式,然后将其转换为 RGB 格式并写入到文件中。你可以根据实际需求进行修改。
阅读全文