須要說明的是,對於新手須要在ubuntu系統安裝SDL庫安裝包和開發安裝包,能夠參考官網的文章:ios
https://wiki.libsdl.org/Installationubuntu
SDL是跨平臺的,下面的代碼更改下#include路徑,指引下鏈接lib庫,就能夠在windows上編譯運行。windows
文章旨在快速運行一個example,具體SDL API需查看官方文檔。ide
1 #include "iostream" 2 #include "SDL2/SDL.h" 3 4 #define PIXEL_W 352 5 #define PIXEL_H 288 6 #define IMAGE_SIZE 152064 // 352 * 288 * 1.5 7 8 #define REFRESH_EVENT (SDL_USEREVENT + 1) // 自定義事件,每40毫秒觸發圖像幀更新 9 10 bool thread_exit = false; 11 // 每40毫秒出發圖像幀更新 12 int refresh_video(void *opaque) 13 { 14 while (thread_exit == false) 15 { 16 SDL_Event event; 17 event.type = REFRESH_EVENT; 18 SDL_PushEvent(&event); 19 std::cout << "push REFRESH_EVENT" << std::endl; 20 SDL_Delay(40); 21 } 22 23 return 0; 24 } 25 26 int main(int argc, char **argv) 27 { 28 if (SDL_Init(SDL_INIT_VIDEO) == -1) 29 { 30 std::cout << SDL_GetError() << std::endl; 31 return -1; 32 } 33 34 SDL_Window *sdlWindow = NULL; 35 sdlWindow= SDL_CreateWindow("SDL example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, PIXEL_W, PIXEL_H, SDL_WINDOW_OPENGL); 36 if (sdlWindow == NULL) 37 { 38 std::cout << SDL_GetError() << std::endl; 39 return -1; 40 } 41 42 SDL_Renderer *sdlRenderer = NULL; 43 sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); 44 if (sdlRenderer == NULL) 45 { 46 std::cout << SDL_GetError() << std::endl; 47 return -1; 48 } 49 50 SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, PIXEL_W, PIXEL_H); 51 52 FILE *fp = fopen("352_288_example.IYUV", "r"); 53 if (fp == NULL) 54 { 55 std::cout << "open file error" << std::endl; 56 return -1; 57 } 58 59 char *pImageBuffer = (char *)malloc(IMAGE_SIZE); 60 if (pImageBuffer == NULL) 61 { 62 std::cout << "malloc image buffer error" << std::endl; 63 return -1; 64 } 65 66 memset(pImageBuffer, 0x00, IMAGE_SIZE); 67 68 SDL_Rect sdlRect; 69 sdlRect.x = 0; 70 sdlRect.y = 0; 71 sdlRect.w = PIXEL_W; 72 sdlRect.h = PIXEL_H; 73 74 SDL_Event event; 75 SDL_Thread *refresh_thread = SDL_CreateThread(refresh_video, NULL, NULL); 76 77 while(1) 78 { 79 std::cout << "waiting event..." << std::endl; 80 SDL_WaitEvent(&event); 81 if (event.type == REFRESH_EVENT) 82 { 83 std::cout << "get REFRESH_EVENT." << std::endl; 84 if (fread(pImageBuffer, 1, IMAGE_SIZE, fp) != IMAGE_SIZE) 85 { 86 fseek(fp, 0, SEEK_SET); 87 fread(pImageBuffer, 1, IMAGE_SIZE, fp); 88 } 89 90 SDL_UpdateTexture(sdlTexture, NULL, pImageBuffer, PIXEL_W); 91 SDL_RenderClear(sdlRenderer); 92 SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, &sdlRect); 93 SDL_RenderPresent(sdlRenderer); 94 } 95 else if (event.type == SDL_QUIT) 96 { 97 std::cout << "get QUIT." << std::endl; 98 break; 99 } 100 else 101 { 102 std::cout << event.type << std::endl; 103 } 104 } 105 106 thread_exit = true; 107 return 0; 108 }
sample所用的視頻文件能夠在這裏下載:spa
https://pan.baidu.com/s/1LyxdBEO3kFi3bLzVnyKJQwcode