av_register_all();
avformat_network_init();
AVFormatContext* pFormatContext = avformat_alloc_context();
if (avformat_open_input(&pFormatContext, "D:\\video\\cuc_ieschool.flv", NULL, NULL) != 0){
MessageBox(L"avformat_open_input failed", L"提示", MB_OK);
return ;
}
if (avformat_find_stream_info(pFormatContext, NULL) < 0){
MessageBox(L"avformat_find_stream_info failed", L"提示", MB_OK);
return;
}
DWORD dwVideoType = -1;
for (int i = 0; i < pFormatContext->nb_streams; i++){
if (pFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
dwVideoType = i;
break;
}
}
AVCodecContext *pCodecContext = pFormatContext->streams[dwVideoType]->codec;
AVCodec *pCodec = avcodec_find_decoder(pCodecContext->codec_id);
if (avcodec_open2(pCodecContext, pCodec, NULL) != 0){
avformat_close_input(&pFormatContext);
MessageBox(L"avcodec_open2 failed", L"提示", MB_OK);
return;
}
int nGot = 0;
AVFrame *pFrame = av_frame_alloc();
AVFrame *pRGB = av_frame_alloc();
AVPacket *pPacket = (AVPacket*)av_malloc(sizeof(AVPacket));
int nPicSize = avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecContext->width, pCodecContext->height);
uint8_t *buf = (uint8_t*)av_malloc(nPicSize);
if (buf == NULL){
printf("av malloc failed!\n");
exit(1);
}
avpicture_fill((AVPicture *)pRGB, buf, AV_PIX_FMT_YUV420P, pCodecContext->width, pCodecContext->height);
FILE *fp;
char filename[255] = {0};
//文件存放路径,根据自己的修改
sprintf_s(filename, 255, "%s_%d.yuv", "D:\\", 0);
if ((fp = fopen(filename, "wb+")) == NULL){
return;
}
SwsContext* pSws = sws_getContext(pCodecContext->width, pCodecContext->height, pCodecContext->pix_fmt, pCodecContext->width, pCodecContext->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
while (true){
if (av_read_frame(pFormatContext, pPacket) >= 0){
if (pPacket->stream_index == dwVideoType){
if (avcodec_decode_video2(pCodecContext, pFrame, &nGot, pPacket) < 0){
break;
}
if(nGot){
int nRet = sws_scale(pSws, pFrame->data, pFrame->linesize, 0, pCodecContext->height, pRGB->data, pRGB->linesize);
fwrite(pRGB->data[0], (pCodecContext->width)*(pCodecContext->height), 1, fp);
fwrite(pRGB->data[1], (pCodecContext->width)*(pCodecContext->height) / 4, 1, fp);
fwrite(pRGB->data[2], (pCodecContext->width)*(pCodecContext->height) / 4, 1, fp);
}
}
}
else{
break;
}
}
fclose(fp);
sws_freeContext(pSws);
av_free(pFrame);
av_free(pRGB);
av_free(buf);
av_free(pPacket);
avcodec_close(pCodecContext);
avformat_close_input(&pFormatContext);
ffmpeg 将flv转yuv
最新推荐文章于 2024-01-02 20:21:36 发布