/
HardwareRenderer.java
1610 lines (1363 loc) · 55 KB
/
HardwareRenderer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view;
import android.content.ComponentCallbacks2;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.opengl.GLUtils;
import android.opengl.ManagedEGLContext;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Trace;
import android.util.Log;
import com.google.android.gles_jni.EGLImpl;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import java.io.File;
import java.io.PrintWriter;
import java.util.concurrent.locks.ReentrantLock;
import static javax.microedition.khronos.egl.EGL10.*;
/**
* Interface for rendering a ViewAncestor using hardware acceleration.
*
* @hide
*/
public abstract class HardwareRenderer {
static final String LOG_TAG = "HardwareRenderer";
/**
* Name of the file that holds the shaders cache.
*/
private static final String CACHE_PATH_SHADERS = "com.android.opengl.shaders_cache";
/**
* Turn on to only refresh the parts of the screen that need updating.
* When turned on the property defined by {@link #RENDER_DIRTY_REGIONS_PROPERTY}
* must also have the value "true".
*/
public static final boolean RENDER_DIRTY_REGIONS = true;
/**
* System property used to enable or disable dirty regions invalidation.
* This property is only queried if {@link #RENDER_DIRTY_REGIONS} is true.
* The default value of this property is assumed to be true.
*
* Possible values:
* "true", to enable partial invalidates
* "false", to disable partial invalidates
*/
static final String RENDER_DIRTY_REGIONS_PROPERTY = "debug.hwui.render_dirty_regions";
/**
* System property used to enable or disable tile rendering
*
* Possible values:
* "true", to enable tile rendering
* "false", to disable tile rendering
*/
static final String TILE_RENDERING_PROPERTY = "debug.enabletr";
/**
* System property used to enable or disable vsync.
* The default value of this property is assumed to be false.
*
* Possible values:
* "true", to disable vsync
* "false", to enable vsync
*/
static final String DISABLE_VSYNC_PROPERTY = "debug.hwui.disable_vsync";
/**
* System property used to enable or disable hardware rendering profiling.
* The default value of this property is assumed to be false.
*
* When profiling is enabled, the adb shell dumpsys gfxinfo command will
* output extra information about the time taken to execute by the last
* frames.
*
* Possible values:
* "true", to enable profiling
* "false", to disable profiling
*
* @hide
*/
public static final String PROFILE_PROPERTY = "debug.hwui.profile";
/**
* System property used to specify the number of frames to be used
* when doing hardware rendering profiling.
* The default value of this property is #PROFILE_MAX_FRAMES.
*
* When profiling is enabled, the adb shell dumpsys gfxinfo command will
* output extra information about the time taken to execute by the last
* frames.
*
* Possible values:
* "60", to set the limit of frames to 60
*/
static final String PROFILE_MAXFRAMES_PROPERTY = "debug.hwui.profile.maxframes";
/**
* System property used to debug EGL configuration choice.
*
* Possible values:
* "choice", print the chosen configuration only
* "all", print all possible configurations
*/
static final String PRINT_CONFIG_PROPERTY = "debug.hwui.print_config";
/**
* Turn on to draw dirty regions every other frame.
*
* Possible values:
* "true", to enable dirty regions debugging
* "false", to disable dirty regions debugging
*
* @hide
*/
public static final String DEBUG_DIRTY_REGIONS_PROPERTY = "debug.hwui.show_dirty_regions";
/**
* A process can set this flag to false to prevent the use of hardware
* rendering.
*
* @hide
*/
public static boolean sRendererDisabled = false;
/**
* Further hardware renderer disabling for the system process.
*
* @hide
*/
public static boolean sSystemRendererDisabled = false;
/**
* Number of frames to profile.
*/
private static final int PROFILE_MAX_FRAMES = 128;
/**
* Number of floats per profiled frame.
*/
private static final int PROFILE_FRAME_DATA_COUNT = 3;
private boolean mEnabled;
private boolean mRequested = true;
/**
* Invoke this method to disable hardware rendering in the current process.
*
* @hide
*/
public static void disable(boolean system) {
sRendererDisabled = true;
if (system) {
sSystemRendererDisabled = true;
}
}
/**
* Indicates whether hardware acceleration is available under any form for
* the view hierarchy.
*
* @return True if the view hierarchy can potentially be hardware accelerated,
* false otherwise
*/
public static boolean isAvailable() {
return GLES20Canvas.isAvailable();
}
/**
* Destroys the hardware rendering context.
*
* @param full If true, destroys all associated resources.
*/
abstract void destroy(boolean full);
/**
* Initializes the hardware renderer for the specified surface.
*
* @param holder The holder for the surface to hardware accelerate.
*
* @return True if the initialization was successful, false otherwise.
*/
abstract boolean initialize(SurfaceHolder holder) throws Surface.OutOfResourcesException;
/**
* Updates the hardware renderer for the specified surface.
*
* @param holder The holder for the surface to hardware accelerate
*/
abstract void updateSurface(SurfaceHolder holder) throws Surface.OutOfResourcesException;
/**
* Destroys the layers used by the specified view hierarchy.
*
* @param view The root of the view hierarchy
*/
abstract void destroyLayers(View view);
/**
* Destroys all hardware rendering resources associated with the specified
* view hierarchy.
*
* @param view The root of the view hierarchy
*/
abstract void destroyHardwareResources(View view);
/**
* This method should be invoked whenever the current hardware renderer
* context should be reset.
*
* @param holder The holder for the surface to hardware accelerate
*/
abstract void invalidate(SurfaceHolder holder);
/**
* This method should be invoked to ensure the hardware renderer is in
* valid state (for instance, to ensure the correct EGL context is bound
* to the current thread.)
*
* @return true if the renderer is now valid, false otherwise
*/
abstract boolean validate();
/**
* This method ensures the hardware renderer is in a valid state
* before executing the specified action.
*
* This method will attempt to set a valid state even if the window
* the renderer is attached to was destroyed.
*
* @return true if the action was run
*/
abstract boolean safelyRun(Runnable action);
/**
* Setup the hardware renderer for drawing. This is called whenever the
* size of the target surface changes or when the surface is first created.
*
* @param width Width of the drawing surface.
* @param height Height of the drawing surface.
*/
abstract void setup(int width, int height);
/**
* Gets the current width of the surface. This is the width that the surface
* was last set to in a call to {@link #setup(int, int)}.
*
* @return the current width of the surface
*/
abstract int getWidth();
/**
* Gets the current height of the surface. This is the height that the surface
* was last set to in a call to {@link #setup(int, int)}.
*
* @return the current width of the surface
*/
abstract int getHeight();
/**
* Gets the current canvas associated with this HardwareRenderer.
*
* @return the current HardwareCanvas
*/
abstract HardwareCanvas getCanvas();
/**
* Outputs extra debugging information in the specified file descriptor.
* @param pw
*/
abstract void dumpGfxInfo(PrintWriter pw);
/**
* Outputs the total number of frames rendered (used for fps calculations)
*
* @return the number of frames rendered
*/
abstract long getFrameCount();
/**
* Sets the directory to use as a persistent storage for hardware rendering
* resources.
*
* @param cacheDir A directory the current process can write to
*/
public static void setupDiskCache(File cacheDir) {
nSetupShadersDiskCache(new File(cacheDir, CACHE_PATH_SHADERS).getAbsolutePath());
}
private static native void nSetupShadersDiskCache(String cacheFile);
/**
* Notifies EGL that the frame is about to be rendered.
* @param size
*/
private static void beginFrame(int[] size) {
nBeginFrame(size);
}
private static native void nBeginFrame(int[] size);
/**
* Preserves the back buffer of the current surface after a buffer swap.
* Calling this method sets the EGL_SWAP_BEHAVIOR attribute of the current
* surface to EGL_BUFFER_PRESERVED. Calling this method requires an EGL
* config that supports EGL_SWAP_BEHAVIOR_PRESERVED_BIT.
*
* @return True if the swap behavior was successfully changed,
* false otherwise.
*/
static boolean preserveBackBuffer() {
return nPreserveBackBuffer();
}
private static native boolean nPreserveBackBuffer();
/**
* Indicates whether the current surface preserves its back buffer
* after a buffer swap.
*
* @return True, if the surface's EGL_SWAP_BEHAVIOR is EGL_BUFFER_PRESERVED,
* false otherwise
*/
static boolean isBackBufferPreserved() {
return nIsBackBufferPreserved();
}
private static native boolean nIsBackBufferPreserved();
/**
* Disables v-sync. For performance testing only.
*/
static void disableVsync() {
nDisableVsync();
}
private static native void nDisableVsync();
/**
* Interface used to receive callbacks whenever a view is drawn by
* a hardware renderer instance.
*/
interface HardwareDrawCallbacks {
/**
* Invoked before a view is drawn by a hardware renderer.
*
* @param canvas The Canvas used to render the view.
*/
void onHardwarePreDraw(HardwareCanvas canvas);
/**
* Invoked after a view is drawn by a hardware renderer.
*
* @param canvas The Canvas used to render the view.
*/
void onHardwarePostDraw(HardwareCanvas canvas);
}
/**
* Draws the specified view.
*
* @param view The view to draw.
* @param attachInfo AttachInfo tied to the specified view.
* @param callbacks Callbacks invoked when drawing happens.
* @param dirty The dirty rectangle to update, can be null.
*
* @return true if the dirty rect was ignored, false otherwise
*/
abstract boolean draw(View view, View.AttachInfo attachInfo, HardwareDrawCallbacks callbacks,
Rect dirty);
/**
* Creates a new display list that can be used to record batches of
* drawing operations.
*
* @param name The name of the display list, used for debugging purpose.
* May be null
*
* @return A new display list.
*/
public abstract DisplayList createDisplayList(String name);
/**
* Creates a new hardware layer. A hardware layer built by calling this
* method will be treated as a texture layer, instead of as a render target.
*
* @param isOpaque Whether the layer should be opaque or not
*
* @return A hardware layer
*/
abstract HardwareLayer createHardwareLayer(boolean isOpaque);
/**
* Creates a new hardware layer.
*
* @param width The minimum width of the layer
* @param height The minimum height of the layer
* @param isOpaque Whether the layer should be opaque or not
*
* @return A hardware layer
*/
abstract HardwareLayer createHardwareLayer(int width, int height, boolean isOpaque);
/**
* Creates a new {@link SurfaceTexture} that can be used to render into the
* specified hardware layer.
*
*
* @param layer The layer to render into using a {@link android.graphics.SurfaceTexture}
*
* @return A {@link SurfaceTexture}
*/
abstract SurfaceTexture createSurfaceTexture(HardwareLayer layer);
/**
* Sets the {@link android.graphics.SurfaceTexture} that will be used to
* render into the specified hardware layer.
*
* @param layer The layer to render into using a {@link android.graphics.SurfaceTexture}
* @param surfaceTexture The {@link android.graphics.SurfaceTexture} to use for the layer
*/
abstract void setSurfaceTexture(HardwareLayer layer, SurfaceTexture surfaceTexture);
/**
* Detaches the specified functor from the current functor execution queue.
*
* @param functor The native functor to remove from the execution queue.
*
* @see HardwareCanvas#callDrawGLFunction(int)
* @see #attachFunctor(android.view.View.AttachInfo, int)
*/
abstract void detachFunctor(int functor);
/**
* Schedules the specified functor in the functors execution queue.
*
* @param attachInfo AttachInfo tied to this renderer.
* @param functor The native functor to insert in the execution queue.
*
* @see HardwareCanvas#callDrawGLFunction(int)
* @see #detachFunctor(int)
*
* @return true if the functor was attached successfully
*/
abstract boolean attachFunctor(View.AttachInfo attachInfo, int functor);
/**
* Initializes the hardware renderer for the specified surface and setup the
* renderer for drawing, if needed. This is invoked when the ViewAncestor has
* potentially lost the hardware renderer. The hardware renderer should be
* reinitialized and setup when the render {@link #isRequested()} and
* {@link #isEnabled()}.
*
* @param width The width of the drawing surface.
* @param height The height of the drawing surface.
* @param holder The target surface
*/
void initializeIfNeeded(int width, int height, SurfaceHolder holder)
throws Surface.OutOfResourcesException {
if (isRequested()) {
// We lost the gl context, so recreate it.
if (!isEnabled()) {
if (initialize(holder)) {
setup(width, height);
}
}
}
}
/**
* Creates a hardware renderer using OpenGL.
*
* @param glVersion The version of OpenGL to use (1 for OpenGL 1, 11 for OpenGL 1.1, etc.)
* @param translucent True if the surface is translucent, false otherwise
*
* @return A hardware renderer backed by OpenGL.
*/
static HardwareRenderer createGlRenderer(int glVersion, boolean translucent) {
switch (glVersion) {
case 2:
return Gl20Renderer.create(translucent);
}
throw new IllegalArgumentException("Unknown GL version: " + glVersion);
}
/**
* Invoke this method when the system is running out of memory. This
* method will attempt to recover as much memory as possible, based on
* the specified hint.
*
* @param level Hint about the amount of memory that should be trimmed,
* see {@link android.content.ComponentCallbacks}
*/
static void trimMemory(int level) {
startTrimMemory(level);
endTrimMemory();
}
/**
* Starts the process of trimming memory. Usually this call will setup
* hardware rendering context and reclaim memory.Extra cleanup might
* be required by calling {@link #endTrimMemory()}.
*
* @param level Hint about the amount of memory that should be trimmed,
* see {@link android.content.ComponentCallbacks}
*/
static void startTrimMemory(int level) {
Gl20Renderer.startTrimMemory(level);
}
/**
* Finishes the process of trimming memory. This method will usually
* cleanup special resources used by the memory trimming process.
*/
static void endTrimMemory() {
Gl20Renderer.endTrimMemory();
}
/**
* Indicates whether hardware acceleration is currently enabled.
*
* @return True if hardware acceleration is in use, false otherwise.
*/
boolean isEnabled() {
return mEnabled;
}
/**
* Indicates whether hardware acceleration is currently enabled.
*
* @param enabled True if the hardware renderer is in use, false otherwise.
*/
void setEnabled(boolean enabled) {
mEnabled = enabled;
}
/**
* Indicates whether hardware acceleration is currently request but not
* necessarily enabled yet.
*
* @return True if requested, false otherwise.
*/
boolean isRequested() {
return mRequested;
}
/**
* Indicates whether hardware acceleration is currently requested but not
* necessarily enabled yet.
*
* @return True to request hardware acceleration, false otherwise.
*/
void setRequested(boolean requested) {
mRequested = requested;
}
@SuppressWarnings({"deprecation"})
static abstract class GlRenderer extends HardwareRenderer {
// These values are not exposed in our EGL APIs
static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
static final int EGL_OPENGL_ES2_BIT = 4;
static final int EGL_SURFACE_TYPE = 0x3033;
static final int EGL_SWAP_BEHAVIOR_PRESERVED_BIT = 0x0400;
static final int SURFACE_STATE_ERROR = 0;
static final int SURFACE_STATE_SUCCESS = 1;
static final int SURFACE_STATE_UPDATED = 2;
static final int FUNCTOR_PROCESS_DELAY = 4;
static EGL10 sEgl;
static EGLDisplay sEglDisplay;
static EGLConfig sEglConfig;
static final Object[] sEglLock = new Object[0];
int mWidth = -1, mHeight = -1;
static final ThreadLocal<ManagedEGLContext> sEglContextStorage
= new ThreadLocal<ManagedEGLContext>();
EGLContext mEglContext;
Thread mEglThread;
EGLSurface mEglSurface;
GL mGl;
HardwareCanvas mCanvas;
long mFrameCount;
Paint mDebugPaint;
static boolean sDirtyRegions;
static final boolean sDirtyRegionsRequested;
static boolean sTileRendering;
static {
String dirtyProperty = SystemProperties.get(RENDER_DIRTY_REGIONS_PROPERTY, "true");
String trProperty = SystemProperties.get(TILE_RENDERING_PROPERTY, "false");
//noinspection PointlessBooleanExpression,ConstantConditions
//enable dirty regions if tile-rendering enabled or dirty regions property enabled
sTileRendering = "true".equalsIgnoreCase(trProperty);
sDirtyRegions = RENDER_DIRTY_REGIONS &&
("true".equalsIgnoreCase(dirtyProperty) ||
sTileRendering);
sDirtyRegionsRequested = sDirtyRegions;
}
boolean mDirtyRegionsEnabled;
boolean mUpdateDirtyRegions;
final boolean mVsyncDisabled;
final boolean mProfileEnabled;
final float[] mProfileData;
final ReentrantLock mProfileLock;
int mProfileCurrentFrame = -PROFILE_FRAME_DATA_COUNT;
final boolean mDebugDirtyRegions;
final int mGlVersion;
final boolean mTranslucent;
private boolean mDestroyed;
private final Rect mRedrawClip = new Rect();
private final int[] mSurfaceSize = new int[2];
private final FunctorsRunnable mFunctorsRunnable = new FunctorsRunnable();
GlRenderer(int glVersion, boolean translucent) {
mGlVersion = glVersion;
mTranslucent = translucent;
String property;
property = SystemProperties.get(DISABLE_VSYNC_PROPERTY, "false");
mVsyncDisabled = "true".equalsIgnoreCase(property);
if (mVsyncDisabled) {
Log.d(LOG_TAG, "Disabling v-sync");
}
property = SystemProperties.get(PROFILE_PROPERTY, "false");
mProfileEnabled = "true".equalsIgnoreCase(property);
if (mProfileEnabled) {
Log.d(LOG_TAG, "Profiling hardware renderer");
}
if (mProfileEnabled) {
property = SystemProperties.get(PROFILE_MAXFRAMES_PROPERTY,
Integer.toString(PROFILE_MAX_FRAMES));
int maxProfileFrames = Integer.valueOf(property);
mProfileData = new float[maxProfileFrames * PROFILE_FRAME_DATA_COUNT];
for (int i = 0; i < mProfileData.length; i += PROFILE_FRAME_DATA_COUNT) {
mProfileData[i] = mProfileData[i + 1] = mProfileData[i + 2] = -1;
}
mProfileLock = new ReentrantLock();
} else {
mProfileData = null;
mProfileLock = null;
}
property = SystemProperties.get(DEBUG_DIRTY_REGIONS_PROPERTY, "false");
mDebugDirtyRegions = "true".equalsIgnoreCase(property);
if (mDebugDirtyRegions) {
Log.d(LOG_TAG, "Debugging dirty regions");
}
}
@Override
void dumpGfxInfo(PrintWriter pw) {
if (mProfileEnabled) {
pw.printf("\n\tDraw\tProcess\tExecute\n");
mProfileLock.lock();
try {
for (int i = 0; i < mProfileData.length; i += PROFILE_FRAME_DATA_COUNT) {
if (mProfileData[i] < 0) {
break;
}
pw.printf("\t%3.2f\t%3.2f\t%3.2f\n", mProfileData[i], mProfileData[i + 1],
mProfileData[i + 2]);
mProfileData[i] = mProfileData[i + 1] = mProfileData[i + 2] = -1;
}
mProfileCurrentFrame = mProfileData.length;
} finally {
mProfileLock.unlock();
}
}
}
@Override
long getFrameCount() {
return mFrameCount;
}
/**
* Indicates whether this renderer instance can track and update dirty regions.
*/
boolean hasDirtyRegions() {
return mDirtyRegionsEnabled;
}
/**
* Checks for OpenGL errors. If an error has occured, {@link #destroy(boolean)}
* is invoked and the requested flag is turned off. The error code is
* also logged as a warning.
*/
void checkEglErrors() {
if (isEnabled()) {
int error = sEgl.eglGetError();
if (error != EGL_SUCCESS) {
// something bad has happened revert to
// normal rendering.
Log.w(LOG_TAG, "EGL error: " + GLUtils.getEGLErrorString(error));
fallback(error != EGL11.EGL_CONTEXT_LOST);
}
}
}
private void fallback(boolean fallback) {
destroy(true);
if (fallback) {
// we'll try again if it was context lost
setRequested(false);
Log.w(LOG_TAG, "Mountain View, we've had a problem here. "
+ "Switching back to software rendering.");
}
}
@Override
boolean initialize(SurfaceHolder holder) throws Surface.OutOfResourcesException {
if (isRequested() && !isEnabled()) {
initializeEgl();
mGl = createEglSurface(holder);
mDestroyed = false;
if (mGl != null) {
int err = sEgl.eglGetError();
if (err != EGL_SUCCESS) {
destroy(true);
setRequested(false);
} else {
if (mCanvas == null) {
mCanvas = createCanvas();
}
if (mCanvas != null) {
setEnabled(true);
} else {
Log.w(LOG_TAG, "Hardware accelerated Canvas could not be created");
}
}
return mCanvas != null;
}
}
return false;
}
@Override
void updateSurface(SurfaceHolder holder) throws Surface.OutOfResourcesException {
if (isRequested() && isEnabled()) {
createEglSurface(holder);
}
}
abstract HardwareCanvas createCanvas();
abstract int[] getConfig(boolean dirtyRegions);
void initializeEgl() {
synchronized (sEglLock) {
if (sEgl == null && sEglConfig == null) {
sEgl = (EGL10) EGLContext.getEGL();
// Get to the default display.
sEglDisplay = sEgl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (sEglDisplay == EGL_NO_DISPLAY) {
throw new RuntimeException("eglGetDisplay failed "
+ GLUtils.getEGLErrorString(sEgl.eglGetError()));
}
// We can now initialize EGL for that display
int[] version = new int[2];
if (!sEgl.eglInitialize(sEglDisplay, version)) {
throw new RuntimeException("eglInitialize failed " +
GLUtils.getEGLErrorString(sEgl.eglGetError()));
}
sEglConfig = chooseEglConfig();
if (sEglConfig == null) {
// We tried to use EGL_SWAP_BEHAVIOR_PRESERVED_BIT, try again without
if (sDirtyRegions) {
sDirtyRegions = false;
sEglConfig = chooseEglConfig();
if (sEglConfig == null) {
throw new RuntimeException("eglConfig not initialized");
}
} else {
throw new RuntimeException("eglConfig not initialized");
}
}
}
}
ManagedEGLContext managedContext = sEglContextStorage.get();
mEglContext = managedContext != null ? managedContext.getContext() : null;
mEglThread = Thread.currentThread();
if (mEglContext == null) {
mEglContext = createContext(sEgl, sEglDisplay, sEglConfig);
sEglContextStorage.set(createManagedContext(mEglContext));
}
}
abstract ManagedEGLContext createManagedContext(EGLContext eglContext);
private EGLConfig chooseEglConfig() {
EGLConfig[] configs = new EGLConfig[1];
int[] configsCount = new int[1];
int[] configSpec = getConfig(sDirtyRegions);
// Debug
final String debug = SystemProperties.get(PRINT_CONFIG_PROPERTY, "");
if ("all".equalsIgnoreCase(debug)) {
sEgl.eglChooseConfig(sEglDisplay, configSpec, null, 0, configsCount);
EGLConfig[] debugConfigs = new EGLConfig[configsCount[0]];
sEgl.eglChooseConfig(sEglDisplay, configSpec, debugConfigs,
configsCount[0], configsCount);
for (EGLConfig config : debugConfigs) {
printConfig(config);
}
}
if (!sEgl.eglChooseConfig(sEglDisplay, configSpec, configs, 1, configsCount)) {
throw new IllegalArgumentException("eglChooseConfig failed " +
GLUtils.getEGLErrorString(sEgl.eglGetError()));
} else if (configsCount[0] > 0) {
if ("choice".equalsIgnoreCase(debug)) {
printConfig(configs[0]);
}
return configs[0];
}
return null;
}
private static void printConfig(EGLConfig config) {
int[] value = new int[1];
Log.d(LOG_TAG, "EGL configuration " + config + ":");
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_RED_SIZE, value);
Log.d(LOG_TAG, " RED_SIZE = " + value[0]);
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_GREEN_SIZE, value);
Log.d(LOG_TAG, " GREEN_SIZE = " + value[0]);
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_BLUE_SIZE, value);
Log.d(LOG_TAG, " BLUE_SIZE = " + value[0]);
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_ALPHA_SIZE, value);
Log.d(LOG_TAG, " ALPHA_SIZE = " + value[0]);
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_DEPTH_SIZE, value);
Log.d(LOG_TAG, " DEPTH_SIZE = " + value[0]);
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_STENCIL_SIZE, value);
Log.d(LOG_TAG, " STENCIL_SIZE = " + value[0]);
sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_SURFACE_TYPE, value);
Log.d(LOG_TAG, " SURFACE_TYPE = 0x" + Integer.toHexString(value[0]));
}
GL createEglSurface(SurfaceHolder holder) throws Surface.OutOfResourcesException {
// Check preconditions.
if (sEgl == null) {
throw new RuntimeException("egl not initialized");
}
if (sEglDisplay == null) {
throw new RuntimeException("eglDisplay not initialized");
}
if (sEglConfig == null) {
throw new RuntimeException("eglConfig not initialized");
}
if (Thread.currentThread() != mEglThread) {
throw new IllegalStateException("HardwareRenderer cannot be used "
+ "from multiple threads");
}
// In case we need to destroy an existing surface
destroySurface();
// Create an EGL surface we can render into.
if (!createSurface(holder)) {
return null;
}
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
if (!sEgl.eglMakeCurrent(sEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
throw new Surface.OutOfResourcesException("eglMakeCurrent failed "
+ GLUtils.getEGLErrorString(sEgl.eglGetError()));
}
initCaches();
enableDirtyRegions();
return mEglContext.getGL();
}
private void enableDirtyRegions() {
// If mDirtyRegions is set, this means we have an EGL configuration
// with EGL_SWAP_BEHAVIOR_PRESERVED_BIT set
if (sDirtyRegions) {
if (!(mDirtyRegionsEnabled = preserveBackBuffer())) {
Log.w(LOG_TAG, "Backbuffer cannot be preserved");
}
} else if (sDirtyRegionsRequested) {
// If mDirtyRegions is not set, our EGL configuration does not
// have EGL_SWAP_BEHAVIOR_PRESERVED_BIT; however, the default
// swap behavior might be EGL_BUFFER_PRESERVED, which means we
// want to set mDirtyRegions. We try to do this only if dirty
// regions were initially requested as part of the device
// configuration (see RENDER_DIRTY_REGIONS)
mDirtyRegionsEnabled = isBackBufferPreserved();
}
}
abstract void initCaches();
EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) {
int[] attribs = { EGL_CONTEXT_CLIENT_VERSION, mGlVersion, EGL_NONE };
return egl.eglCreateContext(eglDisplay, eglConfig, EGL_NO_CONTEXT,
mGlVersion != 0 ? attribs : null);
}
@Override
void destroy(boolean full) {
if (full && mCanvas != null) {
mCanvas = null;
}
if (!isEnabled() || mDestroyed) {
setEnabled(false);
return;
}
destroySurface();
setEnabled(false);
mDestroyed = true;
mGl = null;
}
void destroySurface() {
if (mEglSurface != null && mEglSurface != EGL_NO_SURFACE) {
sEgl.eglMakeCurrent(sEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
sEgl.eglDestroySurface(sEglDisplay, mEglSurface);
mEglSurface = null;
}
}
@Override
void invalidate(SurfaceHolder holder) {