diff --git a/engine/src/flutter/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ExternalTextureTests.java b/engine/src/flutter/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ExternalTextureTests.java new file mode 100644 index 0000000000..1894a0b563 --- /dev/null +++ b/engine/src/flutter/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ExternalTextureTests.java @@ -0,0 +1,111 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package dev.flutter.scenariosui; + +import android.content.Intent; +import android.graphics.Rect; +import android.os.Build.VERSION_CODES; +import androidx.annotation.NonNull; +import androidx.test.filters.LargeTest; +import androidx.test.filters.SdkSuppress; +import androidx.test.rule.ActivityTestRule; +import androidx.test.runner.AndroidJUnit4; +import dev.flutter.scenarios.ExternalTextureFlutterActivity; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +@LargeTest +public class ExternalTextureTests { + private static final int SURFACE_WIDTH = 192; + private static final int SURFACE_HEIGHT = 256; + + Intent intent; + + @Rule @NonNull + public ActivityTestRule activityRule = + new ActivityTestRule<>( + ExternalTextureFlutterActivity.class, + /*initialTouchMode=*/ false, + /*launchActivity=*/ false); + + @Before + public void setUp() { + intent = new Intent(Intent.ACTION_MAIN); + } + + @Test + public void testCanvasSurface() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "canvas"); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.LOLLIPOP) + public void testMediaSurface() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "media"); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.LOLLIPOP) + public void testRotatedMediaSurface_90() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "media"); + intent.putExtra("rotation", 90); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.LOLLIPOP) + public void testRotatedMediaSurface_180() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "media"); + intent.putExtra("rotation", 180); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.LOLLIPOP) + public void testRotatedMediaSurface_270() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "media"); + intent.putExtra("rotation", 270); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.M) + public void testCroppedMediaSurface_bottomLeft() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "image"); + intent.putExtra("crop", new Rect(0, 0, SURFACE_WIDTH / 2, SURFACE_HEIGHT / 2)); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.M) + public void testCroppedMediaSurface_topRight() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "image"); + intent.putExtra( + "crop", new Rect(SURFACE_WIDTH / 2, SURFACE_HEIGHT / 2, SURFACE_WIDTH, SURFACE_HEIGHT)); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } + + @Test + @SdkSuppress(minSdkVersion = VERSION_CODES.M) + public void testCroppedRotatedMediaSurface_bottomLeft_90() throws Exception { + intent.putExtra("scenario", "display_texture"); + intent.putExtra("surface_renderer", "image"); + intent.putExtra("crop", new Rect(0, 0, SURFACE_WIDTH / 2, SURFACE_HEIGHT / 2)); + intent.putExtra("rotation", 90); + ScreenshotUtil.capture(activityRule.launchActivity(intent)); + } +} diff --git a/engine/src/flutter/testing/scenario_app/android/app/src/main/AndroidManifest.xml b/engine/src/flutter/testing/scenario_app/android/app/src/main/AndroidManifest.xml index 4f65e21e5d..31339af1c5 100644 --- a/engine/src/flutter/testing/scenario_app/android/app/src/main/AndroidManifest.xml +++ b/engine/src/flutter/testing/scenario_app/android/app/src/main/AndroidManifest.xml @@ -39,6 +39,19 @@ + + + + + + = VERSION_CODES.M) { + // CanvasSurfaceRenderer doesn't work correctly when used with ImageSurfaceRenderer. + // Use MediaSurfaceRenderer for now. + return new ImageSurfaceRenderer( + selectSurfaceRenderer("media", extras), extras.getParcelable("crop")); + } else { + throw new RuntimeException("ImageSurfaceRenderer not supported"); + } + case "media": + if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + return new MediaSurfaceRenderer(this::createMediaExtractor, extras.getInt("rotation", 0)); + } else { + throw new RuntimeException("MediaSurfaceRenderer not supported"); + } + case "canvas": + default: + return new CanvasSurfaceRenderer(); + } + } + + private MediaExtractor createMediaExtractor() { + // Sample Video generated with FFMPEG. + // ffmpeg -loop 1 -i ~/engine/src/flutter/lib/ui/fixtures/DashInNooglerHat.jpg -c:v libx264 + // -profile:v main -level:v 5.2 -t 1 -vf scale=192:256 -b:v 1M sample.mp4 + try { + MediaExtractor extractor = new MediaExtractor(); + AssetFileDescriptor afd = getAssets().openFd("sample.mp4"); + extractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); + return extractor; + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + @Override + public void onPause() { + surfaceViewRenderer.destroy(); + flutterRenderer.destroy(); + surfaceTextureEntry.release(); + super.onPause(); + } + + @Override + public void onFlutterUiDisplayed() { + surfaceTextureEntry = getFlutterEngine().getRenderer().createSurfaceTexture(); + SurfaceTexture surfaceTexture = surfaceTextureEntry.surfaceTexture(); + surfaceTexture.setDefaultBufferSize(SURFACE_WIDTH, SURFACE_HEIGHT); + flutterRenderer.attach(new Surface(surfaceTexture), firstFrameLatch); + flutterRenderer.repaint(); + textureId = surfaceTextureEntry.id(); + + super.onFlutterUiDisplayed(); + } + + @Override + protected void getScenarioParams(@NonNull Map args) { + super.getScenarioParams(args); + args.put("texture_id", textureId); + args.put("texture_width", SURFACE_WIDTH); + args.put("texture_height", SURFACE_HEIGHT); + } + + private interface SurfaceRenderer { + void attach(Surface surface, CountDownLatch onFirstFrame); + + default boolean canProduceFrames() { + return true; + } + + void repaint(); + + void destroy(); + } + + /** Paints a simple gradient onto the attached Surface. */ + private static class CanvasSurfaceRenderer implements SurfaceRenderer { + private Surface surface; + private CountDownLatch onFirstFrame; + + protected CanvasSurfaceRenderer() {} + + @Override + public void attach(Surface surface, CountDownLatch onFirstFrame) { + this.surface = surface; + this.onFirstFrame = onFirstFrame; + } + + @Override + public void repaint() { + Canvas canvas = + VERSION.SDK_INT >= VERSION_CODES.M + ? surface.lockHardwareCanvas() + : surface.lockCanvas(null); + Paint paint = new Paint(); + paint.setShader( + new LinearGradient( + 0.0f, + 0.0f, + canvas.getWidth(), + canvas.getHeight(), + new int[] { + // Cyan (#00FFFF) + 0xFF00FFFF, + // Magenta (#FF00FF) + 0xFFFF00FF, + // Yellow (#FFFF00) + 0xFFFFFF00, + }, + null, + TileMode.REPEAT)); + canvas.drawPaint(paint); + surface.unlockCanvasAndPost(canvas); + + if (onFirstFrame != null) { + onFirstFrame.countDown(); + onFirstFrame = null; + } + } + + @Override + public void destroy() {} + } + + /** Decodes a sample video into the attached Surface. */ + @RequiresApi(VERSION_CODES.LOLLIPOP) + private static class MediaSurfaceRenderer implements SurfaceRenderer { + private final Supplier extractorSupplier; + private final int rotation; + private CountDownLatch onFirstFrame; + + private Surface surface; + private MediaExtractor extractor; + private MediaFormat format; + private Thread decodeThread; + private final AtomicBoolean atomicCanProduceFrames = new AtomicBoolean(true); + + protected MediaSurfaceRenderer(Supplier extractorSupplier, int rotation) { + this.extractorSupplier = extractorSupplier; + this.rotation = rotation; + } + + @Override + public void attach(Surface surface, CountDownLatch onFirstFrame) { + this.surface = surface; + this.onFirstFrame = onFirstFrame; + + extractor = extractorSupplier.get(); + format = extractor.getTrackFormat(0); + + // NOTE: MediaFormat.KEY_ROTATION was not available until 23+, but the key is still handled on + // API 21+. + format.setInteger("rotation-degrees", rotation); + + decodeThread = new Thread(this::decodeThreadMain); + decodeThread.start(); + } + + @Override + public boolean canProduceFrames() { + return atomicCanProduceFrames.get(); + } + + private void decodeThreadMain() { + try { + MediaCodec codec = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME)); + codec.configure(format, surface, null, 0); + codec.start(); + + // Track 0 is always the video track, since the sample video doesn't contain audio. + extractor.selectTrack(0); + + MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); + boolean seenEOS = false; + long startTimeNs = System.nanoTime(); + + while (true) { + // Move samples (video frames) from the extractor into the decoder, as long as we haven't + // consumed all samples. + if (!seenEOS) { + int inputBufferIndex = codec.dequeueInputBuffer(-1); + ByteBuffer inputBuffer = codec.getInputBuffer(inputBufferIndex); + int sampleSize = extractor.readSampleData(inputBuffer, 0); + if (sampleSize >= 0) { + long presentationTimeUs = extractor.getSampleTime(); + codec.queueInputBuffer(inputBufferIndex, 0, sampleSize, presentationTimeUs, 0); + extractor.advance(); + } else { + codec.queueInputBuffer( + inputBufferIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM); + seenEOS = true; + } + } + + // Then consume decoded video frames from the decoder. These frames are automatically + // pushed to the attached Surface, so this schedules them for present. + int outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 10000); + boolean lastBuffer = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0; + if (outputBufferIndex >= 0) { + if (bufferInfo.size > 0) { + if (onFirstFrame != null) { + onFirstFrame.countDown(); + onFirstFrame = null; + } + + codec.releaseOutputBuffer( + outputBufferIndex, startTimeNs + (bufferInfo.presentationTimeUs * 1000)); + } + } + + // Once we present the last frame, mark this renderer as no longer producing frames and + // exit the loop. + if (lastBuffer) { + atomicCanProduceFrames.set(false); + break; + } + } + + codec.stop(); + codec.release(); + extractor.release(); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + @Override + public void repaint() {} + + @Override + public void destroy() { + try { + decodeThread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + } + + /** + * Takes frames from the inner SurfaceRenderer and feeds it through an ImageReader and ImageWriter + * pair. + */ + @RequiresApi(VERSION_CODES.M) + private static class ImageSurfaceRenderer implements SurfaceRenderer { + private final SurfaceRenderer inner; + private final Rect crop; + + private CountDownLatch onFirstFrame; + private ImageReader reader; + private ImageWriter writer; + + private Handler handler; + private HandlerThread handlerThread; + + private boolean canReadImage = true; + private boolean canWriteImage = true; + + protected ImageSurfaceRenderer(SurfaceRenderer inner, Rect crop) { + this.inner = inner; + this.crop = crop; + } + + @Override + public void attach(Surface surface, CountDownLatch onFirstFrame) { + this.onFirstFrame = onFirstFrame; + writer = ImageWriter.newInstance(surface, 3); + reader = ImageReader.newInstance(SURFACE_WIDTH, SURFACE_HEIGHT, writer.getFormat(), 2); + + inner.attach(reader.getSurface(), null); + + handlerThread = new HandlerThread("image reader/writer thread"); + handlerThread.start(); + + handler = new Handler(handlerThread.getLooper()); + reader.setOnImageAvailableListener(this::onImageAvailable, handler); + writer.setOnImageReleasedListener(this::onImageReleased, handler); + } + + private void onImageAvailable(ImageReader reader) { + Log.v(TAG, "Image available"); + + // If the inner SurfaceRenderer isn't producing frames, don't try to acquire an image. + if (!inner.canProduceFrames()) { + Log.i(TAG, "Inner SurfaceRenderer no longer producing frames, ignoring"); + return; + } + + if (!canWriteImage) { + // If the ImageWriter hasn't released the latest image, don't attempt to enqueue another + // image. + // Otherwise the reader writer pair locks up if the writer runs behind, as the reader runs + // out of images and the writer has no more space for images. + canReadImage = true; + return; + } + + canReadImage = false; + Image image = reader.acquireLatestImage(); + image.setCropRect(crop); + try { + canWriteImage = false; + writer.queueInputImage(image); + } catch (IllegalStateException e) { + // If the output surface disconnects, this method will be interrupted with an + // IllegalStateException. + // Simply log and return. + Log.i(TAG, "Surface disconnected from ImageWriter"); + return; + } + + Log.v(TAG, "Output image"); + + if (onFirstFrame != null) { + onFirstFrame.countDown(); + onFirstFrame = null; + } + } + + private void tryAcquireImage() { + if (canReadImage) { + onImageAvailable(reader); + } + } + + private void onImageReleased(ImageWriter imageWriter) { + Log.v(TAG, "Image released"); + + if (!canWriteImage) { + canWriteImage = true; + if (canReadImage) { + // Try acquire the image in a handler message, as we may have another call to + // onImageAvailable in the thread's message queue. + handler.post(this::tryAcquireImage); + } + } + } + + @Override + public void repaint() { + inner.repaint(); + } + + @Override + public void destroy() { + Log.i(TAG, "Destroying ImageSurfaceRenderer"); + inner.destroy(); + handler.post(this::destroyReaderWriter); + } + + private void destroyReaderWriter() { + writer.close(); + Log.i(TAG, "ImageWriter destroyed"); + reader.close(); + Log.i(TAG, "ImageReader destroyed"); + handlerThread.quitSafely(); + } + } + + private static class SurfaceRendererCallback implements SurfaceHolder.Callback { + final SurfaceRenderer surfaceRenderer; + final CountDownLatch onFirstFrame; + + public SurfaceRendererCallback(SurfaceRenderer surfaceRenderer, CountDownLatch onFirstFrame) { + this.surfaceRenderer = surfaceRenderer; + this.onFirstFrame = onFirstFrame; + } + + @Override + public void surfaceCreated(@NonNull SurfaceHolder holder) { + surfaceRenderer.attach(holder.getSurface(), onFirstFrame); + } + + @Override + public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) { + surfaceRenderer.repaint(); + } + + @Override + public void surfaceDestroyed(@NonNull SurfaceHolder holder) {} + } +} diff --git a/engine/src/flutter/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestActivity.java b/engine/src/flutter/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestActivity.java index 7bda90a54b..adf776d8ac 100644 --- a/engine/src/flutter/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestActivity.java +++ b/engine/src/flutter/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestActivity.java @@ -78,9 +78,17 @@ public abstract class TestActivity extends TestableFlutterActivity { test.put("name", "animated_color_square"); } test.put("use_android_view", launchIntent.getBooleanExtra("use_android_view", false)); + getScenarioParams(test); channel.invokeMethod("set_scenario", test); } + /** + * Populates test-specific parameters that are sent to the Dart test scenario. + * + * @param args The map of test arguments + */ + protected void getScenarioParams(@NonNull Map args) {} + protected void writeTimelineData(@Nullable Uri logFile) { if (logFile == null) { throw new IllegalArgumentException(); diff --git a/engine/src/flutter/testing/scenario_app/lib/src/scenarios.dart b/engine/src/flutter/testing/scenario_app/lib/src/scenarios.dart index e7ff5bfcd2..5515e17d87 100644 --- a/engine/src/flutter/testing/scenario_app/lib/src/scenarios.dart +++ b/engine/src/flutter/testing/scenario_app/lib/src/scenarios.dart @@ -4,6 +4,8 @@ import 'dart:ui'; +import 'package:scenario_app/src/texture.dart'; + import 'animated_color_square.dart'; import 'bogus_font_text.dart'; import 'initial_route_reply.dart'; @@ -49,6 +51,7 @@ Map _scenarios = { 'bogus_font_text': () => BogusFontText(PlatformDispatcher.instance), 'spawn_engine_works' : () => BogusFontText(PlatformDispatcher.instance), 'pointer_events': () => TouchesScenario(PlatformDispatcher.instance), + 'display_texture': () => DisplayTexture(PlatformDispatcher.instance), }; Map _currentScenarioParams = {}; diff --git a/engine/src/flutter/testing/scenario_app/lib/src/texture.dart b/engine/src/flutter/testing/scenario_app/lib/src/texture.dart new file mode 100644 index 0000000000..1dd00ecaeb --- /dev/null +++ b/engine/src/flutter/testing/scenario_app/lib/src/texture.dart @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:ui'; + +import 'package:scenario_app/src/scenarios.dart'; + +import 'channel_util.dart'; +import 'scenario.dart'; + +/// Displays a platform texture with the given width and height. +class DisplayTexture extends Scenario { + /// Creates the DisplayTexture scenario. + /// + /// The [dispatcher] parameter must not be null. + DisplayTexture(PlatformDispatcher dispatcher) + : super(dispatcher); + + int get _textureId => scenarioParams['texture_id'] as int; + double get _textureWidth => + (scenarioParams['texture_width'] as num).toDouble(); + double get _textureHeight => + (scenarioParams['texture_height'] as num).toDouble(); + + @override + void onBeginFrame(Duration duration) { + final SceneBuilder builder = SceneBuilder(); + builder.addTexture( + _textureId, + offset: Offset( + (window.physicalSize.width / 2.0) - (_textureWidth / 2.0), + 0.0, + ), + width: _textureWidth, + height: _textureHeight, + ); + final Scene scene = builder.build(); + window.render(scene); + scene.dispose(); + + sendJsonMessage( + dispatcher: dispatcher, + channel: 'display_data', + json: { + 'data': 'ready', + }, + ); + } +}