Sign in to follow this  

OpenGL Fastest way to stream video to Texture

This topic is 1749 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am using OpenGL 4.2 in my project, using glew and SDL.


What is the fastest way to transfer an RGB 24-bit or grey scale 8-bit image (decoded video frame) from system memory to an OpenGL texture? Is using PBOs the best way to accomplish this, even with modern OpenGL? I saw a NVidia sample using PBOs for this, but its quite a few years old.


The video frames are coming in at 30-60 hz, 640x480..


What is the best way to allocate the gl texture? Should I force power of 2 for the texture (and update a sub rect)?


Use GL_BGRA8 for the internal format, and GL_BGRA for the pixel format (as apposed to GL_RGB for both)?


Should I use BGRA even for grey scale video?


Thanx for any suggestions.

Edited by Ender1618

Share this post

Link to post
Share on other sites

Create two threads. One thread which is pulling the frames. Main thread which is creating PBO and update the texture with the proper frames. Those PBO can then be assigned to an screen aligned quad to be rendererd. Use two PBO while one is getting renderered you fill the second one with the next frame and ping pong between them.

Share this post

Link to post
Share on other sites

At 640x480 you can probably do this in realtime without needing a PBO.  Even if not, I'd advise that you go about it in the following order:


1) Write the basic version that just updates and displays the texture without anything extra.

2) Add double-buffering to it, using two textures; update texture 0/display texture 1, then swap for the next frame.

3) Add a PBO.


Only go to the next step here if the step you're currently on proves too slow for your needs.


GPUs have an annoying tendency to prefer texture data in 1, 2 or 4 byte formats, whereas content deliverers have an annoying tendency to prefer texture data in 3 byte formats so there is no fast way to get 24-bit RGB data into a texture.  You should expand (and swap) it to BGRA at some stage in the process, yes, and this should preferably happen during decompression from source.


For your colour data, create your texture one-time-only as follows:


glTexStorage2D (


You'll see that I'm using glTexStorage2D here rather than glTexImage2D - at this stage we just want to allocate storage for the texture and we're not yet concerned about what data is actually going into it.


Each time you get new data in, update the texture as follows:


glTexSubImage2D (


The key parameters here are the third and second last ones.  You can write a small program to verify this yourself, but the basic summary is that it is absolutely essential that you match these with what the OpenGL driver is going to prefer, otherwise you're going to get nasty slowdowns and this will be irrespective of whether you use a PBO or double-buffer.  I've benchmarked upload performance increases of over 25x (versus GL_RGB/GL_UNSIGNED_BYTE) on some hardware from these two parameters alone.  So get these correct first, then use other methods to make it faster, but only if you need them.


If your data is coming in at 24-bit RGB and if you don't have control over this, then you should expand and swap yourself; don't rely on the driver to do it for you (by e.g. using GL_RGB/GL_UNSIGNED_BYTE).  Expand and swap to a pre-allocated (or static) buffer and then glTexSubImage it and it will still be faster.


For RGB(A) data, this particular combination of format and type parameters should be the fastest on most systems but may not be the fastest on all.  For traditional desktop GL (which I'm assuming you're targetting based on your mention of 4.2) you should be safe enough, but as always, benchmark and find out for yourself.


For greyscale data you should be good enough just using a greyscale format for your texture; if you don't want to create a second texture then you can also expand it, but greyscale formats are still fine and fast - the only tricky cases are around 24-bit RGB data formats.


Finally, and if the video is also displayed at 640x480, don't underestimate the power of glDrawPixels.  The same trickiness around 24-bit RGB also applies here, but it may well work just fine for you.

Share this post

Link to post
Share on other sites

mhaigan, you mention using glTexStorage2D with GL_RGBA8 and glTexSubImage2D with GL_BGRA.  What does it mean that these are different?


What is the difference between glTexStorage2D and glTexImage2D? The docs mention mostly things about mipmap generation, I dont need mipmaps.


I also notice that




will fail, so I would have to do:




for it to work, so is that to say that I must convert my RGB to BGRA so that I could use GL_UNSIGNED_INT_8_8_8_8_REV? Since there is no GL_UNSIGNED_INT_8_8_8_REV.

Edited by Ender1618

Share this post

Link to post
Share on other sites

TexImage vs TexStorage


TexStorage will just allocate storage for the texture, and can allocate storage for multiple miplevels in one go (ensuring that things are set up correctly for submips).  The miplevels part is not relevant for you here, but using TexStorage is the more correct modern OpenGL way of doing this.


Think of it in terms of malloc, memcpy and free - it's a rough (and not entirely accurate) analogy but should work for the purpose of helping you understand.  TexImage needs to check if the texture storage already exists, delete it if so, allocate new storage, then (if the data pointer is non-NULL) copy in the supplied data.  TexStorage just needs to allocate storage.  Since that's all you need for your initial texture creation, TexStorage is sufficient.


TexStorage vs TexSubImage


The difference here is simple enough - the internal format parameter to TexStorage describes how the texture is represented internally by OpenGL.  The format and type parameters to TexSubImage desribe how the data you're feeding it is laid out.  And now unfortunately we need to get into a hangover from legacy OpenGL.  That internal format parameter - it's not prescriptive.  It just means "give me something that I can read data in this format from".  OpenGL itself is allowed to give you more colour channels and more bits-per-channel than you ask for; this point is going to become important shortly, so remember it.




First off, I need to re-emphasise this: don't use GL_BGR/GL_UNSIGNED_BYTE - that's going to punt you right onto the slow path and you'll end up implementing double-buffering, PBOs, and still wondering why you're not getting good performance from it.  The fact that you've mentioned it shows that you're still thinking along the lines of "saving memory" and avoiding what looks like extra CPU-side work in your own code.  This is important - CPU-side work in your own code is not the only CPU-side work you have to deal with; you've also got CPU-side work in the driver, latency, synchronization, format conversion, etc (all in the driver) to worry about and you have no control over those if you get things wrong.  Burn the extra memory, do the extra work in your own code, it's a tradeoff that will allow you to get in and out of that TexSubImage call as fast as possible and that's where the real key to performance is here.


Remember that bit I said was important?  Here's why.  There's no such thing as a 24-bit texture format on the vast majority of hardware.  Ask for a 24-bit format and you'll instead get a 32-bit one, with the extra 8 bits either ignored or set to 255 (as appropriate).  So you gain nothing by trying to transfer 24-bit data, but you lose a lot because that 24-bit data isn't going to match what's actually being stored internally, and the driver will need to convert it.  It's another unfortunate hangover from legacy OpenGL that these options still exist, because they can lead to much confusion and wrong thinking.  See here for further discussion of this:


So match those parameters and the driver will look at them and say "yes!  I can just suck this data straight in without needing to do anything else, hey!, I can even read it in 32-bit chunks too, thanks very much, I'm done, here's control handed back to your program as quickly as possible".  Get them wrong and the driver will say "oops, you've given something I don't like, now I need to go allocating extra buffers, rummaging around in the data, converting it to something I do like, and by the way - do I need to read the original texture back into system memory first?"  You don't have control over what the driver does when you feed it something it doesn't like, and some drivers can do absolutely awful things.  What you do have control over is feeding it something it does like, and because any conversion you need to do is in your own code, you can optimize it to your heart's content.


So yes, convert your RGB source to BGRA; it's a nice fast simple loop that you do have control over (that you can even unwind some).  That's what most GPUs/drivers are going to prefer, so give them that and you'll get the fast transfer.  8_8_8_8_REV is optional but will put you on the absolute fastest path with even crappy low-quality Intels

Share this post

Link to post
Share on other sites

So the glTexStorage2D internal format is just a high level representation of what is going to be in the texture and the depth per channel ? The actual order of R G B A bytes is up to OGL driver.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Similar Content

    • By _OskaR
      I have an OpenGL application but without possibility to wite own shaders.
      I need to perform small VS modification - is possible to do it in an alternative way? Do we have apps or driver modifictions which will catch the shader sent to GPU and override it?
    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
      #define NUM_LIGHTS 2
      struct Light
          vec3 position;
          vec3 diffuse;
          float attenuation;
      uniform Light Lights[NUM_LIGHTS];
    • By pr033r
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article ( inspirate from another code (here: but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch):
      Exe file (if you want to look) and models folder (for those who will download the sources):
      Thanks for any help...

  • Popular Now