环境:
OS: Windows
IDE: VS 2008
ffmpeg : http://www.bairuitech.com/html/ruanjianxiazai/20080613/98.html
SDL : SDL-devel-1.2.15-VC.zip (Visual C++) http://www.libsdl.org/download-1.2.php
流程图:
// MyTestAll.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" extern "C" { #include "libavformat/avformat.h" #include "libavcodec/avcodec.h" #include "libswscale/swscale.h" #include "SDL.h" } int _tmain(int argc, _TCHAR* argv[]) { char filename[100] = "D:/vs/MyTestAll/mp4.mp4"; AVFormatContext * pAVFCtx = NULL; AVCodecContext * pCodecCtx = NULL ; AVCodec * pCodec = NULL ; SDL_Surface* surface =NULL; UINT videoStream =-1 ; SDL_Rect rect; SDL_Event even; av_register_all(); if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO)) { cout <<SDL_GetError()<<endl; exit(-1); } if(av_open_input_file(&pAVFCtx,filename ,NULL,0,NULL)) { cout << "open file: "<<filename<<"error!"<<endl; exit(-1); } if(av_find_stream_info(pAVFCtx)<0) { exit(-1); } dump_format(pAVFCtx,0,filename,0); for(UINT i=0;i<=pAVFCtx->nb_streams;i++) { if(pAVFCtx->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO ) { videoStream = i; break; } } if(videoStream == -1) exit(-1); pCodecCtx = pAVFCtx->streams[videoStream]->codec ; pCodec = avcodec_find_decoder(pCodecCtx->codec_id); if(avcodec_open(pCodecCtx,pCodec)<0) exit(-1); surface = SDL_SetVideoMode(pCodecCtx->width,pCodecCtx->height,0,0); if(surface == NULL) exit(-1); SDL_Overlay * pOverlay = SDL_CreateYUVOverlay(pCodecCtx->width,pCodecCtx->height ,SDL_YV12_OVERLAY,surface); AVFrame * pFrame; pFrame = avcodec_alloc_frame(); AVPacket packet ; int hasVideo ; while(av_read_frame(pAVFCtx,&packet ) == 0) { if(packet.stream_index ==videoStream) { avcodec_decode_video(pCodecCtx,pFrame,&hasVideo,packet.data,packet.size); if(hasVideo) { SDL_LockYUVOverlay(pOverlay); AVPicture picture; picture.data[0] = pOverlay->pixels[0]; picture.data[1] = pOverlay->pixels[2]; picture.data[2] = pOverlay->pixels[1]; picture.linesize[0] = pOverlay->pitches[0]; picture.linesize[1] = pOverlay->pitches[2]; picture.linesize[2] = pOverlay->pitches[1]; SwsContext *pSwsCtx = sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,PIX_FMT_YUV420P, SWS_BICUBIC,NULL,NULL,NULL); sws_scale(pSwsCtx,pFrame->data,pFrame->linesize,0,pCodecCtx->height,picture.data,picture.linesize); SDL_UnlockYUVOverlay(pOverlay); rect.x = 0; rect.y = 0; rect.h = pCodecCtx->height; rect.w = pCodecCtx->width ; SDL_DisplayYUVOverlay(pOverlay,&rect); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); SDL_PollEvent(&even); switch(even.type) { case SDL_QUIT: SDL_Quit(); exit(0); break; default: break; } } av_free(pFrame); avcodec_close(pCodecCtx); av_close_input_file(pAVFCtx); system("pause"); return 0; }
整个项目的文件,我都上传到资源里去了,可以到我的资源里下载
http://download.csdn.net/detail/rao_warrior/4476533