FFmpeg —— 6.示例程序(一):FFmpeg+SDL2.0 打开Windows摄像头

关于FFmpeg的相关教程,大家可以去参考雷霄骅的相关博文,写的很详细。

程序源码

/**
 * 最简单的基于FFmpeg的AVDevice例子(读取摄像头)
 *
 * 本程序实现了本地摄像头数据的获取解码和显示。是基于FFmpeg
 * 的libavdevice类库最简单的例子。通过该例子,可以学习FFmpeg中
 * libavdevice类库的使用方法。
 * 本程序在Windows下可以使用2种方式读取摄像头数据:
 *  1.VFW: Video for Windows 屏幕捕捉设备。注意输入URL是设备的序号,
 *          从0至9。
 *  2.dshow: 使用Directshow。注意作者机器上的摄像头设备名称是
 *         “Integrated Camera”,使用的时候需要改成自己电脑上摄像头设
 *          备的名称。
 * 在Linux下可以使用video4linux2读取摄像头设备。
 * 在MacOS下可以使用avfoundation读取摄像头设备。
 *
 */



#include <stdio.h>

#define __STDC_CONSTANT_MACROS


extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavdevice/avdevice.h"
#include "libavutil/imgutils.h"
#include "libavutil/dict.h"
#include "SDL2/SDL.h"
};


#define USE_DSHOW	0

//Refresh Event
#define SFM_REFRESH_EVENT  (SDL_USEREVENT + 1)

#define SFM_BREAK_EVENT  (SDL_USEREVENT + 2)

int thread_exit = 0;

int sfp_refresh_thread(void *opaque)
{
	thread_exit = 0;
	while (!thread_exit)
	{
		SDL_Event event;
		event.type = SFM_REFRESH_EVENT;
		SDL_PushEvent(&event);
		SDL_Delay(40);
	}

	thread_exit = 0;
	SDL_Event event;
	event.type = SFM_BREAK_EVENT;
	SDL_PushEvent(&event);

	return 0;
}

//Show Dshow Device
void show_dshow_device()
{
	AVFormatContext *pFormatCtx = avformat_alloc_context();
	AVDictionary* options = NULL;	av_dict_set(&options,"list_devices","true",0);
	AVInputFormat *iformat = av_find_input_format("dshow");
	printf("========Device Info=============\n");
	avformat_open_input(&pFormatCtx,"video=dummy",iformat,&options);
	printf("================================\n");

	avformat_free_context(pFormatCtx);
}


//Show Dshow Device Option
void show_dshow_device_option()
{
	AVFormatContext *pFormatCtx = avformat_alloc_context();
	AVDictionary* options = NULL;
	av_dict_set(&options,"list_options","true",0);
	AVInputFormat *iformat = av_find_input_format("dshow");
	printf("========Device Option Info======\n");
	avformat_open_input(&pFormatCtx,"video=HP HD Camera",iformat,&options);
	printf("================================\n");

	avformat_free_context(pFormatCtx);
}

//Show VFW Device
void show_vfw_device()
{
	AVFormatContext *pFormatCtx = avformat_alloc_context();
	AVInputFormat *iformat = av_find_input_format("vfwcap");
	printf("========VFW Device Info======\n");
	avformat_open_input(&pFormatCtx,"list",iformat,NULL);
	printf("=============================\n");

	avformat_free_context(pFormatCtx);
}


int main(int argc, char *argv[])
{
	AVFormatContext	*pFormatCtx;
    AVStream			*stream;
	AVCodecContext		*pCodecCtx;
	AVCodec				*pCodec;
	AVFrame				*pFrame, *pFrameYUV;
	AVPacket			*pPacket;
	SwsContext			*pImgConvertCtx;

	int					videoIndex = -1;
	unsigned int		i = 0;
	unsigned char		*outBuffer;

	SDL_Window			*screen;
	SDL_Renderer		*sdlRenderer;
	SDL_Texture		*sdlTextture;
	SDL_Rect			sdlRect;

	int					screen_w = 0;
	int					screen_h = 0;
	int					ret;
//	int					gotPicture;


	printf("Starting...\n");

	//register device
	avdevice_register_all();

	pFormatCtx = avformat_alloc_context();


	show_dshow_device();

	show_dshow_device_option();

	show_vfw_device();

#if USE_DSHOW
	AVInputFormat *ifmt = av_find_input_format("dshow");
	//set own video device's name
	if (avformat_open_input(&pFormatCtx, "video=HP HD Camera", ifmt, NULL))
	{
		printf("can't open input stream.\n");
		return -1;
	}
#else
	AVInputFormat *ifmt = av_find_input_format("vfwcap");
	AVDictionary *paramDict = NULL;
//	av_dict_set_int(&paramDict, "rtbufsize", 1024*1024*30, 0);
	if (avformat_open_input(&pFormatCtx, "0", ifmt, &paramDict) != 0)
	{
		printf("can't open input stream.\n");
		return -1;
	}

#endif

	if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
	{
		printf("can't find stream information.\n");
		return -1;
	}

	for (i=0; i<pFormatCtx->nb_streams; i++)
	{
		if(pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			videoIndex = i;
			break;
		}
	}

	if (videoIndex == -1)
	{
		printf("can't find a video stream.\n");
		return -1;
	}

	stream = pFormatCtx->streams[videoIndex];
	pCodec = avcodec_find_decoder(stream->codecpar->codec_id);
	if (pCodec == NULL)
	{
		printf("codec not found.\n");
		return -1;
	}

	pCodecCtx = avcodec_alloc_context3(pCodec);
	if (!pCodecCtx)
	{
		printf("can't alloc codec context.\n");
		return -1;
	}

	avcodec_parameters_to_context(pCodecCtx, stream->codecpar);

	if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
	{
		printf("can't open codec.\n");
		return -1;
	}


	pFrame = av_frame_alloc();
	pFrameYUV = av_frame_alloc();

	outBuffer = (unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P,  pCodecCtx->width, pCodecCtx->height,1));
	av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, outBuffer,
			AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);

	pPacket = (AVPacket *)av_malloc(sizeof(AVPacket));

	printf("--------------- File Information ----------------\n");
	av_dump_format(pFormatCtx, 0, 0, 0);
	printf("-------------------------------------------------\n");

	pImgConvertCtx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
			pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);


	//SDL handle
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER))
	{
		printf("can't initialize SDL - %s\n", SDL_GetError());
		return -1;
	}

	screen_w = pCodecCtx->width;
	screen_h = pCodecCtx->height;

	//SDL 2.0 support for multiple windows
	screen = SDL_CreateWindow("Simplest ffmpeg device(read camera)", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
			screen_w, screen_h,
			SDL_WINDOW_OPENGL);
	if (!screen)
	{
		printf("SDL: can't create window - exiting: %s\n", SDL_GetError());
		return -1;
	}

	sdlRenderer = SDL_CreateRenderer(screen, -1, 0);
	//IYUV: Y + U + V  (3 planes)
	//YV12: Y + V + U  (3 planes)
	sdlTextture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, pCodecCtx->width, pCodecCtx->height);

	sdlRect.x = 0;
	sdlRect.y = 0;
	sdlRect.w = screen_w;
	sdlRect.h = screen_h;


	while (av_read_frame(pFormatCtx, pPacket) >= 0)
	{
		if (pPacket->stream_index == videoIndex)
		{
			ret = avcodec_send_packet(pCodecCtx, pPacket);
			if (ret < 0)
			{
				printf("Decode error.\n");
				return -1;
			}

			if (avcodec_receive_frame(pCodecCtx, pFrame) >= 0)
			{
				sws_scale(pImgConvertCtx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
						pFrameYUV->data, pFrameYUV->linesize);

#if OUTPUT_YUV420P
				y_size=pCodecCtx->width*pCodecCtx->height;
				fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y
				fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U
				fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V

#endif

				SDL_UpdateTexture(sdlTextture, &sdlRect, pFrameYUV->data[0], pFrameYUV->linesize[0]);

				SDL_RenderClear(sdlRenderer);
				SDL_RenderCopy(sdlRenderer, sdlTextture, NULL, &sdlRect);
				SDL_RenderPresent(sdlRenderer);

				//SDL end, delay 40ms
				SDL_Delay(40);
			}
		}

		av_packet_unref(pPacket);
	}

	sws_freeContext(pImgConvertCtx);

	SDL_Quit();

	av_free(outBuffer);
	av_frame_free(&pFrameYUV);
	av_frame_free(&pFrame);
	avcodec_close(pCodecCtx);
	avformat_close_input(&pFormatCtx);


	return 0;
}

代码分析

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

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

AVFormatContext *pFormatCtx = avformat_alloc_context();
avformat_open_input(&pFormatCtx, "test.h265",NULL,NULL);

使用libavdevice的时候,唯一的不同在于需要首先查找用于输入的设备。在这里使用av_find_input_format()完成:

AVFormatContext *pFormatCtx = avformat_alloc_context();
AVInputFormat *ifmt=av_find_input_format("vfwcap");
avformat_open_input(&pFormatCtx, 0, ifmt,NULL);

 上述代码首先指定了vfw设备作为输入设备,然后在URL中指定打开第0个设备(在我自己计算机上即是摄像头设备)。
在Windows平台上除了使用vfw设备作为输入设备之外,还可以使用DirectShow作为输入设备:

AVFormatContext *pFormatCtx = avformat_alloc_context();
AVInputFormat *ifmt=av_find_input_format("dshow");
avformat_open_input(&pFormatCtx,"video=HP HD Camera",ifmt,NULL) ;

注意事项 

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编程实现。使用如下代码:

//Show Device
void show_dshow_device(){
	AVFormatContext *pFormatCtx = avformat_alloc_context();
	AVDictionary* options = NULL;
	av_dict_set(&options,"list_devices","true",0);
	AVInputFormat *iformat = av_find_input_format("dshow");
	printf("Device Info=============\n");
	avformat_open_input(&pFormatCtx,"video=dummy",iformat,&options);
	printf("========================\n");
}

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

ffmpeg -list_devices true -f dshow -i dummy

 

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

参考

https://blog.csdn.net/leixiaohua1020/article/details/39702113

https://blog.csdn.net/cairo123/article/details/78780407 

发布了61 篇原创文章 · 获赞 124 · 访问量 70万+

猜你喜欢

转载自blog.csdn.net/guoyunfei123/article/details/105476753