40 lines of code render a YUV video
Any questions add QQ group 981886174 contact
Let’s go straight to the code.
Because the code is very short, I’m going to go straight to the code, and I’ll explain it briefly
File write directly to death in the code, a simple test to use, the path to your own can “G: / data/highway_cif. Yuv data direct download on the net, I am here to provide a free download download.csdn.net/download/An integral… There’s a lot of code to delete here. Just to display YUV video content in the simplest way possible. Remove redundant code. It is easier to understand that all destruction must be added if it is needed for use in the project.
#include <iostream> extern "C" { #include "SDL.h" } int main(int argc, char* argv[]) { int window_width = 352, window_height = 288; // Window size/resolution const int video_width = 352, video_height = 288; // Video_width * video_height * 3/2 const int fream_size = video_width * video_height * 3/2; unsigned char fream_buffer[fream_size]; // Define a frame SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("YUV SDL2 Play", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, window_height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); SDL_Renderer* sdlRenderer = SDL_CreateRenderer(window, -1, 0); SDL_Texture* sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV , SDL_TEXTUREACCESS_STREAMING, video_width , video_height); SDL_Rect sdlRect{0,0, window_width, window_height}; FILE* fp = fopen("G:/data/highway_cif.yuv", "rb+"); if (fp == NULL) { return -1; } while (1) {if (fread(fream_buffer, 1, fream_size, fp)! = fream_size) { // Loop //fseek(fp, 0, SEEK_SET); fread(fream_buffer,1, fream_size, fp); } // Update the data to SDL_UpdateTexture(sdlTexture, NULL, fream_buffer, video_width); / /??? SDL_RenderClear(sdlRenderer); // Copy the updated texture to the renderer SDL_RenderCopy(sdlTexture, sdlTexture, NULL, &sdlRect); SDL_RenderPresent(sdlRenderer); SDL_Delay(40); } return 0; }Copy the code
The key code
The whole part of the code that displays the content is to use this to refresh the texture and then display it in the project
Update texture SDL_UpdateTexture(sdlTexture, NULL, fream_buffer, video_width); Copy to the renderer SDL_RenderCopy(sdlTexture, sdlTexture, NULL, &sdlRect);Copy the code
The first step is to create a frame buffer, using a byte array. It’s the size of one frame of data and then you read the file and you read the file into this array of frame buffers and you read a frame and you immediately render it to the screen and then you rest for 40 milliseconds and you refresh and that 40 milliseconds is calculated based on the frame rate of the YUV file and normally it’s 1000/22 and 22 is the frame rate It can be calculated according to the specific frame rate of the video.
There is very little content, such as reading files, which is the basic content. I will not extend it here, but simply introduce the basic use of SDL.