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 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章