首页 > 其他 > 详细

ffmpeg 最简单的视频播放

时间:2014-10-30 13:20:41      阅读:335      评论:0      收藏:0      [点我收藏+]
   网上有很多关于ffmpeg的视频播放版本,但是都相对比较老,而且同步方式很繁琐,效果也不一定是最好,本人自己重现配合SDL实现了一个播放器,仅供参考,实现音视频同步功能。
  先来说下音视频同步:其实并不像网上那些教程说的那么复杂。
  原理是这样的:
  所有文件在出现前其实都是经历了压片操作,就是编码的工作,而在编码的时候,其实video和audio的每一帧都打上了一个叫时间戳的东西,而这个东西的数值你可能会比较奇怪,从ffmpeg中的packet包中可以看到一包video数据中的一帧数据的时间戳是很长的一个数字,你不用对这个有过多的想法它其实就是一个用来记录音频和视频之间有差距的一个标志,比如一帧视频时234545566,音频是123214124,那很明显就是在播放的时候,如果你手上有这两帧的数据, 那你就不能一起将他们送去SDL渲染,而是先播放audio的, 然后video要等上234545566-123214124的时间才可以。
  看吧,很简单,这就是音视频同步的方法和概念。
  好 上代码,其实ffmpeg已经将文件里面的时间戳都解出来放在了每个packet中,可以直接从这里获取,当然,也可以自己通过视频的帧率和audio的帧率自己来计算并从视频起始时间开始叠加计算,但个人认为没这个必要,ffmpeg提供的pts都是比较准确的。
  video的帧率公式: 1/FPS  (FPS=帧率 , 每秒多少帧数据)
  audio的持续时间公式:  其实这里有个问题,播放音频是一个采样一个采样播放的,然而解码出的frame中的采样个数却不是一个,每种格式都有固定的采样数,比如aac=1024,mp3=1152 其实这个不用去记住, 
ffmpeg会根据文件解析的时候就判断出这个数值,直接从AVCodecCtx的frame_size中获取即可。  比如aac: 1024*1.0/44100
通过上面的两个东西不停的一帧一帧的叠加就能算出每帧数据的PTS了。
   

    这个事player的累,主要播放同步功能都在其中   

点击(此处)折叠或打开

  1. player::player():m_pVC(new VideoContext())
  2. {
  3. }

  4. player::~player()
  5. {

  6. }

  7. void player::play()
  8. {

  9. }

  10. void player::pause()
  11. {

  12. }

  13. void player::loadLocalFile(std::string filename)
  14. {
  15.     m_localFileName = filename;
  16.     init();
  17. }

  18. void player::loadStreamingFile()
  19. {

  20. }

  21. bool player::init()
  22. {
  23.     av_register_all();
  24.     SDL_Init(SDL_INIT_EVERYTHING);
  25.     printf("%s\n",m_localFileName.c_str());
  26.     if(avformat_open_input(&(m_pVC->pFormatCtx),m_localFileName.c_str(),NULL,NULL) < 0)
  27.     {
  28.         printf("open input file Error\n");
  29.         return false;
  30.     }
  31.     
  32.     if (avformat_find_stream_info(m_pVC->pFormatCtx, NULL) < 0)
  33.     {
  34.         printf("Could not find stream information\n");
  35.     }
  36.     av_dump_format(m_pVC->pFormatCtx, 0, m_localFileName.c_str(), 0);

  37.     m_pVC->nbStreams = m_pVC->pFormatCtx->nb_streams;
  38.     m_pVC->streams = new AVStream*[m_pVC->nbStreams];
  39.     for(int i = 0;i < m_pVC->nbStreams;i++)
  40.     {
  41.         m_pVC->streams[i] = m_pVC->pFormatCtx->streams[i];
  42.     }

  43.     //默认情况下之取第一个audio和video作为播放源
  44.     if(DEFAULT_AUDIO_AND_VIDEO)
  45.     {    
  46.         for(int i=0; i < m_pVC->nbStreams; i++)
  47.         {
  48.             if(m_pVC->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  49.             {
  50.                 if(m_pVC->pVideoCodecCtx == NULL)
  51.                 {
  52.                     m_pVC->pVideoCodecCtx = m_pVC->streams[i]->codec;
  53.                     m_pVC->videoindex = i;
  54.                 }
  55.             }
  56.             else if(m_pVC->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  57.             {
  58.                 if(m_pVC->pAudioCodecCtx == NULL)
  59.                 {
  60.                     m_pVC->pAudioCodecCtx = m_pVC->streams[i]->codec;
  61.                     m_pVC->audioindex = i;
  62.                 }
  63.             }
  64.             else if(m_pVC->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
  65.             {
  66.                 if(m_pVC->pSubCodecCtx == NULL)
  67.                 {
  68.                     m_pVC->pSubCodecCtx = m_pVC->streams[i]->codec;
  69.                     m_pVC->subindex = i;
  70.                 }
  71.             }
  72.         }
  73.     }
  74.     else
  75.     {

  76.     }
  77.     m_pVC->nbChannels = m_pVC->pAudioCodecCtx->channels;
  78.     m_pVC->audioCodecID = m_pVC->pAudioCodecCtx->codec_id;
  79.     m_pVC->videoCodecID = m_pVC->pVideoCodecCtx->codec_id;

  80.     m_pVC->pVideoDec = avcodec_find_decoder(m_pVC->videoCodecID);
  81.     if(m_pVC->pVideoDec == NULL)
  82.     {
  83.         printf("Can‘t find video dec\n");
  84.         return false;
  85.     }
  86.     if(avcodec_open2(m_pVC->pVideoCodecCtx,m_pVC->pVideoDec,NULL) < 0)
  87.     {
  88.         return false; // Could not open codec
  89.     }
  90.     m_pVC->pAudioDec = avcodec_find_decoder(m_pVC->audioCodecID);
  91.     if(m_pVC->pAudioDec == NULL)
  92.     {
  93.         printf("Can‘t find video dec\n");
  94.         return false;
  95.     }
  96.     if(avcodec_open2(m_pVC->pAudioCodecCtx,m_pVC->pAudioDec,NULL) < 0)
  97.     {
  98.         return false; // Could not open codec
  99.     }

  100.     initVideoDevice(m_pVC);
  101.     initAudioDevice(m_pVC);
  102.     
  103.     m_pVC->pVideoListMutex = SDL_CreateMutex();
  104.     m_pVC->pAudioListMutex = SDL_CreateMutex();
  105.     m_pVC->pSubListMutex = SDL_CreateMutex();
  106.     m_pVC->videoclockMutex = SDL_CreateMutex();
  107.     m_pVC->audioclockMutex = SDL_CreateMutex();
  108.     m_pVC->pVideoListCond = SDL_CreateCond();
  109.     m_pVC->pAudioListCond = SDL_CreateCond();
  110.     m_pVC->pSubListCond = SDL_CreateCond();

  111. }

  112. bool player::initVideoDevice(shared_ptr<VideoContext> pVC)
  113. {
  114.     pVC->videoClockTime = pVC->pFormatCtx->streams[pVC->videoindex]->start_time;
  115.     int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
  116.     flags |= SDL_RESIZABLE;
  117.     pVC->pScrren = SDL_SetVideoMode(pVC->pVideoCodecCtx->width, pVC->pVideoCodecCtx->height, 0, flags);
  118.     if (!pVC->pScrren)
  119.     {
  120.         printf("SDL: could not set video mode - exiting\n");
  121.         return false;
  122.     }
  123.     //AVRational frame_rate = av_guess_frame_rate(pVC->pFormatCtx, pVC->pFormatCtx->streams[pVC->videoindex], NULL);
  124.     //pVC->videoDuration = av_q2d(pVC->pFormatCtx->streams[pVC->videoindex]->r_frame_rate)*av_q2d(pVC->pVideoCodecCtx->time_base);
  125.     SDL_WM_SetCaption("MAOYIKAI PLAYER ^_^", NULL);
  126.     if(!pVC->pBmp)
  127.     {
  128.         SDL_FreeYUVOverlay(pVC->pBmp);
  129.     }
  130.     pVC->pBmp = SDL_CreateYUVOverlay(pVC->pVideoCodecCtx->width,
  131.                                         pVC->pVideoCodecCtx->height,
  132.                                         SDL_IYUV_OVERLAY,
  133.                                         pVC->pScrren);
  134. }

  135. bool player::initAudioDevice(shared_ptr<VideoContext> pVC)
  136. {
  137.     pVC->audioClockTime = pVC->pFormatCtx->streams[pVC->audioindex]->start_time;
  138.     //pVC->audioDuration = 1024.0/pVC->pAudioCodecCtx->sample_rate;
  139.     //pVC->audioDuration = av_q2d(pVC->pFormatCtx->streams[pVC->audioindex]->r_frame_rate)*av_q2d(pVC->pFormatCtx->streams[pVC->audioindex]->time_base);
  140.     SDL_AudioSpec wantspec,spec;
  141.     int m_dwBitsPerSample = 0;
  142.     switch(pVC->pAudioCodecCtx->sample_fmt)
  143.     {
  144.     case AV_SAMPLE_FMT_U8:
  145.         {
  146.             m_dwBitsPerSample = 8;
  147.         }break;
  148.     case AV_SAMPLE_FMT_S16:
  149.         {
  150.             m_dwBitsPerSample = 16;
  151.         }break;
  152.     case AV_SAMPLE_FMT_S32:
  153.         {
  154.             m_dwBitsPerSample = 32;
  155.         }break;
  156.     case AV_SAMPLE_FMT_FLTP:
  157.         {
  158.             m_dwBitsPerSample = 32;
  159.         }break;
  160.     default:
  161.         {
  162.             m_dwBitsPerSample = 0;
  163.         }break;
  164.     }
  165.     wantspec.freq = pVC->pAudioCodecCtx->sample_rate;
  166.     switch(m_dwBitsPerSample)
  167.     {
  168.     case 8:
  169.         wantspec.format = AUDIO_S8;
  170.         break;
  171.     case 16:
  172.         wantspec.format = AUDIO_S16SYS;
  173.         break;
  174.     default:
  175.         wantspec.format = AUDIO_S16SYS;
  176.         break;
  177.     }
  178.     wantspec.channels = pVC->nbChannels;
  179.     wantspec.silence = 0;
  180.     wantspec.samples = pVC->pAudioCodecCtx->frame_size;
  181.     wantspec.callback = fill_audio;
  182.     wantspec.userdata = &(*pVC);

  183.     if(SDL_OpenAudio(&wantspec, &spec) < 0)
  184.     {
  185.         fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
  186.         return false;
  187.     }

  188.     if (spec.format != AUDIO_S16SYS)
  189.     {
  190.         fprintf(stderr, "SDL advised audio format %d is not supported!\n", spec.format);
  191.         return false;
  192.     }
  193.     pVC->pAu_covert = swr_alloc_set_opts(NULL,AV_CH_LAYOUT_STEREO,AV_SAMPLE_FMT_S16,pVC->pAudioCodecCtx->sample_rate,pVC->pAudioCodecCtx->channel_layout,
  194.                                         pVC->pAudioCodecCtx->sample_fmt,pVC->pAudioCodecCtx->sample_rate,0,NULL);
  195.     swr_init(pVC->pAu_covert);
  196.     pVC->out_buffer_size=av_samples_get_buffer_size(NULL,pVC->pAudioCodecCtx->channels ,pVC->pAudioCodecCtx->frame_size,*(pVC->pAudioDec->sample_fmts), 1);
  197.     pVC->out_buffer=(uint8_t *)av_malloc(pVC->out_buffer_size);
  198.     memset(pVC->out_buffer,0,pVC->out_buffer_size);
  199.     SDL_PauseAudio(0);
  200.     return true;
  201. }

  202. void player::fill_audio(void* user_data,Uint8* stream,int len)
  203. {
  204.     VideoContext* pVc = (VideoContext*)user_data;
  205.     SDL_LockMutex(pVc->pAudioListMutex);
  206.     if(pVc->audioList.empty())
  207.     {
  208.         if(pVc->frameEof == 1)
  209.         {
  210.             printf("audio is play over\n");
  211.             SDL_UnlockMutex(pVc->pAudioListMutex);
  212.             
  213.             if(pVc->videoList.empty())
  214.             {
  215.                 SDL_Event evt;
  216.                 evt.type = SDL_QUIT;
  217.                 SDL_PushEvent(&evt);
  218.             }
  219.             SDL_CloseAudio();
  220.             return ;
  221.         }
  222.         SDL_UnlockMutex(pVc->pAudioListMutex);
  223.         SDL_CondWait(pVc->pAudioListCond,NULL);
  224.         SDL_LockMutex(pVc->pAudioListMutex);
  225.     }
  226.     AVPacket *tmppkt = pVc->audioList.front();
  227.     if(!tmppkt)
  228.     {
  229.         printf("not include availble audio data\n");
  230.         return ;
  231.     }
  232.     SDL_UnlockMutex(pVc->pAudioListMutex);
  233.     AVFrame* pFrame = NULL;
  234.     int got_picture = 0,ret = 0;
  235.     pFrame=avcodec_alloc_frame();
  236.     ret = avcodec_decode_audio4( pVc->pAudioCodecCtx, pFrame,&got_picture, tmppkt);
  237.     if(ret < 0)
  238.     {
  239.         printf("Error in decoding audio frame.\n");
  240.         return ;
  241.     }
  242.     printf("-------audio clock time is %f\n",pVc->audioClockTime);
  243.     if(got_picture > 0)
  244.     {
  245.         //pVc->audioClockTime = tmppkt->pts * av_q2d(pVc->pFormatCtx->streams[pVc->audioindex]->time_base);
  246.         pVc->audioClockTime += pVc->pAudioCodecCtx->frame_size*1.0/pVc->pAudioCodecCtx->sample_rate; //tmppkt->duration*av_q2d(pVc->pFormatCtx->streams[pVc->audioindex]->time_base);
  247.         swr_convert(pVc->pAu_covert,&(pVc->out_buffer), pVc->out_buffer_size,(const uint8_t **)pFrame->data , pFrame->nb_samples);
  248.     }
  249.     else
  250.     {
  251.         memset(pVc->out_buffer,0,pVc->out_buffer_size);
  252.         SDL_LockMutex(pVc->pAudioListMutex);
  253.         pVc->audioList.pop_front();
  254.         SDL_UnlockMutex(pVc->pAudioListMutex);
  255.         return ;
  256.     }

  257.     memcpy(stream, (uint8_t*)(pVc->out_buffer),len);
  258.     memset(pVc->out_buffer,0,pVc->out_buffer_size);

  259.     SDL_LockMutex(pVc->pAudioListMutex);
  260.     pVc->audioList.pop_front();
  261.     SDL_UnlockMutex(pVc->pAudioListMutex);
  262.     av_free_packet(tmppkt);
  263.     avcodec_free_frame(&pFrame);

  264. }

  265. int player::readVideo(void* user_data)
  266. {    
  267.     VideoContext* pVc = (VideoContext*)user_data;
  268.     AVFrame * pFrame = NULL;
  269.     pFrame = avcodec_alloc_frame();
  270.     pVc->pDecodeVideoFrame = pFrame;
  271.     int frameFinished = 0,ret = 0;
  272.     while(1)
  273.     {
  274.         SDL_LockMutex(pVc->pVideoListMutex);
  275.         if(pVc->videoList.empty())
  276.         {
  277.             if(pVc->frameEof == 1)
  278.             {
  279.                 printf("video is play over\n");
  280.                 SDL_UnlockMutex(pVc->pVideoListMutex);
  281.                 return 0;
  282.             }
  283.             SDL_UnlockMutex(pVc->pVideoListMutex);
  284.             SDL_CondWait(pVc->pVideoListCond,NULL);
  285.             SDL_LockMutex(pVc->pVideoListMutex);
  286.         }
  287.         AVPacket *tmppkt = pVc->videoList.front();
  288.         if(!tmppkt)
  289.         {
  290.             printf("can‘t get packet data of video\n");
  291.             return 0;
  292.         }
  293.         SDL_UnlockMutex(pVc->pVideoListMutex);
  294.         ret = avcodec_decode_video2(pVc->pVideoCodecCtx, pFrame, &frameFinished,tmppkt);
  295.         if(ret < 0)
  296.         {
  297.             continue;
  298.         }
  299.     
  300.         printf("++++++++video clock time is %f\n",pVc->videoClockTime);

  301.          if(frameFinished)
  302.         {    
  303.             //pVc->videoClockTime = tmppkt->pts * av_q2d(pVc->pFormatCtx->streams[pVc->videoindex]->time_base);
  304.             pVc->videoClockTime += 1.0/av_q2d(pVc->pFormatCtx->streams[pVc->videoindex]->r_frame_rate);//tmppkt->duration * av_q2d(pVc->pFormatCtx->streams[pVc->videoindex]->time_base);
  305.             AVFrame * pOutputFrame = NULL;
  306.             struct SwsContext * img_convert_ctx;
  307.             pOutputFrame = avcodec_alloc_frame();

  308.             SDL_LockYUVOverlay(pVc->pBmp);

  309.             pOutputFrame->data[0] = pVc->pBmp->pixels[0];
  310.             pOutputFrame->data[1] = pVc->pBmp->pixels[1];
  311.             pOutputFrame->data[2] = pVc->pBmp->pixels[2];

  312.             pOutputFrame->linesize[0] = pVc->pBmp->pitches[0];
  313.             pOutputFrame->linesize[1] = pVc->pBmp->pitches[1];
  314.             pOutputFrame->linesize[2] = pVc->pBmp->pitches[2];

  315.             img_convert_ctx = sws_getContext(pFrame->width,pFrame->height, pVc->pFormatCtx->streams[pVc->videoindex]->codec->pix_fmt,
  316.                 pVc->pVideoCodecCtx->width,pVc->pVideoCodecCtx->height,AV_PIX_FMT_YUV420P,SWS_BICUBIC, NULL,NULL,NULL);
  317.             if(img_convert_ctx == NULL)
  318.             {
  319.                 fprintf(stderr, "Cannot initialize the conversion context!\n");
  320.                 getchar();
  321.             }
  322.             // 将图片转换为RGB格式
  323.             sws_scale(img_convert_ctx,pFrame->data,pFrame->linesize,0,
  324.                 pFrame->height,pOutputFrame->data,pOutputFrame->linesize);
  325.         
  326.             SDL_UnlockYUVOverlay(pVc->pBmp);

  327.             double time = 0;
  328.             if((pVc->videoClockTime - pVc->audioClockTime)*1000 > 0)
  329.             {
  330.                 time = (pVc->videoClockTime - pVc->audioClockTime)*1000;
  331.             }
  332.             else if((pVc->videoClockTime - pVc->audioClockTime)*1000 <= 0)
  333.             {
  334.                 time = 0;
  335.             }        
  336.             Sleep(time);
  337.             SDL_AddTimer(0,showVideo,&(*pVc));
  338.             avcodec_free_frame(&pOutputFrame);
  339.         }
  340.         else
  341.         {
  342.             printf("can‘t decode frame , lost frame\n");
  343.             pVc->videoClockTime += 1.0/av_q2d(pVc->pFormatCtx->streams[pVc->videoindex]->r_frame_rate);
  344.             //pVc->videoClockTime += tmppkt->duration*av_q2d(pVc->pFormatCtx->streams[pVc->videoindex]->time_base);//pVc->videoDuration;
  345.         }
  346.         av_free_packet(tmppkt);
  347.         //avcodec_free_frame(&pFrame);
  348.         SDL_LockMutex(pVc->pVideoListMutex);
  349.         pVc->videoList.pop_front();
  350.         SDL_UnlockMutex(pVc->pVideoListMutex);
  351.     }
  352. }

  353. Uint32 player::showVideo(Uint32 interval, void *param)
  354. {
  355.     VideoContext *data = (VideoContext*)param;
  356.     SDL_Rect rect;
  357.     rect.x = 0;
  358.     rect.y = 0;
  359.     rect.w = data->pVideoCodecCtx->width;
  360.     rect.h = data->pVideoCodecCtx->height;
  361.     SDL_DisplayYUVOverlay(data->pBmp, &rect);
  362.     return 0;
  363. }

  364. int player::readFrame(void* user_data)
  365. {
  366.     VideoContext* pVc = (VideoContext*)user_data;
  367.     while(1)
  368.     {
  369.         AVPacket *pkt = new AVPacket;
  370.         av_init_packet(pkt);
  371.         if(av_read_frame(pVc->pFormatCtx,pkt))
  372.         {
  373.             printf("read frame error or End of File\n");
  374.             pVc->frameEof = 1;
  375.             return 0;
  376.         }
  377.         if(pkt->stream_index == pVc->videoindex)
  378.         {
  379.             SDL_LockMutex(pVc->pVideoListMutex);
  380.             pVc->videoList.push_back(pkt);
  381.             SDL_CondSignal(pVc->pVideoListCond);
  382.             SDL_UnlockMutex(pVc->pVideoListMutex);
  383.         }
  384.         else if(pkt->stream_index == pVc->audioindex)
  385.         {
  386.             SDL_LockMutex(pVc->pAudioListMutex);
  387.             pVc->audioList.push_back(pkt);
  388.             SDL_CondSignal(pVc->pAudioListCond);
  389.             SDL_UnlockMutex(pVc->pAudioListMutex);
  390.         }
  391.         else if(pkt->stream_index == pVc->subindex)
  392.         {
  393.             SDL_LockMutex(pVc->pSubListMutex);
  394.             pVc->subList.push_back(pkt);
  395.             SDL_UnlockMutex(pVc->pSubListMutex);
  396.         }
  397.     }
  398. }

  399. void player::freeMem()
  400. {
  401.     avcodec_free_frame(&(m_pVC->pDecodeVideoFrame));
  402. }

  403. void player::load()
  404. {
  405.     m_pVC->read_tid = SDL_CreateThread(readFrame,&(*m_pVC));
  406.     m_pVC->videoPlay_tid = SDL_CreateThread(readVideo,&(*m_pVC));
  407. }
main函数

点击(此处)折叠或打开

  1. int main()
  2. {
  3.     player test;
  4.     test.loadLocalFile("E:\\C++Learning\\FFMPEG_SDL_WIN32_PLAYER_by_nick\\FLV_STREAM\\5.mp4");
  5.     test.load();
  6.     SDL_Event evt;
  7.     while ( 1 )
  8.     {
  9.         SDL_WaitEvent(&evt);
  10.         switch (evt.type)
  11.         {
  12.         case SDL_KEYDOWN:
  13.             {
  14.                 switch(evt.key.keysym.sym)
  15.                 {
  16.                 case SDLK_p:
  17.                     {
  18.                         printf("Print a Screen shoot\n");
  19.                     }break;
  20.                 }
  21.             }break;
  22.         case SDL_MOUSEMOTION:
  23.             break;
  24.         case SDL_MOUSEBUTTONDOWN:
  25.             break;
  26.         case SDL_QUIT:
  27.             {
  28.                 test.freeMem();
  29.                 exit(0);
  30.             }
  31.         }
  32.     }
  33.     return 0;
  34. }

代码地址:https://www.dropbox.com/sh/xr6n35e2utpe8vo/AACjsv1JgqATmwhpht9lMhI7a?dl=0

ffmpeg 最简单的视频播放

原文:http://blog.chinaunix.net/uid-24922718-id-4548972.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!