inti;AVCodecContext*pCodecCtxOrig=NULL;AVCodecContext*pCodecCtx=NULL;//Find the first video streamvideoStream=-1;for(i=0;i<pFormatCtx->nb_streams;i++)if(pFormatCtx->streams[i]->codec->codec_type=AVMEDIA_TYPE_VIDEO){videoStream=i;break;}if(videoStream==-1)return-1;//Didn't find a video stream// Get a pointer to the codec context for the video streampCodecCtxOrig=pFormatCtx->streams[videoStream]->codec;
AVCodec*pCodec=NULL;// Find the decoder for the video streampCodec=avcodec_find_decoder(pCodecCtx->codec_id);if(pCodec==NULL){fprintf(stderr,"Unsupported codec!\n");return-1;// Codec not found}// Copy contextpCodecCtx=avcodec_alloc_context3(pCodec);if(avcodecc_copy_context(pCodecCtx,pCodecCtxOrig)!=0){fprintf(stderr,"Couldn't copy codec context");return-1;// Error copying codec context}//Open codecif(avcodec_open2(pCodecCtx,pCodec)<0)return-1;// Could not open codec
// Assign appropriate parts of buffer to image planes in pFrameRGB// Note that pFrameRGB is an AVFrame, but AVFrame is a superset of AVPictureavpicture_fill((AVPicture*)pFrameRGB,buffer,PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height);
structSwsContext*sws_ctx=NULL;intframeFinished;AVPacketpacket;// initialize SWS context for software scalingsws_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,PIX_FMT_RGB24,SWS_BILINEAR,NULL,NULL,NULL);i=0;while(av_read_frame(pFormatCtx,&packet)>=0){// Is this a packet from the video stream?if(packet.stream_index==videoStream){//Decode video frameavcodec_decode_video2(pCodecCtx,pFrame,&frameFinished,&packet);//Did we get a video frame?if(frameFinished){//Convert the image from its native format to RGBsws_scale(sws_ctx,(uint8_tconst*contst*)pFrame->data,pFrame->linesize,0,pCodecCtx->height,pFrameRGB->data,pFrameRGB->linesize);// Save the frame to diskif(++i<=5)SaveFrame(pFrameRGB,pCodecCtx->widht,pCodecCtx->height,i);}}// Free the packet that was allocated by av_read_frameav_free_packet(&packet);}
//Free the RGB imageav_free(buffer);av_free(pFrameRGB);//Free the YUV frameav_free(pFrame);//Close the codecsavcodec_close(pCodecCtx);avcodec_close(pCodecCtxOrig);//Close the video fileavformat_close_input(&pFormatCtx);return0;