Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/transition/ScreenRotationAnimation.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.wm.shell.transition;
18
19 import static android.hardware.HardwareBuffer.RGBA_8888;
20 import static android.hardware.HardwareBuffer.USAGE_PROTECTED_CONTENT;
21 import static android.util.RotationUtils.deltaRotation;
22 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
23 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_JUMPCUT;
24 import static android.view.WindowManagerPolicyConstants.SCREEN_FREEZE_LAYER_BASE;
25
26 import static com.android.wm.shell.transition.DefaultTransitionHandler.startSurfaceAnimation;
27 import static com.android.wm.shell.transition.Transitions.TAG;
28
29 import android.animation.Animator;
30 import android.animation.AnimatorListenerAdapter;
31 import android.animation.ArgbEvaluator;
32 import android.animation.ValueAnimator;
33 import android.annotation.NonNull;
34 import android.content.Context;
35 import android.graphics.Color;
36 import android.graphics.ColorSpace;
37 import android.graphics.Matrix;
38 import android.graphics.Rect;
39 import android.hardware.HardwareBuffer;
40 import android.media.Image;
41 import android.media.ImageReader;
42 import android.util.Slog;
43 import android.view.Surface;
44 import android.view.SurfaceControl;
45 import android.view.SurfaceControl.Transaction;
46 import android.view.SurfaceSession;
47 import android.view.animation.Animation;
48 import android.view.animation.AnimationUtils;
49 import android.window.TransitionInfo;
50
51 import com.android.internal.R;
52 import com.android.wm.shell.common.ShellExecutor;
53 import com.android.wm.shell.common.TransactionPool;
54
55 import java.nio.ByteBuffer;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58
59 /**
60 * This class handles the rotation animation when the device is rotated.
61 *
62 * <p>
63 * The screen rotation animation is composed of 3 different part:
64 * <ul>
65 * <li> The screenshot: <p>
66 * A screenshot of the whole screen prior the change of orientation is taken to hide the
67 * element resizing below. The screenshot is then animated to rotate and cross-fade to
68 * the new orientation with the content in the new orientation.
69 *
70 * <li> The windows on the display: <p>y
71 * Once the device is rotated, the screen and its content are in the new orientation. The
72 * animation first rotate the new content into the old orientation to then be able to
73 * animate to the new orientation
74 *
75 * <li> The Background color frame: <p>
76 * To have the animation seem more seamless, we add a color transitioning background behind the
77 * exiting and entering layouts. We compute the brightness of the start and end
78 * layouts and transition from the two brightness values as grayscale underneath the animation
79 * </ul>
80 */
81 class ScreenRotationAnimation {
82 static final int MAX_ANIMATION_DURATION = 10 * 1000;
83
84 private final Context mContext;
85 private final TransactionPool mTransactionPool;
86 private final float[] mTmpFloats = new float[9];
87 /** The leash of the changing window container. */
88 private final SurfaceControl mSurfaceControl;
89
90 private final int mAnimHint;
91 private final int mStartWidth;
92 private final int mStartHeight;
93 private final int mEndWidth;
94 private final int mEndHeight;
95 private final int mStartRotation;
96 private final int mEndRotation;
97
98 /** This layer contains the actual screenshot that is to be faded out. */
99 private SurfaceControl mScreenshotLayer;
100 /**
101 * Only used for screen rotation and not custom animations. Layered behind all other layers
102 * to avoid showing any "empty" spots
103 */
104 private SurfaceControl mBackColorSurface;
105 /** The leash using to animate screenshot layer. */
106 private final SurfaceControl mAnimLeash;
107
108 // The current active animation to move from the old to the new rotated
109 // state. Which animation is run here will depend on the old and new
110 // rotations.
111 private Animation mRotateExitAnimation;
112 private Animation mRotateEnterAnimation;
113 private Animation mRotateAlphaAnimation;
114
115 /** Intensity of light/whiteness of the layout before rotation occurs. */
116 private float mStartLuma;
117 /** Intensity of light/whiteness of the layout after rotation occurs. */
118 private float mEndLuma;
119
120 ScreenRotationAnimation(Context context, SurfaceSession session, TransactionPool pool,
121 Transaction t, TransitionInfo.Change change, SurfaceControl rootLeash, int animHint) {
122 mContext = context;
123 mTransactionPool = pool;
124 mAnimHint = animHint;
125
126 mSurfaceControl = change.getLeash();
127 mStartWidth = change.getStartAbsBounds().width();
128 mStartHeight = change.getStartAbsBounds().height();
129 mEndWidth = change.getEndAbsBounds().width();
130 mEndHeight = change.getEndAbsBounds().height();
131 mStartRotation = change.getStartRotation();
132 mEndRotation = change.getEndRotation();
133
134 mAnimLeash = new SurfaceControl.Builder(session)
135 .setParent(rootLeash)
136 .setEffectLayer()
137 .setCallsite("ShellRotationAnimation")
138 .setName("Animation leash of screenshot rotation")
139 .build();
140
141 try {
142 if (change.getSnapshot() != null) {
143 mScreenshotLayer = change.getSnapshot();
144 t.reparent(mScreenshotLayer, mAnimLeash);
145 mStartLuma = change.getSnapshotLuma();
146 } else {
147 SurfaceControl.LayerCaptureArgs args =
148 new SurfaceControl.LayerCaptureArgs.Builder(mSurfaceControl)
149 .setCaptureSecureLayers(true)
150 .setAllowProtected(true)
151 .setSourceCrop(new Rect(0, 0, mStartWidth, mStartHeight))
152 .build();
153 SurfaceControl.ScreenshotHardwareBuffer screenshotBuffer =
154 SurfaceControl.captureLayers(args);
155 if (screenshotBuffer == null) {
156 Slog.w(TAG, "Unable to take screenshot of display");
157 return;
158 }
159
160 mScreenshotLayer = new SurfaceControl.Builder(session)
161 .setParent(mAnimLeash)
162 .setBLASTLayer()
163 .setSecure(screenshotBuffer.containsSecureLayers())
164 .setOpaque(true)
165 .setCallsite("ShellRotationAnimation")
166 .setName("RotationLayer")
167 .build();
168
169 final ColorSpace colorSpace = screenshotBuffer.getColorSpace();
170 final HardwareBuffer hardwareBuffer = screenshotBuffer.getHardwareBuffer();
171 t.setDataSpace(mScreenshotLayer, colorSpace.getDataSpace());
172 t.setBuffer(mScreenshotLayer, hardwareBuffer);
173 t.show(mScreenshotLayer);
174 if (!isCustomRotate()) {
175 mStartLuma = getMedianBorderLuma(hardwareBuffer, colorSpace);
176 }
177 }
178
179 t.setLayer(mAnimLeash, SCREEN_FREEZE_LAYER_BASE);
180 t.show(mAnimLeash);
181 // Crop the real content in case it contains a larger child layer, e.g. wallpaper.
182 t.setCrop(mSurfaceControl, new Rect(0, 0, mEndWidth, mEndHeight));
183
184 if (!isCustomRotate()) {
185 mBackColorSurface = new SurfaceControl.Builder(session)
186 .setParent(rootLeash)
187 .setColorLayer()
188 .setOpaque(true)
189 .setCallsite("ShellRotationAnimation")
190 .setName("BackColorSurface")
191 .build();
192
193 t.setLayer(mBackColorSurface, -1);
194 t.setColor(mBackColorSurface, new float[]{mStartLuma, mStartLuma, mStartLuma});
195 t.show(mBackColorSurface);
196 }
197
198 } catch (Surface.OutOfResourcesException e) {
199 Slog.w(TAG, "Unable to allocate freeze surface", e);
200 }
201
202 setScreenshotTransform(t);
203 t.apply();
204 }
205
206 private boolean isCustomRotate() {
207 return mAnimHint == ROTATION_ANIMATION_CROSSFADE || mAnimHint == ROTATION_ANIMATION_JUMPCUT;
208 }
209
210 private void setScreenshotTransform(SurfaceControl.Transaction t) {
211 if (mScreenshotLayer == null) {
212 return;
213 }
214 final Matrix matrix = new Matrix();
215 final int delta = deltaRotation(mEndRotation, mStartRotation);
216 if (delta != 0) {
217 // Compute the transformation matrix that must be applied to the snapshot to make it
218 // stay in the same original position with the current screen rotation.
219 switch (delta) {
220 case Surface.ROTATION_90:
221 matrix.setRotate(90, 0, 0);
222 matrix.postTranslate(mStartHeight, 0);
223 break;
224 case Surface.ROTATION_180:
225 matrix.setRotate(180, 0, 0);
226 matrix.postTranslate(mStartWidth, mStartHeight);
227 break;
228 case Surface.ROTATION_270:
229 matrix.setRotate(270, 0, 0);
230 matrix.postTranslate(0, mStartWidth);
231 break;
232 }
233 } else if ((mEndWidth > mStartWidth) == (mEndHeight > mStartHeight)
234 && (mEndWidth != mStartWidth || mEndHeight != mStartHeight)) {
235 // Display resizes without rotation change.
236 final float scale = Math.max((float) mEndWidth / mStartHeight,
237 (float) mEndHeight / mStartHeight);
238 matrix.setScale(scale, scale);
239 }
240 matrix.getValues(mTmpFloats);
241 float x = mTmpFloats[Matrix.MTRANS_X];
242 float y = mTmpFloats[Matrix.MTRANS_Y];
243 t.setPosition(mScreenshotLayer, x, y);
244 t.setMatrix(mScreenshotLayer,
245 mTmpFloats[Matrix.MSCALE_X], mTmpFloats[Matrix.MSKEW_Y],
246 mTmpFloats[Matrix.MSKEW_X], mTmpFloats[Matrix.MSCALE_Y]);
247 }
248
249 /**
250 * Returns true if animating.
251 */
252 public boolean startAnimation(@NonNull ArrayList<Animator> animations,
253 @NonNull Runnable finishCallback, float animationScale,
254 @NonNull ShellExecutor mainExecutor, @NonNull ShellExecutor animExecutor) {
255 if (mScreenshotLayer == null) {
256 // Can't do animation.
257 return false;
258 }
259
260 // TODO : Found a way to get right end luma and re-enable color frame animation.
261 // End luma value is very not stable so it will cause more flicker is we run background
262 // color frame animation.
263 //mEndLuma = getLumaOfSurfaceControl(mEndBounds, mSurfaceControl);
264
265 final boolean customRotate = isCustomRotate();
266 if (customRotate) {
267 mRotateExitAnimation = AnimationUtils.loadAnimation(mContext,
268 mAnimHint == ROTATION_ANIMATION_JUMPCUT ? R.anim.rotation_animation_jump_exit
269 : R.anim.rotation_animation_xfade_exit);
270 mRotateEnterAnimation = AnimationUtils.loadAnimation(mContext,
271 R.anim.rotation_animation_enter);
272 mRotateAlphaAnimation = AnimationUtils.loadAnimation(mContext,
273 R.anim.screen_rotate_alpha);
274 } else {
275 // Figure out how the screen has moved from the original rotation.
276 int delta = deltaRotation(mEndRotation, mStartRotation);
277 switch (delta) { /* Counter-Clockwise Rotations */
278 case Surface.ROTATION_0:
279 mRotateExitAnimation = AnimationUtils.loadAnimation(mContext,
280 R.anim.screen_rotate_0_exit);
281 mRotateEnterAnimation = AnimationUtils.loadAnimation(mContext,
282 R.anim.rotation_animation_enter);
283 break;
284 case Surface.ROTATION_90:
285 mRotateExitAnimation = AnimationUtils.loadAnimation(mContext,
286 R.anim.screen_rotate_plus_90_exit);
287 mRotateEnterAnimation = AnimationUtils.loadAnimation(mContext,
288 R.anim.screen_rotate_plus_90_enter);
289 break;
290 case Surface.ROTATION_180:
291 mRotateExitAnimation = AnimationUtils.loadAnimation(mContext,
292 R.anim.screen_rotate_180_exit);
293 mRotateEnterAnimation = AnimationUtils.loadAnimation(mContext,
294 R.anim.screen_rotate_180_enter);
295 break;
296 case Surface.ROTATION_270:
297 mRotateExitAnimation = AnimationUtils.loadAnimation(mContext,
298 R.anim.screen_rotate_minus_90_exit);
299 mRotateEnterAnimation = AnimationUtils.loadAnimation(mContext,
300 R.anim.screen_rotate_minus_90_enter);
301 break;
302 }
303 }
304
305 mRotateExitAnimation.initialize(mEndWidth, mEndHeight, mStartWidth, mStartHeight);
306 mRotateExitAnimation.restrictDuration(MAX_ANIMATION_DURATION);
307 mRotateExitAnimation.scaleCurrentDuration(animationScale);
308 mRotateEnterAnimation.initialize(mEndWidth, mEndHeight, mStartWidth, mStartHeight);
309 mRotateEnterAnimation.restrictDuration(MAX_ANIMATION_DURATION);
310 mRotateEnterAnimation.scaleCurrentDuration(animationScale);
311
312 if (customRotate) {
313 mRotateAlphaAnimation.initialize(mEndWidth, mEndHeight, mStartWidth, mStartHeight);
314 mRotateAlphaAnimation.restrictDuration(MAX_ANIMATION_DURATION);
315 mRotateAlphaAnimation.scaleCurrentDuration(animationScale);
316
317 startScreenshotAlphaAnimation(animations, finishCallback, mainExecutor,
318 animExecutor);
319 startDisplayRotation(animations, finishCallback, mainExecutor, animExecutor);
320 } else {
321 startDisplayRotation(animations, finishCallback, mainExecutor, animExecutor);
322 startScreenshotRotationAnimation(animations, finishCallback, mainExecutor,
323 animExecutor);
324 //startColorAnimation(mTransaction, animationScale);
325 }
326
327 return true;
328 }
329
330 private void startDisplayRotation(@NonNull ArrayList<Animator> animations,
331 @NonNull Runnable finishCallback, @NonNull ShellExecutor mainExecutor,
332 @NonNull ShellExecutor animExecutor) {
333 startSurfaceAnimation(animations, mRotateEnterAnimation, mSurfaceControl, finishCallback,
334 mTransactionPool, mainExecutor, animExecutor, null /* position */,
335 0 /* cornerRadius */, null /* clipRect */);
336 }
337
338 private void startScreenshotRotationAnimation(@NonNull ArrayList<Animator> animations,
339 @NonNull Runnable finishCallback, @NonNull ShellExecutor mainExecutor,
340 @NonNull ShellExecutor animExecutor) {
341 startSurfaceAnimation(animations, mRotateExitAnimation, mAnimLeash, finishCallback,
342 mTransactionPool, mainExecutor, animExecutor, null /* position */,
343 0 /* cornerRadius */, null /* clipRect */);
344 }
345
346 private void startScreenshotAlphaAnimation(@NonNull ArrayList<Animator> animations,
347 @NonNull Runnable finishCallback, @NonNull ShellExecutor mainExecutor,
348 @NonNull ShellExecutor animExecutor) {
349 startSurfaceAnimation(animations, mRotateAlphaAnimation, mAnimLeash, finishCallback,
350 mTransactionPool, mainExecutor, animExecutor, null /* position */,
351 0 /* cornerRadius */, null /* clipRect */);
352 }
353
354 private void startColorAnimation(float animationScale, @NonNull ShellExecutor animExecutor) {
355 int colorTransitionMs = mContext.getResources().getInteger(
356 R.integer.config_screen_rotation_color_transition);
357 final float[] rgbTmpFloat = new float[3];
358 final int startColor = Color.rgb(mStartLuma, mStartLuma, mStartLuma);
359 final int endColor = Color.rgb(mEndLuma, mEndLuma, mEndLuma);
360 final long duration = colorTransitionMs * (long) animationScale;
361 final Transaction t = mTransactionPool.acquire();
362
363 final ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
364 // Animation length is already expected to be scaled.
365 va.overrideDurationScale(1.0f);
366 va.setDuration(duration);
367 va.addUpdateListener(animation -> {
368 final long currentPlayTime = Math.min(va.getDuration(), va.getCurrentPlayTime());
369 final float fraction = currentPlayTime / va.getDuration();
370 applyColor(startColor, endColor, rgbTmpFloat, fraction, mBackColorSurface, t);
371 });
372 va.addListener(new AnimatorListenerAdapter() {
373 @Override
374 public void onAnimationCancel(Animator animation) {
375 applyColor(startColor, endColor, rgbTmpFloat, 1f /* fraction */, mBackColorSurface,
376 t);
377 mTransactionPool.release(t);
378 }
379
380 @Override
381 public void onAnimationEnd(Animator animation) {
382 applyColor(startColor, endColor, rgbTmpFloat, 1f /* fraction */, mBackColorSurface,
383 t);
384 mTransactionPool.release(t);
385 }
386 });
387 animExecutor.execute(va::start);
388 }
389
390 public void kill() {
391 final Transaction t = mTransactionPool.acquire();
392 if (mAnimLeash.isValid()) {
393 t.remove(mAnimLeash);
394 }
395
396 if (mScreenshotLayer != null && mScreenshotLayer.isValid()) {
397 t.remove(mScreenshotLayer);
398 }
399 if (mBackColorSurface != null && mBackColorSurface.isValid()) {
400 t.remove(mBackColorSurface);
401 }
402 t.apply();
403 mTransactionPool.release(t);
404 }
405
406 /**
407 * Converts the provided {@link HardwareBuffer} and converts it to a bitmap to then sample the
408 * luminance at the borders of the bitmap
409 * @return the average luminance of all the pixels at the borders of the bitmap
410 */
411 private static float getMedianBorderLuma(HardwareBuffer hardwareBuffer, ColorSpace colorSpace) {
412 // Cannot read content from buffer with protected usage.
413 if (hardwareBuffer == null || hardwareBuffer.getFormat() != RGBA_8888
414 || hasProtectedContent(hardwareBuffer)) {
415 return 0;
416 }
417
418 ImageReader ir = ImageReader.newInstance(hardwareBuffer.getWidth(),
419 hardwareBuffer.getHeight(), hardwareBuffer.getFormat(), 1);
420 ir.getSurface().attachAndQueueBufferWithColorSpace(hardwareBuffer, colorSpace);
421 Image image = ir.acquireLatestImage();
422 if (image == null || image.getPlanes().length == 0) {
423 return 0;
424 }
425
426 Image.Plane plane = image.getPlanes()[0];
427 ByteBuffer buffer = plane.getBuffer();
428 int width = image.getWidth();
429 int height = image.getHeight();
430 int pixelStride = plane.getPixelStride();
431 int rowStride = plane.getRowStride();
432 float[] borderLumas = new float[2 * width + 2 * height];
433
434 // Grab the top and bottom borders
435 int l = 0;
436 for (int x = 0; x < width; x++) {
437 borderLumas[l++] = getPixelLuminance(buffer, x, 0, pixelStride, rowStride);
438 borderLumas[l++] = getPixelLuminance(buffer, x, height - 1, pixelStride, rowStride);
439 }
440
441 // Grab the left and right borders
442 for (int y = 0; y < height; y++) {
443 borderLumas[l++] = getPixelLuminance(buffer, 0, y, pixelStride, rowStride);
444 borderLumas[l++] = getPixelLuminance(buffer, width - 1, y, pixelStride, rowStride);
445 }
446
447 // Cleanup
448 ir.close();
449
450 // Oh, is this too simple and inefficient for you?
451 // How about implementing a O(n) solution? https://en.wikipedia.org/wiki/Median_of_medians
452 Arrays.sort(borderLumas);
453 return borderLumas[borderLumas.length / 2];
454 }
455
456 /**
457 * @return whether the hardwareBuffer passed in is marked as protected.
458 */
459 private static boolean hasProtectedContent(HardwareBuffer hardwareBuffer) {
460 return (hardwareBuffer.getUsage() & USAGE_PROTECTED_CONTENT) == USAGE_PROTECTED_CONTENT;
461 }
462
463 private static float getPixelLuminance(ByteBuffer buffer, int x, int y,
464 int pixelStride, int rowStride) {
465 int offset = y * rowStride + x * pixelStride;
466 int pixel = 0;
467 pixel |= (buffer.get(offset) & 0xff) << 16; // R
468 pixel |= (buffer.get(offset + 1) & 0xff) << 8; // G
469 pixel |= (buffer.get(offset + 2) & 0xff); // B
470 pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A
471 return Color.valueOf(pixel).luminance();
472 }
473
474 /**
475 * Gets the average border luma by taking a screenshot of the {@param surfaceControl}.
476 * @see #getMedianBorderLuma(HardwareBuffer, ColorSpace)
477 */
478 private static float getLumaOfSurfaceControl(Rect bounds, SurfaceControl surfaceControl) {
479 if (surfaceControl == null) {
480 return 0;
481 }
482
483 Rect crop = new Rect(0, 0, bounds.width(), bounds.height());
484 SurfaceControl.ScreenshotHardwareBuffer buffer =
485 SurfaceControl.captureLayers(surfaceControl, crop, 1);
486 if (buffer == null) {
487 return 0;
488 }
489
490 return getMedianBorderLuma(buffer.getHardwareBuffer(), buffer.getColorSpace());
491 }
492
493 private static void applyColor(int startColor, int endColor, float[] rgbFloat,
494 float fraction, SurfaceControl surface, SurfaceControl.Transaction t) {
495 final int color = (Integer) ArgbEvaluator.getInstance().evaluate(fraction, startColor,
496 endColor);
497 Color middleColor = Color.valueOf(color);
498 rgbFloat[0] = middleColor.red();
499 rgbFloat[1] = middleColor.green();
500 rgbFloat[2] = middleColor.blue();
501 if (surface.isValid()) {
502 t.setColor(surface, rgbFloat);
503 }
504 t.apply();
505 }
506 }