9.基於FFMPEG+SDL2播放視頻(解碼線程和播放線程分開)

參考資料:
1.雷博博客
2. An ffmpeg and SDL Tutorial

繼續FFMPEG學習之路。。。

1 綜述

本文主要有兩份代碼,第一份代碼就是雷博的《100行實現最簡單的FFMPEG視頻播放器》,採用的方法就是創建一個線程,定時發出信號,而在主線程中則等待信號進行解碼然後顯示,整個流程非常清晰,很容易就能看到之間的關係。第二份代碼則是參考前面《基於FFMPEG+SDL2播放音頻》以及FFMPEG教程《An ffmpeg and SDL Tutorial》將播放線程和解碼線程單獨分開,每個線程單獨做一件事,這樣可以更精確的控制播放,但是同時代碼複雜程度也同樣增大了。。。

2 代碼1(基礎代碼)

此部分代碼是基於前面文章《基於FFMPEG將video解碼爲YUV》以及《基於SDL2播放YUV視頻》基礎上綜合而來,基本思路如下:
初始化複用器和解複用器—>獲取輸入文件的一些信息—>查找解碼器並打開—>初始化SDL—>創建線程定時發出信號—>主線程等待信號解碼並顯示—>結束,退出。

代碼如下:

#include <stdio.h>

#define __STDC_CONSTANT_MACROS
extern "C"
{
	#include "libavcodec/avcodec.h"
	#include "libavformat/avformat.h"
	#include "libswscale/swscale.h"
	#include "sdl/SDL.h"
};

//#define debug_msg(fmt, args ...) printf("--->[%s,%d]  " fmt "\n\n", __FUNCTION__, __LINE__, ##args)

#define REFRESH_EVENT  (SDL_USEREVENT + 1)
#define BREAK_EVENT  (SDL_USEREVENT + 2)
int thread_exit=0;

int refresh_video(void *opaque)
{
	thread_exit=0;
	SDL_Event event;
	
	while (thread_exit==0) 
	{
		event.type = REFRESH_EVENT;
		SDL_PushEvent(&event);
		SDL_Delay(40);
	}
	
	thread_exit=0;
	//Break
	//SDL_Event event;
	event.type = BREAK_EVENT;
	SDL_PushEvent(&event);
	return 0;
}

int main(int argc, char* argv[])
{
	AVFormatContext	*pFormatCtx;  
	AVCodecContext	*pCodecCtx;  
	AVCodec			*pCodec;     
	AVPacket *packet; 
	AVFrame	*pFrame,*pFrameYUV;

	int screen_w,screen_h;
	SDL_Window *screen; 
	SDL_Renderer* sdlRenderer;
	SDL_Texture* sdlTexture;
	SDL_Rect sdlRect;
	SDL_Thread *refresh_thread;
	SDL_Event event;
	
	struct SwsContext *img_convert_ctx;

	uint8_t *out_buffer;
	int ret, got_picture;
	int i = 0;
	int videoindex = -1;
	char filepath[]="Titanic.ts";
	//char filepath[]="屌絲男士.mov";
  
	av_register_all(); 
	
	pFormatCtx = avformat_alloc_context();

	if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL) != 0)
	{
		printf("Couldn't open input stream.\n");
		return -1;
	}

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

	for(i = 0; i < pFormatCtx->nb_streams; i++) 
	{
		if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			videoindex=i;
			break;
		}
	}
	if(videoindex == -1)
	{
		printf("Didn't find a video stream.\n");
		return -1;
	}

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

	if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)
	{ 
		printf("Could not open codec.\n");
		return -1;
	}
    
    	packet=(AVPacket *)av_malloc(sizeof(AVPacket));
    
	pFrame = av_frame_alloc();
	pFrameYUV = av_frame_alloc();
	out_buffer=(uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
	avpicture_fill((AVPicture *)pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height); 

	printf("----------->width is %d, height is %d, size is %d,\n", 
		pCodecCtx->width, pCodecCtx->height,
		avpicture_get_size( pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height));

	//av_dump_format(pFormatCtx,0,filepath,0); 
    
	img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, 
		pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); 

	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER)) 
	{  
		printf( "Could not initialize SDL - %s\n", SDL_GetError()); 
		return -1;
	} 

	screen_w = pCodecCtx->width;
	screen_h = pCodecCtx->height;
	screen = SDL_CreateWindow("FFMPEG_SDL2_Play_Video", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		screen_w, screen_h,SDL_WINDOW_OPENGL);
	if(!screen) 
	{
		printf("SDL: could not create window - exiting:%s\n",SDL_GetError());  
		return -1;
	}

	sdlRenderer = SDL_CreateRenderer(screen, -1, 0);  

	sdlTexture = SDL_CreateTexture(sdlRenderer,SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING,screen_w,screen_h);

	refresh_thread = SDL_CreateThread(refresh_video,NULL,NULL);

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

	while(1)
	{
		SDL_WaitEvent(&event);

		if(event.type==REFRESH_EVENT)
		{
			if (av_read_frame(pFormatCtx, packet)>=0)
			{
				if(packet->stream_index==videoindex)
				{
					ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
					if(ret < 0)
					{
						printf("Decode Error.\n");
						return -1;
					}
					
					if(got_picture)
					{
						sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, 
							pFrameYUV->data, pFrameYUV->linesize);
						
						//fwrite(pFrameYUV->data[0],1, (pCodecCtx->width*pCodecCtx->height),fd_yuv);
						//fwrite(pFrameYUV->data[1],1, (pCodecCtx->width*pCodecCtx->height)/4,fd_yuv);  
						//fwrite(pFrameYUV->data[2],1, (pCodecCtx->width*pCodecCtx->height)/4,fd_yuv);
						//fwrite(out_buffer,1, (pCodecCtx->width*pCodecCtx->height)*3/2,fd_yuv);
						SDL_UpdateTexture( sdlTexture, &sdlRect,out_buffer, pCodecCtx->width);  
						SDL_RenderClear( sdlRenderer );  
						SDL_RenderCopy( sdlRenderer, sdlTexture, &sdlRect, &sdlRect );  
						//SDL_RenderCopy( sdlRenderer, sdlTexture, NULL, NULL);  
						SDL_RenderPresent( sdlRenderer );  
					}
				}
				av_free_packet(packet);
			}
			else
			{
				thread_exit=1;
			}
		}
		else if(event.type==SDL_QUIT)
		{
			thread_exit=1;
		}
		else if(event.type==BREAK_EVENT)
		{
			break;
		}
	}

	sws_freeContext(img_convert_ctx);

	SDL_Quit();
	av_frame_free(&pFrameYUV);
	av_frame_free(&pFrame);
	avcodec_close(pCodecCtx);
	avformat_close_input(&pFormatCtx);

	return 0;
}

3 代碼2(播放線程和解碼線程分開)

將解碼線程和播放線程分開,大致思路是:播放主線程通過事件來刷新定時器並且從VideoPicture隊列中取出一幀解碼後的數據進行顯示,在解碼線程中從文件中不斷讀取數據幀並放入AVPacket隊列中,然後再創建一個線程(解碼線程子線程)從AVPacket隊列中不斷讀出每一幀數據,並將其放入VideoPicture隊列中。這樣就會形成一個整體循環,一個線程不斷的將數據解碼並放入隊列中,另外一個線程則等待事件來顯示並重新刷新事件。

3.1 幾個結構體

3.1.1 VideoState

typedef struct _VideoState_
{
	AVFormatContext *pFormatCtx;

	int videoStreamIndex;
	AVStream* pVideoStream;
	PacketQueue videoQueue;
	VideoPicture pictQueue[VIDEO_PICTURE_QUEUE_SIZE];
	int pictSize;
	int pictRindex;                          //取出索引
	int pictWindex;                         //寫入索引

	SDL_mutex *pictQueueMutex;
	SDL_cond *pictQueueCond;
	SDL_Thread *videoThrd;
	SDL_Thread *parseThrd;

	char fileName[128];
	int quit;

	struct SwsContext *sws_ctx;
}VideoState;

上面的結構體保存了視頻的必要信息,videoStreamIndex 爲video在文件中的索引,videoQueue隊列則是 存放從文件中讀取到的AVPacket數據,pictQueue則爲存放解碼後的YUV數據,pictSize爲pictQueue隊列中的YUV數據數量,pictRindex爲顯示視頻時候的索引,pictWindex爲將YUV數據放到pictQueue隊列中的索引,其他參數也是一些必要的信息。

3.1.2 VideoPicture

typedef struct _VideoPicture_
{
	AVFrame* pFrame;
	int frameWidth;
	int frameHeight;
	int allocated;
}VideoPicture;

此結構體則爲存放解碼後的一幀YUV數據,frameWidth和frameHeight則爲YUV數據的長和寬,allocated則爲一個標誌位,用於判斷是否需要重新申請AVFrame結構體。

3.2 PacketQueue隊列操作

將文件中讀取到的每一幀數據,放入到PacketQueue隊列中,然後從PacketQueue隊列中取出每一幀數據,這一部分相關的操作主要函數有:

void packet_queue_init(PacketQueue *q); 
static int packet_queue_put(PacketQueue *q, AVPacket *pkt) ;
static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) ;

這一部分的內容在前面文章《基於FFMPEG+SDL2播放音頻》中已經做了相關的介紹,這裏就不在介紹了。

3.3 播放線程

在播放主線程中,我們主要是等待刷新事件進行控制,代碼如下:

			case FF_REFRESH_EVENT:
				if (NULL == pSdlScreen)
				{
					VideoState* pState = (VideoState *)event.user.data1;
					if ((pState->pVideoStream) && (pState->pictSize != 0))
					{
						sdlWidth = pState->pictQueue[pState->pictRindex].frameWidth;
						sdlHeight = pState->pictQueue[pState->pictRindex].frameHeight;
						
						printf("------------>SDL width is %d, height is %d\n", sdlWidth, sdlHeight);
						
						pSdlScreen = SDL_CreateWindow("FFMPEG_SDL2_Play_Video", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,sdlWidth, sdlHeight,SDL_WINDOW_OPENGL);
						if(!pSdlScreen) 
						{
							printf("SDL: could not create window - exiting:%s\n",SDL_GetError());  
							return -1;
						}
						pSdlRenderer = SDL_CreateRenderer(pSdlScreen, -1, 0);  
						pTexTure = SDL_CreateTexture(pSdlRenderer,SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING,sdlWidth,sdlHeight);
					}
					else
					{
						schduleRefresh(pState, 1);
						break;
					}
				}
				videoRefreshTimer(event.user.data1,pSdlRenderer,pTexTure);
				break;

其中videoRefreshTimer函數便是我們的顯示函數,在此之前,我們根據YUV數據的長和寬創建了SDL顯示相關的窗口、渲染器、紋理。

在介紹videoRefreshTimer之前先介紹一下SDL中的定時器。

3.3.1 SDL中的定時器—SDL_AddTimer

函數原型如下:

SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval,SDL_TimerCallback callback, void *param);

此函數的作用添加一個新的定時信息,interval單位爲ms,添加定時器interval ms後調用回調函數,callback爲回調函數,param則爲調用回調函數時候攜帶的參數。
回調函數的原型爲:

typedef Uint32 (SDLCALL * SDL_TimerCallback) (Uint32 interval, void *param);

注意,此函數的返回值爲下次調用此回調函數的間隔,如果此返回值爲0,則不再調用此函數。

代碼中的回調相關函數如下:

//定時刷新
void schduleRefresh(VideoState *pState, int delay)
{
	SDL_AddTimer(delay, SDLRefreshCB, pState);
}

//定時刷新回調函數
static Uint32 SDLRefreshCB(Uint32 interval, void *opaque) 
{
    SDL_Event event;
    event.type = FF_REFRESH_EVENT;
    event.user.data1 = opaque;
    SDL_PushEvent(&event);
    return 0; /* 0 means stop timer */
}

可以看到,每次調用時候會發出一個刷新事件(FF_REFRESH_EVENT),通知主線程進行解碼。同時看到SDLRefreshCB返回值爲0,即只調用一次此定時器便失效,然後不再刷新了?不,而是在播放線程中再次添加一個定時器。

3.3.2 播放線程—videoRefreshTimer

先上一下代碼:

 //刷新定時器並將視頻顯示到SDL上
void videoRefreshTimer(void *userdata,SDL_Renderer* renderer,SDL_Texture* texture) 
{
	static int exitCnt = 0;
	
	VideoState* pState = (VideoState *)userdata;

	if (pState->pVideoStream)
	{
		if (pState->pictSize == 0) //當前視頻隊列中沒有視頻數據
		{
			schduleRefresh(pState, 1);  // 1ms後再次刷新

			if (++exitCnt > 200)
				pState->quit = 1;
		} 
		else
		{
			schduleRefresh(pState, 40);
			
			videoDisplay(pState, renderer, texture); //顯示
			
			if(++pState->pictRindex >= VIDEO_PICTURE_QUEUE_SIZE) 
			{
				pState->pictRindex = 0;
			}
			
			SDL_LockMutex(pState->pictQueueMutex);
			pState->pictSize--;
			SDL_CondSignal(pState->pictQueueCond);
			SDL_UnlockMutex(pState->pictQueueMutex);	

			exitCnt = 0;
		}
	}
	else //相關準備還沒有做好
	{
		schduleRefresh(pState, 100);
	}
}

播放線程的主要作用便是刷新定時器並且從VideoPicture隊列中取出一幀YUV圖像進行顯示。

在前面我們說過,定時器每次只觸發一次,然後在播放線程中再次添加一個定時器,這樣做的好處是我們可以精確的控制下次調用播放線程的時間。

播放線程的主要功能便是將一幀YUV圖像進行顯示。

3.3.2.1 顯示畫面—videoDisplay

代碼如下:

//通過SDL顯示畫面
void videoDisplay(VideoState *pState,SDL_Renderer* renderer,SDL_Texture* texture) 
{
	VideoPicture* pVideoPic = &pState->pictQueue[pState->pictRindex];
	
	SDL_Rect sdlRect;

	if (pVideoPic->pFrame)
	{
		sdlRect.x = 0;
		sdlRect.y = 0;
		sdlRect.w = pVideoPic->frameWidth;
		sdlRect.h = pVideoPic->frameHeight;

		SDL_UpdateTexture( texture, &sdlRect,pVideoPic->pFrame->data[0], pVideoPic->pFrame->linesize[0]);  
		SDL_RenderClear( renderer );  
		//SDL_RenderCopy( sdlRenderer, sdlTexture, &sdlRect, &sdlRect );  
		SDL_RenderCopy( renderer, texture, &sdlRect ,  &sdlRect ); 
		SDL_RenderPresent( renderer );  
	}
}

在上面可以看到,我們直接從隊列中取出一幀YUV圖像,然後直接通過標準SDL顯示流程進行顯示。

3.4 解碼線程----decordThread

先上代碼:

//解碼線程
int decordThread(void* arg)
{
	VideoState *state = (VideoState *)arg;
	AVFormatContext * pFormatCtx = avformat_alloc_context();
	AVPacket* packet =(AVPacket *)av_malloc(sizeof(AVPacket));

	int i= 0;
	int videoIndex = -1;
	
	state->videoStreamIndex = -1;

	global_video_state = state;
 
	if(avformat_open_input(&pFormatCtx,state->fileName,NULL,NULL) != 0)
	{
		printf("Couldn't open input stream.\n");
		return -1;
	}

	 state->pFormatCtx = pFormatCtx;

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

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

	if (videoIndex >= 0)
	{
		streamComponentOpen(state, videoIndex);
	}

	if (state->videoStreamIndex < 0)
	{
		printf("open codec error!\n");
		goto fail;
	}

	while(1)
	{
		if (state->quit) break;

		if (state->videoQueue.size > MAX_VIDEOQ_SIZE) //防止隊列過長
		{
			SDL_Delay(10);
			continue;
		}

		if(av_read_frame(state->pFormatCtx, packet) < 0) 
		{
			if(state->pFormatCtx->pb->error == 0) 
			{
				SDL_Delay(100); /* no error; wait for user input */
				continue;
			} 
			else 
				break;
		}

		if (packet->stream_index ==  state->videoStreamIndex)
		{
			packet_queue_put(&state->videoQueue, packet);
		}
		else
		{
			av_free_packet(packet);
		}
	}

	while(state->quit == 0)   //等待退出信號
	{
		SDL_Delay(100);
	}
	
	fail:
	SDL_Event event;
	event.type = FF_QUIT_EVENT;
	event.user.data1 = state;
	SDL_PushEvent(&event);

	return 0;
}

解碼線程主要做了以下幾個工作:
初始化解碼器
從文件中讀出每幀數據並放入隊列
從隊列中取出沒幀數據並解碼放入VideoPicture隊列中

3.4.1 初始化編解碼器

初始化編解碼器其實包含了FFMPEG一整套的流程,如下:
打開輸入文件—>查找文件的一些信息—>查找視頻index—>查找解碼器—>打開解碼器
上面這些流程對應的函數在以前已經說過,這裏不再多說。

在查找解碼器並打開解碼器的時候,另外封裝了一個函數streamComponentOpen,這樣做減少了代碼的複雜性,並且以後音頻解碼器相關的操作也可以複用此函數。

在初始化解碼器後,又創建了一個函數videoThread,此函數的作用便是解碼每一幀數據並放入VideoPicture隊列中,這一點在下面會說明。

3.4.2 讀出每幀數據

從文件中讀出每幀數據並將其放入PacketQueue隊列中,這部分的操作和前面的文章《基於FFMPEG+SDL2播放音頻》中的操作一致,這裏不再說明。

另外,由於前面文章《基於FFMPEG+SDL2播放音頻》中的音頻本身很小,所以會一直讀取數據將其放入隊列中,但是視頻可能很大,幾百兆很正常,所以如果由於某種原因導致取數據操作異常或者退出,而將數據放入隊列操作缺卻一直在進行,這樣就會導致內存申請過大,因此在將數據放入隊列前,可以做一個判斷,當隊列中的數據大於某個值的時候,就會暫停放入隊列操作,等待隊列中的數據被取出,如下:

		if (state->videoQueue.size > MAX_VIDEOQ_SIZE) //防止隊列過長
		{
			SDL_Delay(10);
			continue;
		}

3.4.3 取出每幀數據並解碼

從PacketQueue隊列中取出每幀數據並解碼,這部分的操作和前面的文章《基於FFMPEG+SDL2播放音頻》中的操作一致,這裏不再說明。

再將解碼後的每一幀數據放入VideoPictue隊列中去的函數queuePicture中,需要首先判斷VideoPictue隊列中的AVFrame是否已經初始化,如果沒有初始化,則需要發出FF_ALLOC_EVENT事件,等待allocPicture函數初始化好VideoPictue。

最後附上在vs2010上創建好的工程(在vs2010上測試ok):

基於FFMPEG+SDL2播放視頻(解碼線程和播放線程分開)

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