Skip to content

Instantly share code, notes, and snippets.

@ithmz
Last active October 30, 2023 03:10
Show Gist options
  • Save ithmz/1b58f2df84024cf780add1f9fd6f6aaa to your computer and use it in GitHub Desktop.
Save ithmz/1b58f2df84024cf780add1f9fd6f6aaa to your computer and use it in GitHub Desktop.
Upload YUV texture to OpenGL
// Get texture location in fragment shader
GLint locTexY = glGetUniformLocation(program, "textureY");
GLint locTexVU = glGetUniformLocation(program, "textureVU");
// Upload YUV data to texture buffer
GLuint textureID[2];
glGenTextures(1, &textureID[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, &yuvBuffer[0]);
glBindTexture(0);
glGenTextures(1, &textureID[1]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureID[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RG, width, height/2, 0, GL_RG, GL_UNSIGNED_BYTE, &yuvBuffer[width*height]);
glBindTexture(0);
glUseProgram(program);
glUniform1i(locTexY, 0); // corresponds to GL_TEXTURE0
glUniform1i(locTexVU, 1); // corresponds to GL_TEXTURE1
@xueshenan
Copy link

GL_RG means put u as R and v as G ? And got uv value in shader code as following:
yuv.y = texture(textureVU, texCoord).g - 0.5;
yuv.z = texture(textureVU, texCoord).r - 0.5;

@ithmz
Copy link
Author

ithmz commented Oct 26, 2023

@xueshenan it depends on what is your input format. If it YUV nv12 then r is u and g is v, nv21 is reversed order

@xueshenan
Copy link

thank you, I have solve the problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment