繁体   English   中英

ffmpeg如何有效地解码视频帧?

[英]ffmpeg how to efficiently decode the video frame?

这是我用来在工作线程中解码rtsp流的代码:

while(1)
   {
      // Read a frame
      if(av_read_frame(pFormatCtx, &packet)<0)
         break;                             // Frame read failed (e.g. end of stream)

      if(packet.stream_index==videoStream)
      {
         // Is this a packet from the video stream -> decode video frame

         int frameFinished;
         avcodec_decode_video2(pCodecCtx,pFrame,&frameFinished,&packet);

         // Did we get a video frame?
         if (frameFinished)
         {
             if (LastFrameOk == false)
             {
                 LastFrameOk = true;
             }

             // Convert the image format (init the context the first time)
             int w = pCodecCtx->width;
             int h = pCodecCtx->height;
             img_convert_ctx = ffmpeg::sws_getCachedContext(img_convert_ctx, w, h, pCodecCtx->pix_fmt, w, h, ffmpeg::PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);

             if (img_convert_ctx == NULL)
             {
                 printf("Cannot initialize the conversion context!\n");
                 return false;
             }
             ffmpeg::sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);

             // Convert the frame to QImage
             LastFrame = QImage(w, h, QImage::Format_RGB888);

             for (int y = 0; y < h; y++)
                 memcpy(LastFrame.scanLine(y), pFrameRGB->data[0] + y*pFrameRGB->linesize[0], w * 3);

             LastFrameOk = true;


         }  // frameFinished
      }  // stream_index==videoStream
      av_free_packet(&packet);      // Free the packet that was allocated by av_read_frame
   }

我按照ffmpeg的教程进行操作,并使用while循环读取数据包并对视频进行解码。 但是,是否有更有效的方法来执行此操作,例如接收到数据包时的事件触发功能?

我还没有看到任何事件驱动的读取帧的方法,但是读取RTSP流的目的是什么? 但是我可以提出一些建议来提高性能。 首先,您可以在循环中添加一个非常短的睡眠(例如Sleep(1);)。 在您的程序中,如果您的目的是:

  1. 向用户显示图像:不要使用RGB转换,解码后得到的帧为YUV420P格式,可以使用GPU直接显示给用户,而无需占用CPU。 几乎所有图形卡都支持YUV420P(或YV12)格式。 转换为RGB是一项非常消耗CPU的操作,尤其是对于大图像。

  2. 记录(保存)到磁盘:我要记录流以供以后播放,而无需解码帧。 您可以使用OpenRTSP直接记录到磁盘上,而无需占用任何CPU资源。

  3. 处理实时图像:您可能会找到替代算法来处理YUV420P格式而不是RGB。 YUV420P中的Y平面实际上是彩色RGB图像的灰度版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM