Crazy Redd
Crazy Redd

Reputation: 619

How do I write to a video file from an LWJGL Display?

So I have learnt how to take a screenshot of my LWJGL Display by reading the byte buffer from GL_FRONT with:

public static void takeScreenShot(){
    GL11.glReadBuffer(GL11.GL_FRONT);
    int width = Display.getDisplayMode().getWidth();
    int height = Display.getDisplayMode().getHeight();
    int bpp = 4;
    ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp);
    GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_NSIGNED_BYTE, buffer);
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
    Date date = new Date();
    String datetime = dateFormat.format(date);
    File file = new File(screenshot_dir + "\\" + datetime + ".png");
    String format = "PNG";
    BufferedImage image = new BufferedImage(width, height, Bufferedmage.TYPE_INT_RGB);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            int i = (x + (width * y)) * bpp;
            int r = buffer.get(i) & 0xFF;
            int g = buffer.get(i + 1) & 0xFF;
            int b = buffer.get(i + 2) & 0xFF;
            image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | );
        }
    }
    try {
        ImageIO.write(image, format, file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I assume I can just keep reading from the front buffer about 60 times a second (I know this will dramatically decrease performance). Then I can just write a certain number of frames into a buffer, which would be swapped to another when it is full. After a buffer is full, its contents can then be appended to a file.

How do I format the byte buffers to be frames in a video?

Thank you.

Upvotes: 4

Views: 675

Answers (1)

eliaspr
eliaspr

Reputation: 322

Your question is indeed very old, but for the sake of completeness, I'm going to answer it anyways.

My answer is too big to provide examples or explain. That's why I'm linking other people's tutorials and official documentation.

  1. Render the scene (or whatever) to a 2D texture. (http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/)
  2. Retrieve the texture data using glGetTexImage (https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetTexImage.xhtml)
  3. Download a Java Library for encoding MP4 (or whatever you want) and encode frame after frame.

Here's some pseudocode:

create framebuffer
enable framebuffer
for all frames {
    render to framebuffer
    glGetTexImage(...)
    library.encodeFrame(imageData)
}

This is very general and it depends heavily on the library you use for encoding.

Upvotes: 2

Related Questions