ffmpeg解码视频

来源:互联网 发布:mrj频道 知乎 编辑:程序博客网 时间:2024/05/22 08:27

如果有一段不知道编码格式的视频码流,用ffmpeg解码的流程如下:
 av_register_all();
 AVFormatContext *pFormatCtx;
 AVCodecContext *pCodecCtxv;
 AVFrame *m_pFrame;
 AVCodec *pCodecv;
 if (av_open_input_file (&pFormatCtx, "2.mpg", NULL, 0, NULL) != 0){
  return -1;  
 }
 // Retrieve stream information
 if (av_find_stream_info (pFormatCtx) < 0){
  // Couldn't find stream information
  return -1;  
 }
 int  videoStream = -1;
 for (int i = 0; i < pFormatCtx->nb_streams; i++)
 {
  if (pFormatCtx->streams[i]->codec->codec_type ==
   CODEC_TYPE_VIDEO)
  {
   videoStream = i;
  }
 }

 pCodecCtxv = pFormatCtx->streams[videoStream]->codec;
 pCodecv = avcodec_find_decoder(pCodecCtxv->codec_id);
 if (pCodecv == NULL)
  return -1; 

 // pCodecCtxv = avcodec_alloc_context();
 m_pFrame = avcodec_alloc_frame();
 if(NULL==pCodecCtxv ||NULL==m_pFrame)
  return -1;
 if (avcodec_open(pCodecCtxv, pCodecv) < 0)
 {
  return -1;
 }
 AVPacket packet;
 int nWdith = 704; //根据实际情况。
 int nHeight = 576;
 int nFrame = 0;
 
 while (av_read_frame(pFormatCtx, &packet) >= 0 )
 {
  TRACE("nFrame = %d\n",nFrame++);
  int len = -1;
  int uSize = 0;
  int nLen = avcodec_decode_video(pCodecCtxv,m_pFrame,&uSize,packet.data,packet.size);
 // TRACE("解码返回值:%d\n",nLen); 
  if(uSize>0)
  {
   TRACE(" dec suc\n");
   /*LPBYTE PtrY = NULL;  LPBYTE PtrU = NULL;  LPBYTE PtrV = NULL;
   //YUV data linesize
   int    iSizeY = 0;  int iSizeU = 0;   int    iSizeV = 0;
   PtrY = m_pFrame->data[0];   PtrU = m_pFrame->data[1];    PtrV = m_pFrame->data[2];
   iSizeY = m_pFrame->linesize[0]; iSizeU = m_pFrame->linesize[1];  iSizeV = m_pFrame->linesize[2];

   unsigned int i = 0;
   for (i = 0; i < nHeight; i++)
   {
    SaveData(PtrY,nWdith);
    PtrY += iSizeY;
   }

   for (i = 0; i < nHeight/2; i++) 
   {
    SaveData(PtrV,nWdith/2);
    PtrV += iSizeV;
   }

   for (i = 0; i < nHeight/2; i++)
   {
    SaveData(PtrU,nWdith/2);
    PtrU += iSizeU;
   }*/
  }
  else
  {
   TRACE(" dec faild\n");
  }
  av_free_packet(&packet);
 }
 //释放资源省略。
以上代码加上头文件即可,裸h264,裸mepg2,裸mpeg4,含视频的AVI已测过。

0 0