FFmpeg —— ffmpeg代码方式将.mp4文件提取保存为.h264文件(附完整源码)
#include <iostream>
extern "C"
{
#include "libavformat/"
#include "libswscale/"
#include "libswresample/"
#include "libavdevice/"
}
int main()
{
const char *srcMedia = "in.mp4";
const char *destMedia = "out.h264";
/***************************************************************/
AVFormatContext *inFormatContext = nullptr;
if (0 != avformat_open_input(&inFormatContext, srcMedia, nullptr, nullptr)) { return -1; }
int vInIndex = av_find_best_stream(inFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
if (vInIndex == AVERROR_STREAM_NOT_FOUND) { return -1; }
AVStream *vInStream = inFormatContext->streams[vInIndex];
if (!vInStream) { return -1; }
AVCodec *inCodec = avcodec_find_encoder(vInStream->codecpar->codec_id);
if (!inCodec) { return -1; }
/***************************************************************/
/***************************************************************/
AVFormatContext *outFormatContext = avformat_alloc_context();
AVOutputFormat *outFormat = av_guess_format(nullptr, destMedia, nullptr);
outFormatContext->oformat = outFormat;
AVStream *vOutStream = avformat_new_stream(outFormatContext, inCodec);
if (!vOutStream) { return-1; }
if (avcodec_parameters_copy(vOutStream->codecpar, vInStream->codecpar) < 0) { return -1; }
vOutStream->codecpar->codec_tag = 0;
/***************************************************************/
avio_open(&outFormatContext->pb, destMedia, AVIO_FLAG_WRITE);
avformat_write_header(outFormatContext, nullptr);
AVPacket *avPacket = av_packet_alloc();
av_init_packet(avPacket);
while (av_read_frame(inFormatContext, avPacket) >= 0)
{
if (avPacket->stream_index == vInIndex)
{
avPacket->stream_index = 0;
av_interleaved_write_frame(outFormatContext, avPacket);
}
av_packet_unref(avPacket);
}
if (avPacket) { av_packet_free(&avPacket); }avPacket = nullptr;
if (inFormatContext) { avformat_close_input(&inFormatContext); }inFormatContext = nullptr;
if (outFormatContext)
{
av_write_trailer(outFormatContext);
avio_close(outFormatContext->pb);
avformat_free_context(outFormatContext);
}
outFormatContext = nullptr;
return 0;
}