视频太快FFmpeg

时间:2012-11-22 02:02:40

标签: c++ ffmpeg frame-rate

我再次遇到ffmpeg的问题,我是ffmpeg的新手,我找不到最新的好教程...

这次,当我用ffmpeg播放视频时,它播放得太快,ffmpeg忽略了FPS,我不想用线程睡眠处理它,因为视频有不同的FPS。

我创建了一个线程,在那里你可以找到循环:

AVPacket framepacket;

while(av_read_frame(formatContext,&framepacket)>= 0){
    pausecontrol.lock();

    // Is it a video or audio frame¿?
    if(framepacket.stream_index==gotVideoCodec){
        int framereaded;
        // Video? Ok
        avcodec_decode_video2(videoCodecContext,videoFrame,&framereaded,&framepacket);
        // Yeah, did we get it?
        if(framereaded && doit){
            AVRational millisecondbase = {1,1000};
            int f_number = framepacket.dts;
            int f_time = av_rescale_q(framepacket.dts,formatContext->streams[gotVideoCodec]->time_base,millisecondbase);
            currentTime=f_time;
            currentFrameNumber=f_number;

            int stWidth = videoCodecContext->width;
            int stHeight = videoCodecContext->height;
            SwsContext *ctx = sws_getContext(stWidth, stHeight, videoCodecContext->pix_fmt, stWidth,
            stHeight, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
            if(ctx!=0){
            sws_scale(ctx,videoFrame->data,videoFrame->linesize,0,videoCodecContext->height,videoFrameRGB->data,videoFrameRGB->linesize);
            QImage framecapsule=QImage(stWidth,stHeight,QImage::Format_RGB888);

            for(int y=0;y<stHeight;y++){
                memcpy(framecapsule.scanLine(y),videoFrameRGB->data[0]+y*videoFrameRGB->linesize[0],stWidth*3);
            }
            emit newFrameReady(framecapsule);
            sws_freeContext(ctx);
            }

        }
    }
    if(framepacket.stream_index==gotAudioCodec){
        // Audio? Ok
    }
    pausecontrol.unlock();
    av_free_packet(&framepacket);
}

任何想法?

1 个答案:

答案 0 :(得分:3)

最简单的解决方案是使用基于FPS值的延迟

firstFrame = true;
for(;;)
{
  //  decoding, color conversion, etc.

  if (!firstFrame)
  {
    const double frameDuration = 1000.0 / frameRate;
    duration_t actualDelay = get_local_time() - lastTime;
    if (frameDuration > actualDelay)
      sleep(frameDuration - actualDelay); 
  }
  else
    firstFrame = false;

  emit newFrameReady(framecapsule);

  lastTime = get_local_time();
}

get_local_time()duration_t是抽象的。

更准确的方法是为每个帧使用时间戳,但想法是相同的