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

个人学习本文的目的主要是想想了解视频聊天软件中的视频聊天,虽然前两天已经成功调用了opencv的视频播放。但是那个opencv毕竟是用来做视频分析用。而ffmpeg虽然大部分工作在于转码和编码用,但是也调用下。


原文地址:http://blog.csdn.net/leixiaohua1020/article/details/39702113

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

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

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

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

Libavdevice支持以下设备作为输入端:

alsa
avfoundation
bktr
dshow
dv1394
fbdev
gdigrab
iec61883
jack
lavfi
libcdio
libdc1394
openal
oss
pulse
qtkit
sndio
video4linux2, v4l2
vfwcap
x11grab
decklink

Libavdevice支持以下设备作为输出端:

alsa
caca
decklink
fbdev
opengl
oss
pulse
sdl
sndio
xv

libavdevice使用

计划记录两个基于FFmpeg的libavdevice类库的例子,分成两篇文章写。本文记录一个基于FFmpeg的Libavdevice类库读取摄像头数据的例子。下一篇文章记录一个基于FFmpeg的Libavdevice类库录制屏幕的例子。本文程序读取计算机上的摄像头的数据并且解码显示出来。有关解码显示方面的代码本文不再详述,可以参考文章:

100行代码实现最简单的基于FFMPEG+SDL的视频播放器(SDL1.x)

本文主要记录使用libavdevice需要注意的步骤。

首先,使用libavdevice的时候需要包含其头文件:

  1. #include "libavdevice/avdevice.h"  
然后,在程序中需要注册libavdevice:

  1. avdevice_register_all();  

接下来就可以使用libavdevice的功能了。

使用libavdevice读取数据和直接打开视频文件比较类似。因为系统的设备也被FFmpeg认为是一种输入的格式(即AVInputFormat)。使用FFmpeg打开一个普通的视频文件使用如下函数:

  1. AVFormatContext *pFormatCtx = avformat_alloc_context();  
  2. avformat_open_input(&pFormatCtx, "test.h265",NULL,NULL); 
使用libavdevice的时候,唯一的不同在于需要首先查找用于输入的设备。在这里使用av_find_input_format()完成:

  1. AVFormatContext *pFormatCtx = avformat_alloc_context();  
  2. AVInputFormat *ifmt=av_find_input_format("vfwcap");  
  3. avformat_open_input(&pFormatCtx, 0, ifmt,NULL); 
上述代码首先指定了vfw设备作为输入设备,然后在URL中指定打开第0个设备(在我自己计算机上即是摄像头设备)。
在Windows平台上除了使用vfw设备作为输入设备之外,还可以使用DirectShow作为输入设备:
  1. AVFormatContext *pFormatCtx = avformat_alloc_context();  
  2. AVInputFormat *ifmt=av_find_input_format("dshow");  
  3. avformat_open_input(&pFormatCtx,"video=Integrated Camera",ifmt,NULL) ;  

使用ffmpeg.exe打开vfw设备和Directshow设备的方法可以参考文章:

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

注意事项

1. URL的格式是"video={设备名称}",但是设备名称外面不能加引号。例如在上述例子中URL是"video=Integrated Camera",而不能写成"video=\"Integrated Camera\"",否则就无法打开设备。这与直接使用ffmpeg.exe打开dshow设备(命令为: ffmpeg -list_options true -f dshow -i video="Integrated Camera")有很大的不同。
2. Dshow的设备名称必须要提前获取,在这里有两种方法:

(1) 通过FFmpeg编程实现。使用如下代码:

  1. //Show Device  
  2. void show_dshow_device(){  
  3.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  4.     AVDictionary* options = NULL;  
  5.     av_dict_set(&options,"list_devices","true",0);  
  6.     AVInputFormat *iformat = av_find_input_format("dshow");  
  7.     printf("Device Info=============\n");  
  8.     avformat_open_input(&pFormatCtx,"video=dummy",iformat,&options);  
  9.     printf("========================\n");  
  10. }  

上述代码实际上相当于输入了下面一条命令:

  1. ffmpeg -list_devices true -f dshow -i dummy   

执行的结果如下图所示:

 

该方法好处是可以使用程序自动获取名称。但是当设备名称中包含中文字符的时候,会出现设备名称为乱码的情况。如果直接把乱码的设备名作为输入的话,是无法打开该设备的。这时候需要把乱码ANSI转换为UTF-8。例如上图中的第一个音频设备显示为“鍐呰楹﹀厠椋?(Conexant 20672 SmartAudi”,转码之后即为“内装麦克风 (Conexant 20672 SmartAudi”。使用转码之后的名称即可打开该设备。

(2) 自己去系统中看。
这个方法更简单一些,但是缺点是需要手工操作。该方法使用DirectShow的调试工具GraphEdit(或者网上下一个GraphStudioNext)即可查看输入名称。
打开GraphEdit选择“图像->插入滤镜”

 
然后就可以通过查看Audio Capture Sources来查看音频输入设备的简体中文名称了。从图中可以看出是“内装麦克风 (Conexant 20672 SmartAudi”。

 


在Linux平台上可以使用video4linux2打开视频设备;在MacOS上,可以使用avfoundation打开视频设备,这里不再详述。


代码

下面直接贴上程序代码:

  1. /** 
  2.  * 最简单的基于FFmpeg的AVDevice例子(读取摄像头) 
  3.  * Simplest FFmpeg Device (Read Camera) 
  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.VFW: Video for Windows 屏幕捕捉设备。注意输入URL是设备的序号, 
  16.  *          从0至9。 
  17.  *  2.dshow: 使用Directshow。注意作者机器上的摄像头设备名称是 
  18.  *         “Integrated Camera”,使用的时候需要改成自己电脑上摄像头设 
  19.  *          备的名称。 
  20.  * 在Linux下可以使用video4linux2读取摄像头设备。 
  21.  * 在MacOS下可以使用avfoundation读取摄像头设备。 
  22.  * 
  23.  * This software read data from Computer's Camera and play it. 
  24.  * It's the simplest example about usage of FFmpeg's libavdevice Library.  
  25.  * It's suiltable for the beginner of FFmpeg. 
  26.  * This software support 2 methods to read camera in Microsoft Windows: 
  27.  *  1.gdigrab: VfW (Video for Windows) capture input device. 
  28.  *             The filename passed as input is the capture driver number, 
  29.  *             ranging from 0 to 9. 
  30.  *  2.dshow: Use Directshow. Camera's name in author's computer is  
  31.  *             "Integrated Camera". 
  32.  * It use video4linux2 to read Camera in Linux. 
  33.  * It use avfoundation to read Camera in MacOS. 
  34.  *  
  35.  */  
  36.   
  37.   
  38. #include <stdio.h>  
  39.   
  40. #define __STDC_CONSTANT_MACROS  
  41.   
  42. #ifdef _WIN32  
  43. //Windows  
  44. extern "C"  
  45. {  
  46. #include "libavcodec/avcodec.h"  
  47. #include "libavformat/avformat.h"  
  48. #include "libswscale/swscale.h"  
  49. #include "libavdevice/avdevice.h"  
  50. #include "SDL/SDL.h"  
  51. };  
  52. #else  
  53. //Linux...  
  54. #ifdef __cplusplus  
  55. extern "C"  
  56. {  
  57. #endif  
  58. #include <libavcodec/avcodec.h>  
  59. #include <libavformat/avformat.h>  
  60. #include <libswscale/swscale.h>  
  61. #include <libavdevice/avdevice.h>  
  62. #include <SDL/SDL.h>  
  63. #ifdef __cplusplus  
  64. };  
  65. #endif  
  66. #endif  
  67.   
  68. //Output YUV420P   
  69. #define OUTPUT_YUV420P 0  
  70. //'1' Use Dshow   
  71. //'0' Use VFW  
  72. #define USE_DSHOW 0  
  73.   
  74.   
  75. //Refresh Event  
  76. #define SFM_REFRESH_EVENT  (SDL_USEREVENT + 1)  
  77.   
  78. int thread_exit=0;  
  79.   
  80. int sfp_refresh_thread(void *opaque)  
  81. {  
  82.     while (thread_exit==0) {  
  83.         SDL_Event event;  
  84.         event.type = SFM_REFRESH_EVENT;  
  85.         SDL_PushEvent(&event);  
  86.         SDL_Delay(40);  
  87.     }  
  88.     return 0;  
  89. }  
  90.   
  91.   
  92. //Show Dshow Device  
  93. void show_dshow_device(){  
  94.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  95.     AVDictionary* options = NULL;  
  96.     av_dict_set(&options,"list_devices","true",0);  
  97.     AVInputFormat *iformat = av_find_input_format("dshow");  
  98.     printf("========Device Info=============\n");  
  99.     avformat_open_input(&pFormatCtx,"video=dummy",iformat,&options);  
  100.     printf("================================\n");  
  101. }  
  102.   
  103. //Show Dshow Device Option  
  104. void show_dshow_device_option(){  
  105.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  106.     AVDictionary* options = NULL;  
  107.     av_dict_set(&options,"list_options","true",0);  
  108.     AVInputFormat *iformat = av_find_input_format("dshow");  
  109.     printf("========Device Option Info======\n");  
  110.     avformat_open_input(&pFormatCtx,"video=Integrated Camera",iformat,&options);  
  111.     printf("================================\n");  
  112. }  
  113.   
  114. //Show VFW Device  
  115. void show_vfw_device(){  
  116.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  117.     AVInputFormat *iformat = av_find_input_format("vfwcap");  
  118.     printf("========VFW Device Info======\n");  
  119.     avformat_open_input(&pFormatCtx,"list",iformat,NULL);  
  120.     printf("=============================\n");  
  121. }  
  122.   
  123. //Show AVFoundation Device  
  124. void show_avfoundation_device(){  
  125.     AVFormatContext *pFormatCtx = avformat_alloc_context();  
  126.     AVDictionary* options = NULL;  
  127.     av_dict_set(&options,"list_devices","true",0);  
  128.     AVInputFormat *iformat = av_find_input_format("avfoundation");  
  129.     printf("==AVFoundation Device Info===\n");  
  130.     avformat_open_input(&pFormatCtx,"",iformat,&options);  
  131.     printf("=============================\n");  
  132. }  
  133.   
  134.   
  135. int main(int argc, char* argv[])  
  136. {  
  137.   
  138.     AVFormatContext *pFormatCtx;  
  139.     int             i, videoindex;  
  140.     AVCodecContext  *pCodecCtx;  
  141.     AVCodec         *pCodec;  
  142.       
  143.     av_register_all();  
  144.     avformat_network_init();  
  145.     pFormatCtx = avformat_alloc_context();  
  146.       
  147.     //Open File  
  148.     //char filepath[]="src01_480x272_22.h265";  
  149.     //avformat_open_input(&pFormatCtx,filepath,NULL,NULL)  
  150.   
  151.     //Register Device  
  152.     avdevice_register_all();  
  153.   
  154. //Windows  
  155. #ifdef _WIN32  
  156.   
  157.     //Show Dshow Device  
  158.     show_dshow_device();  
  159.     //Show Device Options  
  160.     show_dshow_device_option();  
  161.     //Show VFW Options  
  162.     show_vfw_device();  
  163.   
  164. #if USE_DSHOW  
  165.     AVInputFormat *ifmt=av_find_input_format("dshow");  
  166.     //Set own video device's name  
  167.     if(avformat_open_input(&pFormatCtx,"video=Integrated Camera",ifmt,NULL)!=0){  
  168.         printf("Couldn't open input stream.\n");  
  169.         return -1;  
  170.     }  
  171. #else  
  172.     AVInputFormat *ifmt=av_find_input_format("vfwcap");  
  173.     if(avformat_open_input(&pFormatCtx,"0",ifmt,NULL)!=0){  
  174.         printf("Couldn't open input stream.\n");  
  175.         return -1;  
  176.     }  
  177. #endif  
  178. #elif defined linux  
  179.     //Linux  
  180.     AVInputFormat *ifmt=av_find_input_format("video4linux2");  
  181.     if(avformat_open_input(&pFormatCtx,"/dev/video0",ifmt,NULL)!=0){  
  182.         printf("Couldn't open input stream.\n");  
  183.         return -1;  
  184.     }  
  185. #else  
  186.     show_avfoundation_device();  
  187.     //Mac  
  188.     AVInputFormat *ifmt=av_find_input_format("avfoundation");  
  189.     //Avfoundation  
  190.     //[video]:[audio]  
  191.     if(avformat_open_input(&pFormatCtx,"0",ifmt,NULL)!=0){  
  192.         printf("Couldn't open input stream.\n");  
  193.         return -1;  
  194.     }  
  195. #endif  
  196.   
  197.   
  198.     if(avformat_find_stream_info(pFormatCtx,NULL)<0)  
  199.     {  
  200.         printf("Couldn't find stream information.\n");  
  201.         return -1;  
  202.     }  
  203.     videoindex=-1;  
  204.     for(i=0; i<pFormatCtx->nb_streams; i++)   
  205.         if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)  
  206.         {  
  207.             videoindex=i;  
  208.             break;  
  209.         }  
  210.     if(videoindex==-1)  
  211.     {  
  212.         printf("Couldn't find a video stream.\n");  
  213.         return -1;  
  214.     }  
  215.     pCodecCtx=pFormatCtx->streams[videoindex]->codec;  
  216.     pCodec=avcodec_find_decoder(pCodecCtx->codec_id);  
  217.     if(pCodec==NULL)  
  218.     {  
  219.         printf("Codec not found.\n");  
  220.         return -1;  
  221.     }  
  222.     if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)  
  223.     {  
  224.         printf("Could not open codec.\n");  
  225.         return -1;  
  226.     }  
  227.     AVFrame *pFrame,*pFrameYUV;  
  228.     pFrame=av_frame_alloc();  
  229.     pFrameYUV=av_frame_alloc();  
  230.     //uint8_t *out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));  
  231.     //avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);  
  232.     //SDL----------------------------  
  233.     if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {    
  234.         printf( "Could not initialize SDL - %s\n", SDL_GetError());   
  235.         return -1;  
  236.     }   
  237.     int screen_w=0,screen_h=0;  
  238.     SDL_Surface *screen;   
  239.     screen_w = pCodecCtx->width;  
  240.     screen_h = pCodecCtx->height;  
  241.     screen = SDL_SetVideoMode(screen_w, screen_h, 0,0);  
  242.   
  243.     if(!screen) {    
  244.         printf("SDL: could not set video mode - exiting:%s\n",SDL_GetError());    
  245.         return -1;  
  246.     }  
  247.     SDL_Overlay *bmp;   
  248.     bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);   
  249.     SDL_Rect rect;  
  250.     rect.x = 0;      
  251.     rect.y = 0;      
  252.     rect.w = screen_w;      
  253.     rect.h = screen_h;    
  254.     //SDL End------------------------  
  255.     int ret, got_picture;  
  256.   
  257.     AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));  
  258.   
  259. #if OUTPUT_YUV420P   
  260.     FILE *fp_yuv=fopen("output.yuv","wb+");    
  261. #endif    
  262.   
  263.     struct SwsContext *img_convert_ctx;  
  264.     img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);   
  265.     //------------------------------  
  266.     SDL_Thread *video_tid = SDL_CreateThread(sfp_refresh_thread,NULL);  
  267.     //  
  268.     SDL_WM_SetCaption("Simplest FFmpeg Read Camera",NULL);  
  269.     //Event Loop  
  270.     SDL_Event event;  
  271.   
  272.     for (;;) {  
  273.         //Wait  
  274.         SDL_WaitEvent(&event);  
  275.         if(event.type==SFM_REFRESH_EVENT){  
  276.             //------------------------------  
  277.             if(av_read_frame(pFormatCtx, packet)>=0){  
  278.                 if(packet->stream_index==videoindex){  
  279.                     ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);  
  280.                     if(ret < 0){  
  281.                         printf("Decode Error.\n");  
  282.                         return -1;  
  283.                     }  
  284.                     if(got_picture){  
  285.                         SDL_LockYUVOverlay(bmp);  
  286.                         pFrameYUV->data[0]=bmp->pixels[0];  
  287.                         pFrameYUV->data[1]=bmp->pixels[2];  
  288.                         pFrameYUV->data[2]=bmp->pixels[1];       
  289.                         pFrameYUV->linesize[0]=bmp->pitches[0];  
  290.                         pFrameYUV->linesize[1]=bmp->pitches[2];     
  291.                         pFrameYUV->linesize[2]=bmp->pitches[1];  
  292.                         sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);  
  293.   
  294. #if OUTPUT_YUV420P    
  295.                         int y_size=pCodecCtx->width*pCodecCtx->height;      
  296.                         fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y     
  297.                         fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U    
  298.                         fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V    
  299. #endif    
  300.   
  301.                         SDL_UnlockYUVOverlay(bmp);   
  302.                           
  303.                         SDL_DisplayYUVOverlay(bmp, &rect);   
  304.   
  305.                     }  
  306.                 }  
  307.                 av_free_packet(packet);  
  308.             }else{  
  309.                 //Exit Thread  
  310.                 thread_exit=1;  
  311.                 break;  
  312.             }  
  313.         }else if(event.type==SDL_QUIT){  
  314.             thread_exit=1;  
  315.             break;  
  316.         }  
  317.   
  318.     }  
  319.       
  320.   
  321.     sws_freeContext(img_convert_ctx);  
  322.   
  323. #if OUTPUT_YUV420P   
  324.     fclose(fp_yuv);  
  325. #endif   
  326.   
  327.     SDL_Quit();  
  328.   
  329.     //av_free(out_buffer);  
  330.     av_free(pFrameYUV);  
  331.     avcodec_close(pCodecCtx);  
  332.     avformat_close_input(&pFormatCtx);  
  333.   
  334.     return 0;  
  335. }  


结果

程序的运行效果如下。输出了摄像头的数据。

可以通过下面的宏定义来确定是否将解码后的YUV420P数据输出成文件:

  1. #define OUTPUT_YUV420P 0  

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

  1. //'1' Use Dshow   
  2. //'0' Use VFW  
  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的安装路径调整脚本里面的参数。编译命令如下。

  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_readcamera.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++进行编译。编译命令如下。

  1. g++ simplest_ffmpeg_readcamera.cpp -g -o simplest_ffmpeg_readcamera.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进行编译。编译命令如下。

  1. gcc simplest_ffmpeg_readcamera.cpp -g -o simplest_ffmpeg_readcamera.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”参数,否则编译无法通过。编译命令如下。

  1. gcc simplest_ffmpeg_readcamera.cpp -g -o simplest_ffmpeg_readcamera.out \  
  2. -framework Cocoa -I /usr/local/include -L /usr/local/lib -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavdevice -lswscale  

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

此外,增加了MacOS下使用avfoundation读取摄像头的代码。

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

SourceForge上已经更新。

以下是基于FFmpegAVDevice样例(读取摄像头)的代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libavdevice/avdevice.h> #include <libavformat/avformat.h> int main(int argc, char *argv[]) { AVInputFormat *inputFormat; AVFormatContext *formatCtx = NULL; AVDictionary *options = NULL; AVCodecContext *codecCtx = NULL; AVFrame *frame = NULL; AVPacket pkt; int ret; avdevice_register_all(); inputFormat = av_find_input_format("video4linux2"); av_dict_set(&options, "video_size", "640x480", 0); av_dict_set(&options, "framerate", "30", 0); ret = avformat_open_input(&formatCtx, "/dev/video0", inputFormat, &options); if (ret < 0) { fprintf(stderr, "Could not open input file\n"); return 1; } ret = avformat_find_stream_info(formatCtx, NULL); if (ret < 0) { fprintf(stderr, "Could not find stream information\n"); return 1; } codecCtx = avcodec_alloc_context3(NULL); if (!codecCtx) { fprintf(stderr, "Could not allocate codec context\n"); return 1; } ret = avcodec_parameters_to_context(codecCtx, formatCtx->streams[0]->codecpar); if (ret < 0) { fprintf(stderr, "Could not copy codec parameters to codec context\n"); return 1; } ret = avcodec_open2(codecCtx, avcodec_find_decoder(codecCtx->codec_id), NULL); if (ret < 0) { fprintf(stderr, "Could not open codec\n"); return 1; } frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Could not allocate frame\n"); return 1; } while (1) { ret = av_read_frame(formatCtx, &pkt); if (ret < 0) break; if (pkt.stream_index == 0) { ret = avcodec_send_packet(codecCtx, &pkt); if (ret < 0) { fprintf(stderr, "Could not send packet to decoder\n"); break; } while (ret >= 0) { ret = avcodec_receive_frame(codecCtx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; else if (ret < 0) { fprintf(stderr, "Error during decoding\n"); break; } printf("Frame %d (type=%c, size=%d bytes)\n", codecCtx->frame_number, av_get_picture_type_char(frame->pict_type), frame->pkt_size); av_frame_unref(frame); } } av_packet_unref(&pkt); } av_frame_free(&frame); avcodec_free_context(&codecCtx); avformat_close_input(&formatCtx); av_dict_free(&options); return 0; } ``` 这个样例使用了video4linux2作为输入格式,打开了/dev/video0设备,读取该设备的视频流,并将视频帧通过AVCodecContext解码。在解码的过程中,将每一帧的信息打印到控制台上。 请注意,使用此样例代码需要安装FFmpeg库,并且需要有摄像头设备。如果要在其他平台上运行,需要根据平台不同进行一定的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值