### Implement Video Playback with MoviePlayer Source: https://context7.com/google/grafika/llms.txt Shows how to initialize and control video playback using the MoviePlayer class. This includes setting up a Surface, configuring loop mode, and using PlayTask to handle decoding on a background thread. ```java import com.android.grafika.MoviePlayer; import com.android.grafika.SpeedControlCallback; import android.view.Surface; import java.io.File; File videoFile = new File(context.getFilesDir(), "video.mp4"); Surface outputSurface = textureView.getSurface(); SpeedControlCallback frameCallback = new SpeedControlCallback(); MoviePlayer player = new MoviePlayer(videoFile, outputSurface, frameCallback); player.setLoopMode(true); MoviePlayer.PlayTask playTask = new MoviePlayer.PlayTask(player, new MoviePlayer.PlayerFeedback() { @Override public void playbackStopped() { Log.d(TAG, "Playback finished"); } }); playTask.execute(); playTask.requestStop(); playTask.waitForStop(); ``` -------------------------------- ### Encode H.264 Video with VideoEncoderCore Source: https://context7.com/google/grafika/llms.txt Demonstrates how to initialize VideoEncoderCore, obtain an input Surface for OpenGL rendering, and manage the encoding lifecycle including draining the encoder and releasing resources. ```java import com.android.grafika.VideoEncoderCore; import android.view.Surface; import java.io.File; int width = 1280; int height = 720; int bitRate = 6000000; File outputFile = new File(context.getFilesDir(), "encoded-video.mp4"); VideoEncoderCore encoder = new VideoEncoderCore(width, height, bitRate, outputFile); Surface inputSurface = encoder.getInputSurface(); EglCore eglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); WindowSurface encoderSurface = new WindowSurface(eglCore, inputSurface, true); encoderSurface.makeCurrent(); GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); encoderSurface.setPresentationTime(System.nanoTime()); encoder.drainEncoder(false); encoderSurface.swapBuffers(); encoder.drainEncoder(true); encoder.release(); encoderSurface.release(); eglCore.release(); ``` -------------------------------- ### Implement Circular Buffer Recording with CircularEncoder Source: https://context7.com/google/grafika/llms.txt Shows how to configure a circular buffer for video recording, handle callbacks for file saving, and trigger the save operation to capture the last N seconds of video. ```java import com.android.grafika.CircularEncoder; import android.view.Surface; import java.io.File; int width = 1280; int height = 720; int bitRate = 6000000; int frameRate = 30; int desiredSpanSec = 7; CircularEncoder.Callback callback = new CircularEncoder.Callback() { @Override public void fileSaveComplete(int status) { if (status == 0) Log.d(TAG, "Video saved successfully"); } @Override public void bufferStatus(long totalTimeMsec) { Log.d(TAG, "Buffer contains " + totalTimeMsec + "ms of video"); } }; CircularEncoder circularEncoder = new CircularEncoder(width, height, bitRate, frameRate, desiredSpanSec, callback); Surface inputSurface = circularEncoder.getInputSurface(); EglCore eglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); WindowSurface encoderSurface = new WindowSurface(eglCore, inputSurface, true); circularEncoder.frameAvailableSoon(); encoderSurface.makeCurrent(); encoderSurface.setPresentationTime(timestampNanos); encoderSurface.swapBuffers(); File outputFile = new File(context.getFilesDir(), "instant-replay.mp4"); circularEncoder.saveVideo(outputFile); circularEncoder.shutdown(); ``` -------------------------------- ### Configure Texture2dProgram for Shaders and Filters Source: https://context7.com/google/grafika/llms.txt Demonstrates initializing Texture2dProgram with different types, configuring convolution kernels for image processing, and executing draw calls with transformation matrices. It requires an active OpenGL ES context and appropriate vertex/texture buffers. ```java import com.android.grafika.gles.Texture2dProgram; import com.android.grafika.gles.Texture2dProgram.ProgramType; import android.opengl.GLES20; import java.nio.FloatBuffer; Texture2dProgram program = new Texture2dProgram(ProgramType.TEXTURE_EXT); Texture2dProgram bwProgram = new Texture2dProgram(ProgramType.TEXTURE_EXT_BW); Texture2dProgram filterProgram = new Texture2dProgram(ProgramType.TEXTURE_EXT_FILT); float[] blurKernel = {1f/16f, 2f/16f, 1f/16f, 2f/16f, 4f/16f, 2f/16f, 1f/16f, 2f/16f, 1f/16f}; filterProgram.setKernel(blurKernel, 0.0f); filterProgram.setTexSize(1280, 720); int textureId = program.createTextureObject(); float[] mvpMatrix = new float[16]; float[] texMatrix = new float[16]; Matrix.setIdentityM(mvpMatrix, 0); surfaceTexture.getTransformMatrix(texMatrix); program.draw(mvpMatrix, vertexBuffer, 0, 4, 2, 8, texMatrix, texCoordBuffer, textureId, 8); program.release(); ``` -------------------------------- ### Configure and Control TextureMovieEncoder Source: https://context7.com/google/grafika/llms.txt This snippet demonstrates how to initialize the TextureMovieEncoder, configure it with an output file and EGL context, and manage the recording lifecycle. It also shows how to hook into the SurfaceTexture frame availability listener to trigger frame encoding. ```java import com.android.grafika.TextureMovieEncoder; import com.android.grafika.TextureMovieEncoder.EncoderConfig; import android.graphics.SurfaceTexture; import android.opengl.EGL14; import java.io.File; TextureMovieEncoder videoEncoder = new TextureMovieEncoder(); File outputFile = new File(context.getFilesDir(), "recording.mp4"); EGLContext sharedContext = EGL14.eglGetCurrentContext(); EncoderConfig config = new EncoderConfig( outputFile, 640, 480, 1000000, sharedContext ); videoEncoder.startRecording(config); videoEncoder.setTextureId(cameraTextureId); SurfaceTexture cameraSurfaceTexture = new SurfaceTexture(cameraTextureId); cameraSurfaceTexture.setOnFrameAvailableListener(st -> { st.updateTexImage(); videoEncoder.frameAvailable(st); }); boolean isRecording = videoEncoder.isRecording(); videoEncoder.updateSharedContext(EGL14.eglGetCurrentContext()); videoEncoder.stopRecording(); ``` -------------------------------- ### TextureMovieEncoder Usage Source: https://context7.com/google/grafika/llms.txt Demonstrates the typical workflow for using TextureMovieEncoder to record video from a camera preview texture. ```APIDOC ## TextureMovieEncoder - Threaded Video Recording from GL Texture TextureMovieEncoder runs video encoding on a dedicated thread, receiving frames from an external GL texture (e.g., camera preview). It handles EGL context sharing and manages encoder lifecycle. ### Initialization and Configuration ```java import com.android.grafika.TextureMovieEncoder; import com.android.grafika.TextureMovieEncoder.EncoderConfig; import android.graphics.SurfaceTexture; import android.opengl.EGL14; import java.io.File; // Create encoder instance (can be static to survive Activity restarts) TextureMovieEncoder videoEncoder = new TextureMovieEncoder(); // Configure encoder with output file, dimensions, bitrate, and shared EGL context File outputFile = new File(context.getFilesDir(), "recording.mp4"); EGLContext sharedContext = EGL14.eglGetCurrentContext(); EncoderConfig config = new EncoderConfig( outputFile, // output file path 640, // encoded width 480, // encoded height 1000000, // bitrate (1 Mbps) sharedContext // EGL context to share textures with ); ``` ### Starting and Frame Handling ```java // Start recording (creates encoder thread) videoEncoder.startRecording(config); // Set the texture ID that receives camera frames videoEncoder.setTextureId(cameraTextureId); // For each frame from camera, notify encoder SurfaceTexture cameraSurfaceTexture = new SurfaceTexture(cameraTextureId); cameraSurfaceTexture.setOnFrameAvailableListener(st -> { // Update texture and notify encoder st.updateTexImage(); videoEncoder.frameAvailable(st); }); ``` ### Status and Context Management ```java // Check if currently recording boolean isRecording = videoEncoder.isRecording(); // Update shared context if EGL context was recreated EGLContext newContext = EGL14.eglGetCurrentContext(); videoEncoder.updateSharedContext(newContext); ``` ### Stopping Recording ```java // Stop recording videoEncoder.stopRecording(); ``` ``` -------------------------------- ### Render Full-Screen Textures with FullFrameRect Source: https://context7.com/google/grafika/llms.txt Shows how to use FullFrameRect to simplify rendering a full-screen quad. It covers creating the texture object, updating the SurfaceTexture, and dynamically switching shader programs during the render loop. ```java import com.android.grafika.gles.FullFrameRect; import com.android.grafika.gles.Texture2dProgram; import android.graphics.SurfaceTexture; Texture2dProgram program = new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT); FullFrameRect fullScreen = new FullFrameRect(program); int textureId = fullScreen.createTextureObject(); SurfaceTexture surfaceTexture = new SurfaceTexture(textureId); float[] texMatrix = new float[16]; surfaceTexture.updateTexImage(); surfaceTexture.getTransformMatrix(texMatrix); fullScreen.drawFrame(textureId, texMatrix); Texture2dProgram bwProgram = new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT_BW); fullScreen.changeProgram(bwProgram); fullScreen.getProgram().setTexSize(1280, 720); fullScreen.release(true); ``` -------------------------------- ### WindowSurface: EGL Surface Management for Android Source: https://context7.com/google/grafika/llms.txt WindowSurface simplifies EGL surface creation and management for Android Surfaces and SurfaceTextures. It provides methods for making surfaces current, swapping buffers, and saving frames, supporting both native surfaces and SurfaceTextures. ```java import com.android.grafika.gles.EglCore; import com.android.grafika.gles.WindowSurface; import android.graphics.SurfaceTexture; import android.view.Surface; import java.io.File; // Create EglCore first EglCore eglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); // Create WindowSurface from Android Surface (e.g., MediaCodec input) Surface inputSurface = videoEncoder.getInputSurface(); WindowSurface windowSurface = new WindowSurface(eglCore, inputSurface, true); // Or create from SurfaceTexture (e.g., for camera preview) SurfaceTexture surfaceTexture = new SurfaceTexture(textureId); WindowSurface textureSurface = new WindowSurface(eglCore, surfaceTexture); // Make surface current before rendering windowSurface.makeCurrent(); // Get surface dimensions int width = windowSurface.getWidth(); int height = windowSurface.getHeight(); // Render your OpenGL content here... GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // Set presentation time for video encoding windowSurface.setPresentationTime(timestampNanos); // Swap buffers to display/encode the frame windowSurface.swapBuffers(); // Save current frame to PNG file File outputFile = new File(context.getFilesDir(), "frame.png"); windowSurface.saveFrame(outputFile); // Recreate surface with new EglCore (e.g., after context change) EglCore newEglCore = new EglCore(newSharedContext, EglCore.FLAG_RECORDABLE); windowSurface.recreate(newEglCore); // Release when done windowSurface.release(); ``` -------------------------------- ### Perform OpenGL ES Operations with GlUtil Source: https://context7.com/google/grafika/llms.txt Demonstrates how to compile shader programs, manage textures, create vertex buffers, and check for OpenGL errors using the GlUtil utility class. It requires an active OpenGL context and provides helper methods to reduce boilerplate code. ```java import com.android.grafika.gles.GlUtil; import android.opengl.GLES20; import java.nio.ByteBuffer; import java.nio.FloatBuffer; String vertexShader = "uniform mat4 uMVPMatrix;\nattribute vec4 aPosition;\nvoid main() {\n gl_Position = uMVPMatrix * aPosition;\n}\n"; String fragmentShader = "precision mediump float;\nvoid main() {\n gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n}\n"; int programHandle = GlUtil.createProgram(vertexShader, fragmentShader); GlUtil.checkGlError("glBindTexture"); int positionLoc = GLES20.glGetAttribLocation(programHandle, "aPosition"); GlUtil.checkLocation(positionLoc, "aPosition"); ByteBuffer imageData = ByteBuffer.allocateDirect(width * height * 4); int textureHandle = GlUtil.createImageTexture(imageData, width, height, GLES20.GL_RGBA); float[] vertices = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f }; FloatBuffer vertexBuffer = GlUtil.createFloatBuffer(vertices); float[] mvpMatrix = GlUtil.IDENTITY_MATRIX; GlUtil.logVersionInfo(); ``` -------------------------------- ### WindowSurface - Recordable EGL Window Surface Source: https://context7.com/google/grafika/llms.txt WindowSurface wraps EGL surface creation and management for Android Surfaces and SurfaceTextures, providing methods for making surfaces current, swapping buffers, and saving frames. ```APIDOC ## WindowSurface - Recordable EGL Window Surface ### Description WindowSurface wraps EGL surface creation and management for both native Android Surfaces and SurfaceTextures. It provides convenient methods for making surfaces current, swapping buffers, and saving frames to files. ### Method N/A (Class Usage) ### Endpoint N/A (Class Usage) ### Parameters N/A (Class Usage) ### Request Example ```java import com.android.grafika.gles.EglCore; import com.android.grafika.gles.WindowSurface; import android.graphics.SurfaceTexture; import android.view.Surface; import java.io.File; // Create EglCore first EglCore eglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); // Create WindowSurface from Android Surface (e.g., MediaCodec input) Surface inputSurface = videoEncoder.getInputSurface(); WindowSurface windowSurface = new WindowSurface(eglCore, inputSurface, true); // Or create from SurfaceTexture (e.g., for camera preview) SurfaceTexture surfaceTexture = new SurfaceTexture(textureId); WindowSurface textureSurface = new WindowSurface(eglCore, surfaceTexture); // Make surface current before rendering windowSurface.makeCurrent(); // Get surface dimensions int width = windowSurface.getWidth(); int height = windowSurface.getHeight(); // Render your OpenGL content here... GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // Set presentation time for video encoding windowSurface.setPresentationTime(timestampNanos); // Swap buffers to display/encode the frame windowSurface.swapBuffers(); // Save current frame to PNG file File outputFile = new File(context.getFilesDir(), "frame.png"); windowSurface.saveFrame(outputFile); // Recreate surface with new EglCore (e.g., after context change) EglCore newEglCore = new EglCore(newSharedContext, EglCore.FLAG_RECORDABLE); windowSurface.recreate(newEglCore); // Release when done windowSurface.release(); ``` ### Response N/A (Class Usage) ### Response Example N/A (Class Usage) ``` -------------------------------- ### Implement CameraRenderer for OpenGL Preview and Recording Source: https://context7.com/google/grafika/llms.txt A custom GLSurfaceView.Renderer implementation that manages a SurfaceTexture for camera input, applies real-time shader filters via FullFrameRect, and handles video encoding with TextureMovieEncoder. This class demonstrates how to synchronize frame updates and trigger recording sessions within an OpenGL rendering loop. ```java public class CameraRenderer implements GLSurfaceView.Renderer { private FullFrameRect mFullScreen; private SurfaceTexture mSurfaceTexture; private int mTextureId; private float[] mSTMatrix = new float[16]; private TextureMovieEncoder mVideoEncoder; private boolean mRecording = false; @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { mFullScreen = new FullFrameRect(new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT)); mTextureId = mFullScreen.createTextureObject(); mSurfaceTexture = new SurfaceTexture(mTextureId); mVideoEncoder = new TextureMovieEncoder(); } public void startRecording(File outputFile) { TextureMovieEncoder.EncoderConfig config = new TextureMovieEncoder.EncoderConfig(outputFile, 640, 480, 1000000, EGL14.eglGetCurrentContext()); mVideoEncoder.startRecording(config); mVideoEncoder.setTextureId(mTextureId); mRecording = true; } @Override public void onDrawFrame(GL10 gl) { mSurfaceTexture.updateTexImage(); mSurfaceTexture.getTransformMatrix(mSTMatrix); if (mRecording) { mVideoEncoder.frameAvailable(mSurfaceTexture); } mFullScreen.drawFrame(mTextureId, mSTMatrix); } } ``` -------------------------------- ### EglCore: EGL State Management for Android Graphics Source: https://context7.com/google/grafika/llms.txt EglCore manages EGL display, context, and configuration for OpenGL ES 2/3. It supports shared contexts for video encoding and recordable surfaces required by MediaCodec, handling EGL initialization and surface creation. ```java import com.android.grafika.gles.EglCore; import com.android.grafika.gles.WindowSurface; import android.opengl.EGLContext; import android.view.Surface; // Create EglCore with recordable flag for video encoding EglCore eglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); // Or create with shared context and GLES3 support EGLContext sharedContext = EGL14.eglGetCurrentContext(); EglCore sharedEglCore = new EglCore(sharedContext, EglCore.FLAG_RECORDABLE | EglCore.FLAG_TRY_GLES3); // Query GLES version int glVersion = eglCore.getGlVersion(); // Returns 2 or 3 // Create window surface from Android Surface Surface encoderSurface = mediaCodec.createInputSurface(); EGLSurface eglSurface = eglCore.createWindowSurface(encoderSurface); // Create offscreen surface for FBO rendering EGLSurface offscreenSurface = eglCore.createOffscreenSurface(1280, 720); // Make context current eglCore.makeCurrent(eglSurface); // Set presentation timestamp for video encoding (nanoseconds) eglCore.setPresentationTime(eglSurface, System.nanoTime()); // Swap buffers to publish frame boolean success = eglCore.swapBuffers(eglSurface); // Release resources when done eglCore.releaseSurface(eglSurface); eglCore.release(); ``` -------------------------------- ### GlUtil - OpenGL ES Utility Functions Source: https://context7.com/google/grafika/llms.txt Provides static utility methods for common OpenGL ES operations including shader compilation, program linking, texture creation, error checking, and buffer allocation. ```APIDOC ## GlUtil - OpenGL ES Utility Functions ### Description Provides static utility methods for common OpenGL ES operations including shader compilation, program linking, texture creation, error checking, and buffer allocation. ### Methods - `createProgram(String vertexShader, String fragmentShader)`: Creates an OpenGL ES shader program. - `checkGlError(String op)`: Checks for OpenGL ES errors and throws a RuntimeException if an error occurred. - `checkLocation(int location, String label)`: Validates a shader attribute or uniform location. - `createImageTexture(ByteBuffer imageData, int width, int height, int format)`: Creates an OpenGL ES texture from raw image data. - `createFloatBuffer(float[] vertices)`: Creates a FloatBuffer from a float array. - `logVersionInfo()`: Logs OpenGL ES version information. ### Constants - `IDENTITY_MATRIX`: A 4x4 identity matrix. ``` -------------------------------- ### EglCore - Core EGL State Management Source: https://context7.com/google/grafika/llms.txt EglCore manages EGL display, context, and configuration, supporting GLES2/GLES3, shared contexts for video encoding, and recordable surface configurations for MediaCodec. ```APIDOC ## EglCore - Core EGL State Management ### Description EglCore provides core EGL state management including display, context, and configuration. It handles EGL initialization with support for GLES2/GLES3, shared contexts for video encoding, and recordable surface configurations required by MediaCodec. ### Method N/A (Class Usage) ### Endpoint N/A (Class Usage) ### Parameters N/A (Class Usage) ### Request Example ```java import com.android.grafika.gles.EglCore; import com.android.grafika.gles.WindowSurface; import android.opengl.EGLContext; import android.view.Surface; // Create EglCore with recordable flag for video encoding EglCore eglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); // Or create with shared context and GLES3 support EGLContext sharedContext = EGL14.eglGetCurrentContext(); EglCore sharedEglCore = new EglCore(sharedContext, EglCore.FLAG_RECORDABLE | EglCore.FLAG_TRY_GLES3); // Query GLES version int glVersion = eglCore.getGlVersion(); // Returns 2 or 3 // Create window surface from Android Surface Surface encoderSurface = mediaCodec.createInputSurface(); EGLSurface eglSurface = eglCore.createWindowSurface(encoderSurface); // Create offscreen surface for FBO rendering EGLSurface offscreenSurface = eglCore.createOffscreenSurface(1280, 720); // Make context current eglCore.makeCurrent(eglSurface); // Set presentation timestamp for video encoding (nanoseconds) eglCore.setPresentationTime(eglSurface, System.nanoTime()); // Swap buffers to publish frame boolean success = eglCore.swapBuffers(eglSurface); // Release resources when done eglCore.releaseSurface(eglSurface); eglCore.release(); ``` ### Response N/A (Class Usage) ### Response Example N/A (Class Usage) ``` -------------------------------- ### MoviePlayer - Video Playback to Surface Source: https://context7.com/google/grafika/llms.txt Decodes video from MP4 files using MediaCodec and renders frames to a Surface. Supports loop playback, frame callbacks for timing control, and runs on a dedicated thread. ```APIDOC ## MoviePlayer - Video Playback to Surface ### Description Decodes video from MP4 files using MediaCodec and renders frames to a Surface. It supports loop playback, frame callbacks for timing control, and runs on a dedicated thread to avoid blocking the UI. ### Constructor - `MoviePlayer(File videoFile, Surface outputSurface, SpeedControlCallback frameCallback)`: Initializes the MoviePlayer. ### Methods - `getVideoWidth()`: Returns the width of the video. - `getVideoHeight()`: Returns the height of the video. - `setLoopMode(boolean loopMode)`: Enables or disables loop playback. ### Inner Classes - `PlayTask`: Manages video playback on a background thread. - `setLoopMode(boolean loopMode)`: Sets loop mode for the playback task. - `execute()`: Starts playback on a new thread. - `requestStop()`: Requests playback to stop. - `waitForStop()`: Waits for playback to complete. - `PlayerFeedback`: Interface for receiving playback status updates. - `playbackStopped()`: Callback when playback finishes. - `FrameCallback`: Interface for custom frame rendering control. - `preRender(long presentationTimeUsec)`: Called before a frame is rendered. - `postRender()`: Called after a frame render call returns. - `loopReset()`: Called when looped playback restarts. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.