最简单的基于FFmpeg的AVDevice例子(屏幕录制)

=====================================================
最简单的基于FFmpeg的AVDevice例子文章列表:

最简单的基于FFmpeg的AVDevice例子(读取摄像头)

最简单的基于FFmpeg的AVDevice例子(屏幕录制)
=====================================================


FFmpeg中有一个和多媒体设备交互的类库:Libavdevice。使用这个库可以读取电脑的多媒体设备的数据,或者输出数据到指定的多媒体设备上。

计划写2个有关FFmpeg的libavdevice类库的例子。上篇文章记录了一个基于FFmpeg的Libavdevice类库读取摄像头数据的例子。本篇文章记录一个基于FFmpeg的Libavdevice类库录制屏幕的例子。本文程序录制当前桌面内容并且解码显示出来。有关解码显示方面的代码本文不再详述,可以参考文章:
100行代码实现最简单的基于FFMPEG+SDL的视频播放器(SDL1.x)

抓屏方法

上篇文章记录了libavdevice的使用方法,本文不再重复。在Windows系统使用libavdevice抓取屏幕数据有两种方法:gdigrab和dshow。下文分别介绍。
1. gdigrab
gdigrab是FFmpeg专门用于抓取Windows桌面的设备。非常适合用于屏幕录制。它通过不同的输入URL支持两种方式的抓取:
(1)“desktop”:抓取整张桌面。或者抓取桌面中的一个特定的区域。
(2)“title={窗口名称}”:抓取屏幕中特定的一个窗口(目前中文窗口还有乱码问题)。
gdigrab另外还支持一些参数,用于设定抓屏的位置:
offset_x:抓屏起始点横坐标。
offset_y:抓屏起始点纵坐标。
video_size:抓屏的大小。
framerate:抓屏的帧率。
参考的代码如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //Use gdigrab  
  2.  AVDictionary* options = NULL;  
  3.  //Set some options  
  4.  //grabbing frame rate  
  5.  //av_dict_set(&options,"framerate","5",0);  
  6.  //The distance from the left edge of the screen or desktop  
  7.  //av_dict_set(&options,"offset_x","20",0);  
  8.  //The distance from the top edge of the screen or desktop  
  9.  //av_dict_set(&options,"offset_y","40",0);  
  10.  //Video frame size. The default is to capture the full screen  
  11.  //av_dict_set(&options,"video_size","640x480",0);  
  12.  AVInputFormat *ifmt=av_find_input_format("gdigrab");  
  13.  if(avformat_open_input(&pFormatCtx,"desktop",ifmt,&options)!=0){  
  14.   printf("Couldn't open input stream.(无法打开输入流)\n");  
  15.   return -1;  
  16.   }  

2. dshow
使用dshow抓屏需要安装抓屏软件:screen-capture-recorder
软件地址: http://sourceforge.net/projects/screencapturer/
下载软件安装完成后,可以指定dshow的输入设备为“screen-capture-recorder”即可。有关dshow设备的使用方法在上一篇文章中已经有详细叙述,这里不再重复。参考的代码如下:
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AVInputFormat *ifmt=av_find_input_format("dshow");  
  2.  if(avformat_open_input(&pFormatCtx,"video=screen-capture-recorder",ifmt,NULL)!=0){  
  3.   printf("Couldn't open input stream.(无法打开输入流)\n");  
  4.   return -1;  
  5.  }  

注:上述两种抓屏方法也可以直接使用ffmpeg.exe的命令行完成,可以参考文章:

FFmpeg获取DirectShow设备数据(摄像头,录屏)

在Linux下可以使用x11grab抓屏,在MacOS下可以使用avfoundation抓屏,在这里不再详细叙述。

代码

下面直接贴上程序代码:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 最简单的基于FFmpeg的AVDevice例子(屏幕录制) 
  3.  * Simplest FFmpeg Device (Screen Capture) 
  4.  * 
  5.  * 雷霄骅 Lei Xiaohua 
  6.  * leixiaohua1020@126.com 
  7.  * 中国传媒大学/数字电视技术 
  8.  * Communication University of China / Digital TV Technology 
  9.  * http://blog.csdn.net/leixiaohua1020 
  10.  * 
  11.  * 本程序实现了屏幕录制功能。可以录制并播放桌面数据。是基于FFmpeg 
  12.  * 的libavdevice类库最简单的例子。通过该例子,可以学习FFmpeg中 
  13.  * libavdevice类库的使用方法。 
  14.  * 本程序在Windows下可以使用2种方式录制屏幕: 
  15.  *  1.gdigrab: Win32下的基于GDI的屏幕录制设备。 
  16.  *             抓取桌面的时候,输入URL为“desktop”。 
  17.  *  2.dshow: 使用Directshow。注意需要安装额外的软件screen-capture-recorder 
  18.  * 在Linux下可以使用x11grab录制屏幕。 
  19.  * 在MacOS下可以使用avfoundation录制屏幕。 
  20.  * 
  21.  * This software capture screen of computer. It's the simplest example 
  22.  * about usage of FFmpeg's libavdevice Library.  
  23.  * It's suiltable for the beginner of FFmpeg. 
  24.  * This software support 2 methods to capture screen in Microsoft Windows: 
  25.  *  1.gdigrab: Win32 GDI-based screen capture device. 
  26.  *             Input URL in avformat_open_input() is "desktop". 
  27.  *  2.dshow: Use Directshow. Need to install screen-capture-recorder. 
  28.  * It use x11grab to capture screen in Linux. 
  29.  * It use avfoundation to capture screen in MacOS. 
  30.  */  
  31.   
  32.   
  33. #include <stdio.h>  
  34.   
  35. #define __STDC_CONSTANT_MACROS  
  36.   
  37. #ifdef _WIN32  
  38. //Windows  
  39. extern "C"  
  40. {  
  41. #include "libavcodec/avcodec.h"  
  42. #include "libavformat/avformat.h"  
  43. #include "libswscale/swscale.h"  
  44. #include "libavdevice/avdevice.h"  
  45. #include "SDL/SDL.h"  
  46. };  
  47. #else  
  48. //Linux...  
  49. #ifdef __cplusplus  
  50. extern "C"  
  51. {  
  52. #endif  
  53. #include <libavcodec/avcodec.h>  
  54. #include <libavformat/avformat.h>  
  55. #include <libswscale/swscale.h>  
  56. #include <libavdevice/avdevice.h>  
  57. #include <SDL/SDL.h>  
  58. #ifdef __cplusplus  
  59. };  
  60. #endif  
  61. #endif  
  62.   
  63. //Output YUV420P   
  64. #define OUTPUT_YUV420P 0  
  65. //'1' Use Dshow   
  66. //'0' Use GDIgrab  
  67. #define USE_DSHOW 0  
  68.   
  69. //Refresh Event  
  70. #define SFM_REFRESH_EVENT  (SDL_USEREVENT + 1)  
  71.   
  72. int thread_exit=0;  
  73.   
  74. int sfp_refresh_thread(void *opaque)  
  75. {  
  76.     while (thread_exit==0) {  
  77.         SDL_Event event;  
  78.         event.type = SFM_REFRESH_EVENT;  
  79.         SDL_PushEvent(&event);  
  80.         SDL_Delay(40);  
  81.     }  
  82.     return 0;  
  83. }  
  84.   
  85. //Show Dshow Device  
  86. void show_dshow_device(){  
  87.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  88.     AVDictionary* options = NULL;  
  89.     av_dict_set(&options,"list_devices","true",0);  
  90.     AVInputFormat *iformat = av_find_input_format("dshow");  
  91.     printf("========Device Info=============\n");  
  92.     avformat_open_input(&pFormatCtx,"video=dummy",iformat,&options);  
  93.     printf("================================\n");  
  94. }  
  95.   
  96. //Show AVFoundation Device  
  97. void show_avfoundation_device(){  
  98.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  99.     AVDictionary* options = NULL;  
  100.     av_dict_set(&options,"list_devices","true",0);  
  101.     AVInputFormat *iformat = av_find_input_format("avfoundation");  
  102.     printf("==AVFoundation Device Info===\n");  
  103.     avformat_open_input(&pFormatCtx,"",iformat,&options);  
  104.     printf("=============================\n");  
  105. }  
  106.   
  107.   
  108.   
  109. int main(int argc, char* argv[])  
  110. {  
  111.   
  112.     AVFormatContext *pFormatCtx;  
  113.     int             i, videoindex;  
  114.     AVCodecContext  *pCodecCtx;  
  115.     AVCodec         *pCodec;  
  116.       
  117.     av_register_all();  
  118.     avformat_network_init();  
  119.     pFormatCtx = avformat_alloc_context();  
  120.       
  121.     //Open File  
  122.     //char filepath[]="src01_480x272_22.h265";  
  123.     //avformat_open_input(&pFormatCtx,filepath,NULL,NULL)  
  124.   
  125.     //Register Device  
  126.     avdevice_register_all();  
  127.     //Windows  
  128. #ifdef _WIN32  
  129. #if USE_DSHOW  
  130.     //Use dshow  
  131.     //  
  132.     //Need to Install screen-capture-recorder  
  133.     //screen-capture-recorder  
  134.     //Website: http://sourceforge.net/projects/screencapturer/  
  135.     //  
  136.     AVInputFormat *ifmt=av_find_input_format("dshow");  
  137.     if(avformat_open_input(&pFormatCtx,"video=screen-capture-recorder",ifmt,NULL)!=0){  
  138.         printf("Couldn't open input stream.\n");  
  139.         return -1;  
  140.     }  
  141. #else  
  142.     //Use gdigrab  
  143.     AVDictionary* options = NULL;  
  144.     //Set some options  
  145.     //grabbing frame rate  
  146.     //av_dict_set(&options,"framerate","5",0);  
  147.     //The distance from the left edge of the screen or desktop  
  148.     //av_dict_set(&options,"offset_x","20",0);  
  149.     //The distance from the top edge of the screen or desktop  
  150.     //av_dict_set(&options,"offset_y","40",0);  
  151.     //Video frame size. The default is to capture the full screen  
  152.     //av_dict_set(&options,"video_size","640x480",0);  
  153.     AVInputFormat *ifmt=av_find_input_format("gdigrab");  
  154.     if(avformat_open_input(&pFormatCtx,"desktop",ifmt,&options)!=0){  
  155.         printf("Couldn't open input stream.\n");  
  156.         return -1;  
  157.     }  
  158.   
  159. #endif  
  160. #elif defined linux  
  161.     //Linux  
  162.     AVDictionary* options = NULL;  
  163.     //Set some options  
  164.     //grabbing frame rate  
  165.     //av_dict_set(&options,"framerate","5",0);  
  166.     //Make the grabbed area follow the mouse  
  167.     //av_dict_set(&options,"follow_mouse","centered",0);  
  168.     //Video frame size. The default is to capture the full screen  
  169.     //av_dict_set(&options,"video_size","640x480",0);  
  170.     AVInputFormat *ifmt=av_find_input_format("x11grab");  
  171.     //Grab at position 10,20  
  172.     if(avformat_open_input(&pFormatCtx,":0.0+10,20",ifmt,&options)!=0){  
  173.         printf("Couldn't open input stream.\n");  
  174.         return -1;  
  175.     }  
  176. #else  
  177.     show_avfoundation_device();  
  178.     //Mac  
  179.     AVInputFormat *ifmt=av_find_input_format("avfoundation");  
  180.     //Avfoundation  
  181.     //[video]:[audio]  
  182.     if(avformat_open_input(&pFormatCtx,"1",ifmt,NULL)!=0){  
  183.         printf("Couldn't open input stream.\n");  
  184.         return -1;  
  185.     }  
  186. #endif  
  187.   
  188.     if(avformat_find_stream_info(pFormatCtx,NULL)<0)  
  189.     {  
  190.         printf("Couldn't find stream information.\n");  
  191.         return -1;  
  192.     }  
  193.     videoindex=-1;  
  194.     for(i=0; i<pFormatCtx->nb_streams; i++)   
  195.         if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)  
  196.         {  
  197.             videoindex=i;  
  198.             break;  
  199.         }  
  200.     if(videoindex==-1)  
  201.     {  
  202.         printf("Didn't find a video stream.\n");  
  203.         return -1;  
  204.     }  
  205.     pCodecCtx=pFormatCtx->streams[videoindex]->codec;  
  206.     pCodec=avcodec_find_decoder(pCodecCtx->codec_id);  
  207.     if(pCodec==NULL)  
  208.     {  
  209.         printf("Codec not found.\n");  
  210.         return -1;  
  211.     }  
  212.     if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)  
  213.     {  
  214.         printf("Could not open codec.\n");  
  215.         return -1;  
  216.     }  
  217.     AVFrame *pFrame,*pFrameYUV;  
  218.     pFrame=av_frame_alloc();  
  219.     pFrameYUV=av_frame_alloc();  
  220.     //uint8_t *out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));  
  221.     //avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);  
  222.     //SDL----------------------------  
  223.     if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {    
  224.         printf( "Could not initialize SDL - %s\n", SDL_GetError());   
  225.         return -1;  
  226.     }   
  227.     int screen_w=640,screen_h=360;  
  228.     const SDL_VideoInfo *vi = SDL_GetVideoInfo();  
  229.     //Half of the Desktop's width and height.  
  230.     screen_w = vi->current_w/2;  
  231.     screen_h = vi->current_h/2;  
  232.     SDL_Surface *screen;   
  233.     screen = SDL_SetVideoMode(screen_w, screen_h, 0,0);  
  234.   
  235.     if(!screen) {    
  236.         printf("SDL: could not set video mode - exiting:%s\n",SDL_GetError());    
  237.         return -1;  
  238.     }  
  239.     SDL_Overlay *bmp;   
  240.     bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);   
  241.     SDL_Rect rect;  
  242.     rect.x = 0;      
  243.     rect.y = 0;      
  244.     rect.w = screen_w;      
  245.     rect.h = screen_h;    
  246.     //SDL End------------------------  
  247.     int ret, got_picture;  
  248.   
  249.     AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));  
  250.   
  251. #if OUTPUT_YUV420P   
  252.     FILE *fp_yuv=fopen("output.yuv","wb+");    
  253. #endif    
  254.   
  255.     struct SwsContext *img_convert_ctx;  
  256.     img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);   
  257.     //------------------------------  
  258.     SDL_Thread *video_tid = SDL_CreateThread(sfp_refresh_thread,NULL);  
  259.     //  
  260.     SDL_WM_SetCaption("Simplest FFmpeg Grab Desktop",NULL);  
  261.     //Event Loop  
  262.     SDL_Event event;  
  263.   
  264.     for (;;) {  
  265.         //Wait  
  266.         SDL_WaitEvent(&event);  
  267.         if(event.type==SFM_REFRESH_EVENT){  
  268.             //------------------------------  
  269.             if(av_read_frame(pFormatCtx, packet)>=0){  
  270.                 if(packet->stream_index==videoindex){  
  271.                     ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);  
  272.                     if(ret < 0){  
  273.                         printf("Decode Error.\n");  
  274.                         return -1;  
  275.                     }  
  276.                     if(got_picture){  
  277.                         SDL_LockYUVOverlay(bmp);  
  278.                         pFrameYUV->data[0]=bmp->pixels[0];  
  279.                         pFrameYUV->data[1]=bmp->pixels[2];  
  280.                         pFrameYUV->data[2]=bmp->pixels[1];       
  281.                         pFrameYUV->linesize[0]=bmp->pitches[0];  
  282.                         pFrameYUV->linesize[1]=bmp->pitches[2];     
  283.                         pFrameYUV->linesize[2]=bmp->pitches[1];  
  284.                         sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);  
  285.   
  286. #if OUTPUT_YUV420P    
  287.                         int y_size=pCodecCtx->width*pCodecCtx->height;      
  288.                         fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y     
  289.                         fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U    
  290.                         fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V    
  291. #endif    
  292.                         SDL_UnlockYUVOverlay(bmp);   
  293.                           
  294.                         SDL_DisplayYUVOverlay(bmp, &rect);   
  295.   
  296.                     }  
  297.                 }  
  298.                 av_free_packet(packet);  
  299.             }else{  
  300.                 //Exit Thread  
  301.                 thread_exit=1;  
  302.                 break;  
  303.             }  
  304.         }else if(event.type==SDL_QUIT){  
  305.             thread_exit=1;  
  306.             break;  
  307.         }  
  308.   
  309.     }  
  310.   
  311.   
  312.     sws_freeContext(img_convert_ctx);  
  313.   
  314. #if OUTPUT_YUV420P   
  315.     fclose(fp_yuv);  
  316. #endif   
  317.   
  318.     SDL_Quit();  
  319.   
  320.     //av_free(out_buffer);  
  321.     av_free(pFrameYUV);  
  322.     avcodec_close(pCodecCtx);  
  323.     avformat_close_input(&pFormatCtx);  
  324.   
  325.     return 0;  
  326. }  



结果

程序的运行效果如下。这个运行结果还是十分有趣的,会出现一个屏幕“嵌套”在另一个屏幕里面的现象,环环相套。
 
可以通过代码定义的宏来确定是否将解码后的YUV420P数据输出成文件:
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #define OUTPUT_YUV420P 0  

可以通过下面的宏定义来确定使用GDIGrab或者是Dshow打开摄像头:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //'1' Use Dshow   
  2. //'0' Use GDIgrab  
  3. #define USE_DSHOW 0  


下载


Simplest FFmpeg Device 


项目主页

SourceForge:https://sourceforge.net/projects/simplestffmpegdevice/

Github:https://github.com/leixiaohua1020/simplest_ffmpeg_device

开源中国:http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_device


CSDN下载地址:
http://download.csdn.net/detail/leixiaohua1020/7994049

注:
 本工程包含两个基于FFmpeg的libavdevice的例子:
 simplest_ffmpeg_grabdesktop:屏幕录制。
 simplest_ffmpeg_readcamera:读取摄像头


更新-1.1(2015.1.9)=========================================

该版本中,修改了SDL的显示方式,弹出的窗口可以移动了。

CSDN下载地址:http://download.csdn.net/detail/leixiaohua1020/8344695


更新-1.2 (2015.2.13)=========================================

这次考虑到了跨平台的要求,调整了源代码。经过这次调整之后,源代码可以在以下平台编译通过:

VC++:打开sln文件即可编译,无需配置。

cl.exe:打开compile_cl.bat即可命令行下使用cl.exe进行编译,注意可能需要按照VC的安装路径调整脚本里面的参数。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ::VS2010 Environment  
  2. call "D:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"  
  3. ::include  
  4. @set INCLUDE=include;%INCLUDE%  
  5. ::lib  
  6. @set LIB=lib;%LIB%  
  7. ::compile and link  
  8. cl simplest_ffmpeg_grabdesktop.cpp /MD /link SDL.lib SDLmain.lib avcodec.lib ^  
  9. avformat.lib avutil.lib avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib ^  
  10. /SUBSYSTEM:WINDOWS /OPT:NOREF  

MinGW:MinGW命令行下运行compile_mingw.sh即可使用MinGW的g++进行编译。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. g++ simplest_ffmpeg_grabdesktop.cpp -g -o simplest_ffmpeg_grabdesktop.exe \  
  2. -I /usr/local/include -L /usr/local/lib \  
  3. -lmingw32 -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavdevice -lswscale  

GCC(Linux):Linux命令行下运行compile_gcc.sh即可使用GCC进行编译。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. gcc simplest_ffmpeg_grabdesktop.cpp -g -o simplest_ffmpeg_grabdesktop.out \  
  2. -I /usr/local/include -L /usr/local/lib -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavdevice -lswscale  

GCC(MacOS):MacOS命令行下运行compile_gcc_mac.sh即可使用GCC进行编译。Mac的GCC和Linux的GCC差别不大,但是使用SDL1.2的时候,必须加上“-framework Cocoa”参数,否则编译无法通过。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. gcc simplest_ffmpeg_grabdesktop.cpp -g -o simplest_ffmpeg_grabdesktop.out \  
  2. -framework Cocoa -I /usr/local/include -L /usr/local/lib -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavdevice -lswscale  

PS:相关的编译命令已经保存到了工程文件夹中

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值