summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xapct-tests/perftests/textclassifier/run.sh2
-rw-r--r--api/current.txt2
-rw-r--r--api/system-current.txt1
-rw-r--r--api/test-current.txt1
-rw-r--r--core/java/android/app/Activity.java10
-rw-r--r--core/java/android/net/MacAddress.java25
-rw-r--r--core/java/android/os/SystemProperties.java7
-rw-r--r--core/java/android/os/ZygoteProcess.java2
-rw-r--r--core/java/android/provider/Settings.java8
-rw-r--r--core/java/android/view/SurfaceView.java3
-rw-r--r--core/java/android/view/accessibility/AccessibilityNodeProvider.java130
-rw-r--r--core/java/com/android/internal/os/Zygote.java3
-rw-r--r--core/java/com/android/internal/os/ZygoteArguments.java2
-rw-r--r--core/jni/AndroidRuntime.cpp6
-rw-r--r--core/jni/com_android_internal_os_Zygote.cpp10
-rw-r--r--core/proto/android/server/protolog.proto2
-rw-r--r--core/res/AndroidManifest.xml13
-rw-r--r--core/res/res/values/strings.xml5
-rw-r--r--data/etc/services.core.protolog.json5
-rw-r--r--media/Android.bp20
-rw-r--r--media/apex/java/android/media/DataSourceDesc.java384
-rw-r--r--media/apex/java/android/media/FileDataSourceDesc.java134
-rw-r--r--media/apex/java/android/media/Media2HTTPConnection.java385
-rw-r--r--media/apex/java/android/media/Media2HTTPService.java58
-rw-r--r--media/apex/java/android/media/Media2Utils.java78
-rw-r--r--media/apex/java/android/media/MediaPlayer2.java5507
-rw-r--r--media/apex/java/android/media/MediaPlayer2Utils.java43
-rw-r--r--media/apex/java/android/media/UriDataSourceDesc.java80
-rw-r--r--media/jni/Android.bp82
-rw-r--r--media/jni/android_media_DataSourceCallback.cpp159
-rw-r--r--media/jni/android_media_DataSourceCallback.h70
-rw-r--r--media/jni/android_media_MediaMetricsJNI.cpp3
-rw-r--r--media/jni/android_media_MediaPlayer2.cpp1477
-rw-r--r--media/proto/Android.bp20
-rw-r--r--media/proto/jarjar-rules.txt2
-rw-r--r--media/proto/mediaplayer2.proto53
-rw-r--r--packages/BackupEncryption/Android.bp1
-rw-r--r--packages/BackupEncryption/AndroidManifest.xml11
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java63
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java232
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java67
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java243
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java179
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java68
-rw-r--r--packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java98
-rw-r--r--packages/BackupEncryption/test/robolectric/Android.bp2
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java614
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java397
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java287
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java256
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java72
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java100
-rw-r--r--packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java106
-rw-r--r--packages/BackupEncryption/test/unittest/Android.bp22
-rw-r--r--packages/BackupEncryption/test/unittest/AndroidManifest.xml27
-rw-r--r--packages/BackupEncryption/test/unittest/AndroidTest.xml29
-rw-r--r--packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java120
-rw-r--r--packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java77
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java3
-rw-r--r--packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java13
-rw-r--r--packages/SystemUI/res/layout/navigation_bar.xml15
-rw-r--r--packages/SystemUI/res/layout/rounded_corners.xml12
-rw-r--r--packages/SystemUI/src/com/android/systemui/ScreenDecorations.java263
-rw-r--r--packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java33
-rw-r--r--packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java172
-rw-r--r--packages/SystemUI/src/com/android/systemui/assist/AssistModule.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java12
-rw-r--r--packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java89
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java10
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java27
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java53
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java83
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java104
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java33
-rw-r--r--services/backup/backuplib/java/com/android/server/backup/TransportManager.java3
-rw-r--r--services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java76
-rw-r--r--services/core/java/com/android/server/StorageManagerService.java20
-rw-r--r--services/core/java/com/android/server/TelephonyRegistry.java36
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerService.java2
-rw-r--r--services/core/java/com/android/server/display/DisplayModeDirector.java5
-rw-r--r--services/core/java/com/android/server/display/utils/AmbientFilter.java (renamed from services/core/java/com/android/server/display/whitebalance/AmbientFilter.java)5
-rw-r--r--services/core/java/com/android/server/display/utils/AmbientFilterFactory.java105
-rw-r--r--services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java1
-rw-r--r--services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java40
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerService.java8
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerShellCommand.java79
-rw-r--r--services/core/java/com/android/server/protolog/ProtoLogImpl.java86
-rw-r--r--services/core/java/com/android/server/stats/ProcfsMemoryUtil.java90
-rw-r--r--services/core/java/com/android/server/stats/StatsCompanionService.java78
-rw-r--r--services/core/java/com/android/server/wm/DisplayContent.java129
-rw-r--r--services/core/java/com/android/server/wm/WindowContainer.java16
-rw-r--r--services/net/Android.bp79
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl9
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl8
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl6
-rw-r--r--services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl9
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl8
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl6
-rw-r--r--services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl4
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl27
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl21
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl25
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl23
-rw-r--r--services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl21
-rw-r--r--services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl8
-rw-r--r--services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl17
-rw-r--r--services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl8
-rw-r--r--services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl7
-rw-r--r--services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl4
-rw-r--r--services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl7
-rw-r--r--services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl5
-rw-r--r--services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl15
-rw-r--r--services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl13
-rw-r--r--services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl11
-rw-r--r--services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl10
-rw-r--r--services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl4
-rw-r--r--services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl14
-rw-r--r--services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl16
-rw-r--r--services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl9
-rw-r--r--services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl24
-rw-r--r--services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl8
-rw-r--r--services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl7
-rw-r--r--services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl4
-rw-r--r--services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl7
-rw-r--r--services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl7
-rw-r--r--services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl5
-rw-r--r--services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl15
-rw-r--r--services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl13
-rw-r--r--services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl11
-rw-r--r--services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl10
-rw-r--r--services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl4
-rw-r--r--services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl15
-rw-r--r--services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl16
-rw-r--r--services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl26
-rw-r--r--services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl41
-rw-r--r--services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl25
-rw-r--r--services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl24
-rw-r--r--services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl21
-rw-r--r--services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl24
-rw-r--r--services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl24
-rw-r--r--services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl22
-rw-r--r--services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl32
-rw-r--r--services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl30
-rw-r--r--services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl28
-rw-r--r--services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl27
-rw-r--r--services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl21
-rw-r--r--services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl33
-rw-r--r--services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl33
-rw-r--r--services/net/java/android/net/DhcpResultsParcelable.aidl28
-rw-r--r--services/net/java/android/net/IIpMemoryStore.aidl118
-rw-r--r--services/net/java/android/net/INetworkMonitor.aidl68
-rw-r--r--services/net/java/android/net/INetworkMonitorCallbacks.aidl29
-rw-r--r--services/net/java/android/net/INetworkStackConnector.aidl32
-rw-r--r--services/net/java/android/net/INetworkStackStatusCallback.aidl22
-rw-r--r--services/net/java/android/net/InitialConfigurationParcelable.aidl27
-rw-r--r--services/net/java/android/net/IpMemoryStoreClient.java227
-rw-r--r--services/net/java/android/net/PrivateDnsConfigParcel.aidl22
-rw-r--r--services/net/java/android/net/ProvisioningConfigurationParcelable.aidl38
-rw-r--r--services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl30
-rw-r--r--services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl30
-rw-r--r--services/net/java/android/net/dhcp/IDhcpServer.aidl32
-rw-r--r--services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl24
-rw-r--r--services/net/java/android/net/ip/IIpClient.aidl38
-rw-r--r--services/net/java/android/net/ip/IIpClientCallbacks.aidl66
-rw-r--r--services/net/java/android/net/ipmemorystore/Blob.aidl26
-rw-r--r--services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl30
-rw-r--r--services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl27
-rw-r--r--services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl30
-rw-r--r--services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl29
-rw-r--r--services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl27
-rw-r--r--services/net/java/android/net/ipmemorystore/NetworkAttributes.java371
-rw-r--r--services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl37
-rw-r--r--services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java50
-rw-r--r--services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java50
-rw-r--r--services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java54
-rw-r--r--services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java53
-rw-r--r--services/net/java/android/net/ipmemorystore/OnStatusListener.java49
-rw-r--r--services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java147
-rw-r--r--services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl24
-rw-r--r--services/net/java/android/net/ipmemorystore/Status.java74
-rw-r--r--services/net/java/android/net/ipmemorystore/StatusParcelable.aidl22
-rw-r--r--services/tests/servicestests/src/com/android/server/display/utils/AmbientFilterTest.java (renamed from services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterTest.java)7
-rw-r--r--services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterStubber.java (renamed from services/net/java/android/net/IIpMemoryStoreCallbacks.aidl)13
-rw-r--r--services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java24
-rw-r--r--services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java4
-rw-r--r--services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java29
-rw-r--r--services/wifi/Android.bp3
-rw-r--r--services/wifi/java/android/net/wifi/IWifiStackConnector.aidl5
-rw-r--r--services/wifi/java/android/net/wifi/WifiStackClient.java57
-rw-r--r--startop/view_compiler/dex_builder.cc21
-rw-r--r--startop/view_compiler/dex_builder.h54
-rw-r--r--startop/view_compiler/dex_layout_compiler.cc211
-rw-r--r--startop/view_compiler/dex_layout_compiler.h31
-rw-r--r--startop/view_compiler/dex_testcase_generator.cc36
-rw-r--r--telephony/java/android/telephony/SubscriptionManager.java6
-rw-r--r--telephony/java/android/telephony/TelephonyManager.java40
-rw-r--r--tests/ApkVerityTest/Android.bp34
-rw-r--r--tests/ApkVerityTest/AndroidTest.xml41
-rw-r--r--tests/ApkVerityTest/ApkVerityTestApp/Android.bp (renamed from tests/FlickerTests/lib/test/Android.bp)34
-rw-r--r--tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml23
-rw-r--r--tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml25
-rw-r--r--tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java (renamed from services/wifi/java/android/net/wifi/WifiApiServiceInfo.aidl)11
-rw-r--r--tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java (renamed from services/net/java/android/net/NattKeepalivePacketDataParcelable.aidl)11
-rw-r--r--tests/ApkVerityTest/block_device_writer/Android.bp30
-rw-r--r--tests/ApkVerityTest/block_device_writer/block_device_writer.cpp189
-rw-r--r--tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java496
-rw-r--r--tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java140
-rw-r--r--tests/ApkVerityTest/testdata/Android.bp77
-rw-r--r--tests/ApkVerityTest/testdata/ApkVerityTestApp.dmbin0 -> 237348 bytes
-rw-r--r--tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dmbin0 -> 237025 bytes
-rw-r--r--tests/ApkVerityTest/testdata/ApkVerityTestCert.derbin0 -> 1330 bytes
-rw-r--r--tests/ApkVerityTest/testdata/ApkVerityTestCert.pem30
-rw-r--r--tests/ApkVerityTest/testdata/ApkVerityTestKey.pem52
-rw-r--r--tests/ApkVerityTest/testdata/README.md13
-rw-r--r--tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java14
-rw-r--r--tests/FlickerTests/AndroidManifest.xml4
-rw-r--r--tests/FlickerTests/AndroidTest.xml1
-rw-r--r--tests/FlickerTests/lib/Android.bp57
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java134
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java183
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java27
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java420
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java140
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java433
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java240
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java144
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java192
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java263
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java63
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java64
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java80
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java74
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java100
-rw-r--r--tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java59
-rw-r--r--tests/FlickerTests/lib/test/AndroidManifest.xml26
-rw-r--r--tests/FlickerTests/lib/test/AndroidTest.xml20
-rw-r--r--tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pbbin565800 -> 0 bytes
-rw-r--r--tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pbbin3580523 -> 0 bytes
-rw-r--r--tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pbbin1936878 -> 0 bytes
-rw-r--r--tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pbbin355010 -> 0 bytes
-rw-r--r--tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pbbin194353 -> 0 bytes
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java181
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java60
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java88
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java230
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java36
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java258
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java108
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java49
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java78
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java70
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java50
-rw-r--r--tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java79
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java43
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java5
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java5
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java14
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java5
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java39
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java23
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java7
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java23
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java5
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java11
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java5
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java15
-rw-r--r--tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java59
-rw-r--r--tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java5
-rw-r--r--tests/net/java/com/android/server/ConnectivityServiceTest.java14
-rw-r--r--tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt13
-rw-r--r--tools/protologtool/src/com/android/protolog/tool/Constants.kt2
-rw-r--r--tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt14
-rw-r--r--tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt24
-rw-r--r--tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt29
-rw-r--r--tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt21
-rw-r--r--tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt59
-rw-r--r--tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt45
-rw-r--r--tools/validatekeymaps/Main.cpp1
301 files changed, 6035 insertions, 16875 deletions
diff --git a/apct-tests/perftests/textclassifier/run.sh b/apct-tests/perftests/textclassifier/run.sh
index 8660d26388ac..d36d190a573a 100755
--- a/apct-tests/perftests/textclassifier/run.sh
+++ b/apct-tests/perftests/textclassifier/run.sh
@@ -1,5 +1,5 @@
set -e
-make TextClassifierPerfTests perf-setup.sh
+build/soong/soong_ui.bash --make-mode TextClassifierPerfTests perf-setup.sh
adb install ${OUT}/testcases/TextClassifierPerfTests/arm64/TextClassifierPerfTests.apk
adb shell cmd package compile -m speed -f com.android.perftests.textclassifier
adb push ${OUT}/obj/EXECUTABLES/perf-setup.sh_intermediates/perf-setup.sh /data/local/tmp/
diff --git a/api/current.txt b/api/current.txt
index d688220fd17b..140b6e030433 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -8,6 +8,7 @@ package android {
public static final class Manifest.permission {
ctor public Manifest.permission();
field public static final String ACCEPT_HANDOVER = "android.permission.ACCEPT_HANDOVER";
+ field public static final String ACCESSIBILITY_SHORTCUT_TARGET = "android.permission.ACCESSIBILITY_SHORTCUT_TARGET";
field public static final String ACCESS_BACKGROUND_LOCATION = "android.permission.ACCESS_BACKGROUND_LOCATION";
field public static final String ACCESS_CHECKIN_PROPERTIES = "android.permission.ACCESS_CHECKIN_PROPERTIES";
field public static final String ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION";
@@ -45013,6 +45014,7 @@ package android.telephony {
field public static final int DATA_ROAMING_DISABLE = 0; // 0x0
field public static final int DATA_ROAMING_ENABLE = 1; // 0x1
field public static final int DEFAULT_SUBSCRIPTION_ID = 2147483647; // 0x7fffffff
+ field public static final String EXTRA_SLOT_INDEX = "android.telephony.extra.SLOT_INDEX";
field public static final String EXTRA_SUBSCRIPTION_INDEX = "android.telephony.extra.SUBSCRIPTION_INDEX";
field public static final int INVALID_SIM_SLOT_INDEX = -1; // 0xffffffff
field public static final int INVALID_SUBSCRIPTION_ID = -1; // 0xffffffff
diff --git a/api/system-current.txt b/api/system-current.txt
index 325167a10ea2..ced3b3c5ba6d 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -8234,6 +8234,7 @@ package android.telephony {
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getIsimIst();
method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.Map<java.lang.Integer,java.lang.Integer> getLogicalToPhysicalSlotMapping();
method public static long getMaxNumberVerificationTimeoutMillis();
+ method @NonNull public String getNetworkCountryIso(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public long getPreferredNetworkTypeBitmask();
method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public int getRadioPowerState();
method public int getSimApplicationState();
diff --git a/api/test-current.txt b/api/test-current.txt
index 0e93738b28f4..61bdc96d6e29 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -2912,6 +2912,7 @@ package android.telephony {
method public int checkCarrierPrivilegesForPackage(String);
method public int getCarrierIdListVersion();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getLine1AlphaTag();
+ method @NonNull public String getNetworkCountryIso(int);
method public android.util.Pair<java.lang.Integer,java.lang.Integer> getRadioHalVersion();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void refreshUiccProfile();
method @Deprecated public void setCarrierTestOverride(String, String, String, String, String, String, String);
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index bf7d6324764f..2847f77de73d 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -1925,11 +1925,15 @@ public class Activity extends ContextThemeWrapper
}
/**
- * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
- * of a voice interaction. That is, returns true if this activity was directly
+ * Like {@link #isVoiceInteraction}, but only returns {@code true} if this is also the root
+ * of a voice interaction. That is, returns {@code true} if this activity was directly
* started by the voice interaction service as the initiation of a voice interaction.
* Otherwise, for example if it was started by another activity while under voice
- * interaction, returns false.
+ * interaction, returns {@code false}.
+ * If the activity {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode} is
+ * {@code singleTask}, it forces the activity to launch in a new task, separate from the one
+ * that started it. Therefore, there is no longer a relationship between them, and
+ * {@link #isVoiceInteractionRoot()} return {@code false} in this case.
*/
public boolean isVoiceInteractionRoot() {
try {
diff --git a/core/java/android/net/MacAddress.java b/core/java/android/net/MacAddress.java
index a809b28c9204..2cf2a6514e77 100644
--- a/core/java/android/net/MacAddress.java
+++ b/core/java/android/net/MacAddress.java
@@ -85,6 +85,9 @@ public final class MacAddress implements Parcelable {
private static final long OUI_MASK = MacAddress.fromString("ff:ff:ff:0:0:0").mAddr;
private static final long NIC_MASK = MacAddress.fromString("0:0:0:ff:ff:ff").mAddr;
private static final MacAddress BASE_GOOGLE_MAC = MacAddress.fromString("da:a1:19:0:0:0");
+ /** Default wifi MAC address used for a special purpose **/
+ private static final MacAddress DEFAULT_MAC_ADDRESS =
+ MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
// Internal representation of the MAC address as a single 8 byte long.
// The encoding scheme sets the two most significant bytes to 0. The 6 bytes of the
@@ -361,16 +364,7 @@ public final class MacAddress implements Parcelable {
* @hide
*/
public static @NonNull MacAddress createRandomUnicastAddress() {
- SecureRandom r = new SecureRandom();
- long addr = r.nextLong() & VALID_LONG_MASK;
- addr |= LOCALLY_ASSIGNED_MASK;
- addr &= ~MULTICAST_MASK;
- MacAddress mac = new MacAddress(addr);
- // WifiInfo.DEFAULT_MAC_ADDRESS is being used for another purpose, so do not use it here.
- if (mac.toString().equals(WifiInfo.DEFAULT_MAC_ADDRESS)) {
- return createRandomUnicastAddress();
- }
- return mac;
+ return createRandomUnicastAddress(null, new SecureRandom());
}
/**
@@ -380,18 +374,23 @@ public final class MacAddress implements Parcelable {
* The locally assigned bit is always set to 1. The multicast bit is always set to 0.
*
* @param base a base MacAddress whose OUI is used for generating the random address.
+ * If base == null then the OUI will also be randomized.
* @param r a standard Java Random object used for generating the random address.
* @return a random locally assigned MacAddress.
*
* @hide
*/
public static @NonNull MacAddress createRandomUnicastAddress(MacAddress base, Random r) {
- long addr = (base.mAddr & OUI_MASK) | (NIC_MASK & r.nextLong());
+ long addr;
+ if (base == null) {
+ addr = r.nextLong() & VALID_LONG_MASK;
+ } else {
+ addr = (base.mAddr & OUI_MASK) | (NIC_MASK & r.nextLong());
+ }
addr |= LOCALLY_ASSIGNED_MASK;
addr &= ~MULTICAST_MASK;
MacAddress mac = new MacAddress(addr);
- // WifiInfo.DEFAULT_MAC_ADDRESS is being used for another purpose, so do not use it here.
- if (mac.toString().equals(WifiInfo.DEFAULT_MAC_ADDRESS)) {
+ if (mac.equals(DEFAULT_MAC_ADDRESS)) {
return createRandomUnicastAddress(base, r);
}
return mac;
diff --git a/core/java/android/os/SystemProperties.java b/core/java/android/os/SystemProperties.java
index b6af82948da3..d4abf28d2e63 100644
--- a/core/java/android/os/SystemProperties.java
+++ b/core/java/android/os/SystemProperties.java
@@ -39,6 +39,13 @@ import java.util.HashMap;
* Gives access to the system properties store. The system properties
* store contains a list of string key-value pairs.
*
+ * <p>Use this class only for the system properties that are local. e.g., within
+ * an app, a partition, or a module. For system properties used across the
+ * boundaries, formally define them in <code>*.sysprop</code> files and use the
+ * auto-generated methods. For more information, see <a href=
+ * "https://source.android.com/devices/architecture/sysprops-apis">Implementing
+ * System Properties as APIs</a>.</p>
+ *
* {@hide}
*/
@SystemApi
diff --git a/core/java/android/os/ZygoteProcess.java b/core/java/android/os/ZygoteProcess.java
index eaf9929c56d0..9a3a7cea42dd 100644
--- a/core/java/android/os/ZygoteProcess.java
+++ b/core/java/android/os/ZygoteProcess.java
@@ -576,6 +576,8 @@ public class ZygoteProcess {
argsForZygote.add("--mount-external-installer");
} else if (mountExternal == Zygote.MOUNT_EXTERNAL_LEGACY) {
argsForZygote.add("--mount-external-legacy");
+ } else if (mountExternal == Zygote.MOUNT_EXTERNAL_PASS_THROUGH) {
+ argsForZygote.add("--mount-external-pass-through");
}
argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 8b20f0bec7be..61d8eb13bcf2 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -7881,14 +7881,6 @@ public final class Settings {
public static final String DEVICE_PAIRED = "device_paired";
/**
- * Integer state indicating whether package verifier is enabled.
- * TODO(b/34259924): Remove this setting.
- *
- * @hide
- */
- public static final String PACKAGE_VERIFIER_STATE = "package_verifier_state";
-
- /**
* Specifies additional package name for broadcasting the CMAS messages.
* @hide
*/
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 262b9e50ad00..db3ef20d5859 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -675,6 +675,7 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall
mTmpTransaction.remove(mBackgroundControl);
mBackgroundControl = null;
}
+ mSurface.release();
mTmpTransaction.apply();
}
}
@@ -962,7 +963,6 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall
} finally {
mIsCreating = false;
if (mSurfaceControl != null && !mSurfaceCreated) {
- mSurface.release();
releaseSurfaces();
}
}
@@ -1143,6 +1143,7 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall
mRtTransaction.remove(mBackgroundControl);
mSurfaceControl = null;
mBackgroundControl = null;
+ mSurface.release();
}
mRtHandlingPositionUpdates = false;
}
diff --git a/core/java/android/view/accessibility/AccessibilityNodeProvider.java b/core/java/android/view/accessibility/AccessibilityNodeProvider.java
index 4b25378755f1..f4c7b96b8edc 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeProvider.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeProvider.java
@@ -44,28 +44,126 @@ import java.util.List;
* View itself. Similarly the returned instance is responsible for performing accessibility
* actions on any virtual view or the root view itself. For example:
* </p>
- * <pre>
- * getAccessibilityNodeProvider(
- * if (mAccessibilityNodeProvider == null) {
- * mAccessibilityNodeProvider = new AccessibilityNodeProvider() {
- * public boolean performAction(int action, int virtualDescendantId) {
- * // Implementation.
- * return false;
+ * <div>
+ * <div class="ds-selector-tabs"><section><h3 id="kotlin">Kotlin</h3>
+ * <pre class="prettyprint lang-kotlin">
+ * // "view" is the View instance on which this class performs accessibility functions.
+ * class MyCalendarViewAccessibilityDelegate(
+ * private var view: MyCalendarView) : AccessibilityDelegate() {
+ * override fun getAccessibilityNodeProvider(host: View): AccessibilityNodeProvider {
+ * return object : AccessibilityNodeProvider() {
+ * override fun createAccessibilityNodeInfo(virtualViewId: Int):
+ * AccessibilityNodeInfo? {
+ * when (virtualViewId) {
+ * <var>host-view-id</var> -&gt; {
+ * val node = AccessibilityNodeInfo.obtain(view)
+ * node.addChild(view, <var>child-view-id</var>)
+ * // Set other attributes like screenReaderFocusable
+ * // and contentDescription.
+ * return node
+ * }
+ * <var>child-view-id</var> -&gt; {
+ * val node = AccessibilityNodeInfo
+ * .obtain(view, virtualViewId)
+ * node.setParent(view)
+ * node.addAction(ACTION_SCROLL_UP)
+ * node.addAction(ACTION_SCROLL_DOWN)
+ * // Set other attributes like focusable and visibleToUser.
+ * node.setBoundsInScreen(
+ * Rect(<var>coords-of-edges-relative-to-screen</var>))
+ * return node
+ * }
+ * else -&gt; return null
* }
+ * }
*
- * public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String text,
- * int virtualDescendantId) {
- * // Implementation.
- * return null;
+ * override fun performAction(
+ * virtualViewId: Int,
+ * action: Int,
+ * arguments: Bundle
+ * ): Boolean {
+ * if (virtualViewId == <var>host-view-id</var>) {
+ * return view.performAccessibilityAction(action, arguments)
* }
+ * when (action) {
+ * ACTION_SCROLL_UP.id -&gt; {
+ * // Implement logic in a separate method.
+ * navigateToPreviousMonth()
*
- * public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualDescendantId) {
- * // Implementation.
- * return null;
+ * return true
+ * }
+ * ACTION_SCROLL_DOWN.id -&gt;
+ * // Implement logic in a separate method.
+ * navigateToNextMonth()
+ *
+ * return true
+ * else -&gt; return false
* }
- * });
- * return mAccessibilityNodeProvider;
+ * }
+ * }
+ * }
+ * }
* </pre>
+ * </section><section><h3 id="java">Java</h3>
+ * <pre class="prettyprint lang-java">
+ * final class MyCalendarViewAccessibilityDelegate extends AccessibilityDelegate {
+ * // The View instance on which this class performs accessibility functions.
+ * private final MyCalendarView view;
+ *
+ * MyCalendarViewAccessibilityDelegate(MyCalendarView view) {
+ * this.view = view;
+ * }
+ *
+ * &#64;Override
+ * public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
+ * return new AccessibilityNodeProvider() {
+ * &#64;Override
+ * &#64;Nullable
+ * public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) {
+ * if (virtualViewId == <var>host-view-id</var>) {
+ * AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain(view);
+ * node.addChild(view, <var>child-view-id</var>);
+ * // Set other attributes like screenReaderFocusable and contentDescription.
+ * return node;
+ * } else if (virtualViewId == <var>child-view-id</var>) {
+ * AccessibilityNodeInfo node =
+ * AccessibilityNodeInfo.obtain(view, virtualViewId);
+ * node.setParent(view);
+ * node.addAction(ACTION_SCROLL_UP);
+ * node.addAction(ACTION_SCROLL_DOWN);
+ * // Set other attributes like focusable and visibleToUser.
+ * node.setBoundsInScreen(
+ * new Rect(<var>coordinates-of-edges-relative-to-screen</var>));
+ * return node;
+ * } else {
+ * return null;
+ * }
+ * }
+ *
+ * &#64;Override
+ * public boolean performAction(int virtualViewId, int action, Bundle arguments) {
+ * if (virtualViewId == <var>host-view-id</var>) {
+ * return view.performAccessibilityAction(action, arguments);
+ * }
+ *
+ * if (action == ACTION_SCROLL_UP.getId()) {
+ * // Implement logic in a separate method.
+ * navigateToPreviousMonth();
+ *
+ * return true;
+ * } else if (action == ACTION_SCROLL_DOWN.getId()) {
+ * // Implement logic in a separate method.
+ * navigateToNextMonth();
+ *
+ * return true;
+ * } else {
+ * return false;
+ * }
+ * }
+ * };
+ * }
+ * }
+ * </pre></section></div></div>
*/
public abstract class AccessibilityNodeProvider {
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index 9d4cdc73b452..3ce3838a212e 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -135,6 +135,9 @@ public final class Zygote {
/** Read-write external storage should be mounted instead of package sandbox */
public static final int MOUNT_EXTERNAL_FULL = IVold.REMOUNT_MODE_FULL;
+ /** The lower file system should be bind mounted directly on external storage */
+ public static final int MOUNT_EXTERNAL_PASS_THROUGH = IVold.REMOUNT_MODE_PASS_THROUGH;
+
/** Number of bytes sent to the Zygote over USAP pipes or the pool event FD */
static final int USAP_MANAGEMENT_MESSAGE_BYTES = 8;
diff --git a/core/java/com/android/internal/os/ZygoteArguments.java b/core/java/com/android/internal/os/ZygoteArguments.java
index abc416061cc8..a23e659db49a 100644
--- a/core/java/com/android/internal/os/ZygoteArguments.java
+++ b/core/java/com/android/internal/os/ZygoteArguments.java
@@ -362,6 +362,8 @@ class ZygoteArguments {
mMountExternal = Zygote.MOUNT_EXTERNAL_INSTALLER;
} else if (arg.equals("--mount-external-legacy")) {
mMountExternal = Zygote.MOUNT_EXTERNAL_LEGACY;
+ } else if (arg.equals("--mount-external-pass-through")) {
+ mMountExternal = Zygote.MOUNT_EXTERNAL_PASS_THROUGH;
} else if (arg.equals("--query-abi-list")) {
mAbiListQuery = true;
} else if (arg.equals("--get-pid")) {
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 49b9eba76b1a..b4374fe26576 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -1169,6 +1169,12 @@ void AndroidRuntime::start(const char* className, const Vector<String8>& options
return;
}
+ const char* i18nRootDir = getenv("ANDROID_I18N_ROOT");
+ if (i18nRootDir == NULL) {
+ LOG_FATAL("No runtime directory specified with ANDROID_I18N_ROOT environment variable.");
+ return;
+ }
+
const char* tzdataRootDir = getenv("ANDROID_TZDATA_ROOT");
if (tzdataRootDir == NULL) {
LOG_FATAL("No tz data directory specified with ANDROID_TZDATA_ROOT environment variable.");
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index d42a48a1f899..93ef75148df7 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -303,7 +303,8 @@ enum MountExternalKind {
MOUNT_EXTERNAL_LEGACY = 4,
MOUNT_EXTERNAL_INSTALLER = 5,
MOUNT_EXTERNAL_FULL = 6,
- MOUNT_EXTERNAL_COUNT = 7
+ MOUNT_EXTERNAL_PASS_THROUGH = 7,
+ MOUNT_EXTERNAL_COUNT = 8
};
// The order of entries here must be kept in sync with MountExternalKind enum values.
@@ -708,15 +709,14 @@ static void MountEmulatedStorage(uid_t uid, jint mount_mode,
const userid_t user_id = multiuser_get_user_id(uid);
const std::string user_source = StringPrintf("/mnt/user/%d", user_id);
+ const std::string pass_through_source = StringPrintf("/mnt/pass_through/%d", user_id);
bool isFuse = GetBoolProperty(kPropFuse, false);
CreateDir(user_source, 0751, AID_ROOT, AID_ROOT, fail_fn);
if (isFuse) {
- // TODO(b/135341433): Bind mount the appropriate storage view for the app given its permissions
- // media and media_location permission access. This should prevent the kernel from incorrectly
- // sharing a cache across permission buckets
- BindMount(user_source, "/storage", fail_fn);
+ BindMount(mount_mode == MOUNT_EXTERNAL_PASS_THROUGH ? pass_through_source : user_source,
+ "/storage", fail_fn);
} else {
const std::string& storage_source = ExternalStorageViews[mount_mode];
BindMount(storage_source, "/storage", fail_fn);
diff --git a/core/proto/android/server/protolog.proto b/core/proto/android/server/protolog.proto
index 7c98d318570b..3512c0aea4a5 100644
--- a/core/proto/android/server/protolog.proto
+++ b/core/proto/android/server/protolog.proto
@@ -23,7 +23,7 @@ option java_multiple_files = true;
/* represents a single log entry */
message ProtoLogMessage {
/* log statement identifier, created from message string and log level. */
- optional fixed32 message_hash = 1;
+ optional sfixed32 message_hash = 1;
/* log time, relative to the elapsed system time clock. */
optional fixed64 elapsed_realtime_nanos = 2;
/* string parameters passed to the log call. */
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 1d590ea2f896..7a0d0cbe6095 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -2552,6 +2552,19 @@
android:label="@string/permlab_readSyncStats"
android:protectionLevel="normal" />
+ <!-- ==================================================== -->
+ <!-- Permissions related to accessibility -->
+ <!-- ==================================================== -->
+ <eat-comment />
+
+ <!-- Allows applications to define the accessibility shortcut target.
+ <p>Protection level: normal
+ -->
+ <permission android:name="android.permission.ACCESSIBILITY_SHORTCUT_TARGET"
+ android:description="@string/permdesc_accessibilityShortcutTarget"
+ android:label="@string/permlab_accessibilityShortcutTarget"
+ android:protectionLevel="normal" />
+
<!-- ============================================ -->
<!-- Permissions for low-level system interaction -->
<!-- ============================================ -->
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index d2989d9a8ab6..56e1fed5bcec 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1745,6 +1745,11 @@
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permdesc_startViewPermissionUsage">Allows the holder to start the permission usage for an app. Should never be needed for normal apps.</string>
+ <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
+ <string name="permlab_accessibilityShortcutTarget">accessibility shortcut target</string>
+ <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
+ <string name="permdesc_accessibilityShortcutTarget">Allows an app to define the accessibility shortcut target.</string>
+
<!-- Policy administration -->
<!-- Title of policy access to limiting the user's password choices -->
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
index 261891fb3bbc..f32935fa300f 100644
--- a/data/etc/services.core.protolog.json
+++ b/data/etc/services.core.protolog.json
@@ -1,10 +1,11 @@
{
"version": "1.0.0",
"messages": {
- "485522692": {
+ "594230385": {
"message": "Test completed successfully: %b %d %o %x %e %g %f %% %s.",
"level": "ERROR",
- "group": "TEST_GROUP"
+ "group": "TEST_GROUP",
+ "at": "com\/android\/server\/wm\/ProtoLogGroup.java:94"
}
},
"groups": {
diff --git a/media/Android.bp b/media/Android.bp
index a59b3e76faed..2f75e4458ef5 100644
--- a/media/Android.bp
+++ b/media/Android.bp
@@ -63,26 +63,6 @@ filegroup {
path: "apex/java",
}
-filegroup {
- name: "mediaplayer2-srcs",
- srcs: [
- "apex/java/android/media/CloseGuard.java",
- "apex/java/android/media/DataSourceCallback.java",
- "apex/java/android/media/DataSourceDesc.java",
- "apex/java/android/media/UriDataSourceDesc.java",
- "apex/java/android/media/FileDataSourceDesc.java",
- "apex/java/android/media/Media2Utils.java",
- "apex/java/android/media/MediaPlayer2Utils.java",
- "apex/java/android/media/MediaPlayer2.java",
- "apex/java/android/media/Media2HTTPService.java",
- "apex/java/android/media/Media2HTTPConnection.java",
- "apex/java/android/media/RoutingDelegate.java",
- "apex/java/android/media/BufferingParams.java",
- "apex/java/android/media/ProxyDataSourceCallback.java",
- ],
- path: "apex/java",
-}
-
metalava_updatable_media_args = " --error UnhiddenSystemApi " +
"--hide RequiresPermission " +
"--hide MissingPermission --hide BroadcastBehavior " +
diff --git a/media/apex/java/android/media/DataSourceDesc.java b/media/apex/java/android/media/DataSourceDesc.java
deleted file mode 100644
index 9a9c74aba2c7..000000000000
--- a/media/apex/java/android/media/DataSourceDesc.java
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * Copyright 2018 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.media;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.Uri;
-import android.os.ParcelFileDescriptor;
-
-import java.net.CookieHandler;
-import java.net.CookieManager;
-import java.net.HttpCookie;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Data source descriptor.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * @hide
- */
-public class DataSourceDesc {
- // intentionally less than long.MAX_VALUE
- static final long LONG_MAX = 0x7ffffffffffffffL;
-
- // keep consistent with native code
- public static final long LONG_MAX_TIME_MS = LONG_MAX / 1000;
- /**
- * @hide
- */
- public static final long LONG_MAX_TIME_US = LONG_MAX_TIME_MS * 1000;
-
- public static final long POSITION_UNKNOWN = LONG_MAX_TIME_MS;
-
- private String mMediaId;
- private long mStartPositionMs = 0;
- private long mEndPositionMs = POSITION_UNKNOWN;
-
- DataSourceDesc(String mediaId, long startPositionMs, long endPositionMs) {
- mMediaId = mediaId;
- mStartPositionMs = startPositionMs;
- mEndPositionMs = endPositionMs;
- }
-
- /**
- * Releases the resources held by this {@code DataSourceDesc} object.
- */
- void close() {
- }
-
- // Have to declare protected for finalize() since it is protected
- // in the base class Object.
- @Override
- protected void finalize() throws Throwable {
- close();
- }
-
- /**
- * Return the media Id of data source.
- * @return the media Id of data source
- */
- public @Nullable String getMediaId() {
- return mMediaId;
- }
-
- /**
- * Return the position in milliseconds at which the playback will start.
- * @return the position in milliseconds at which the playback will start
- */
- public long getStartPosition() {
- return mStartPositionMs;
- }
-
- /**
- * Return the position in milliseconds at which the playback will end.
- * {@link #POSITION_UNKNOWN} means ending at the end of source content.
- * @return the position in milliseconds at which the playback will end
- */
- public long getEndPosition() {
- return mEndPositionMs;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("DataSourceDesc{");
- sb.append("mMediaId=").append(mMediaId);
- sb.append(", mStartPositionMs=").append(mStartPositionMs);
- sb.append(", mEndPositionMs=").append(mEndPositionMs);
- sb.append('}');
- return sb.toString();
- }
-
- /**
- * Builder for {@link DataSourceDesc}.
- * <p>
- * Here is an example where <code>Builder</code> is used to define the
- * {@link DataSourceDesc} to be used by a {@link MediaPlayer2} instance:
- *
- * <pre class="prettyprint">
- * DataSourceDesc newDSD = new DataSourceDesc.Builder()
- * .setDataSource(context, uri, headers, cookies)
- * .setStartPosition(1000)
- * .setEndPosition(15000)
- * .build();
- * mediaplayer2.setDataSourceDesc(newDSD);
- * </pre>
- */
- public static final class Builder {
- private static final int SOURCE_TYPE_UNKNOWN = 0;
- private static final int SOURCE_TYPE_URI = 1;
- private static final int SOURCE_TYPE_FILE = 2;
-
- private int mSourceType = SOURCE_TYPE_UNKNOWN;
- private String mMediaId;
- private long mStartPositionMs = 0;
- private long mEndPositionMs = POSITION_UNKNOWN;
-
- // For UriDataSourceDesc
- private Uri mUri;
- private Map<String, String> mHeader;
- private List<HttpCookie> mCookies;
-
- // For FileDataSourceDesc
- private ParcelFileDescriptor mPFD;
- private long mOffset = 0;
- private long mLength = FileDataSourceDesc.FD_LENGTH_UNKNOWN;
-
- /**
- * Constructs a new BuilderBase with the defaults.
- */
- public Builder() {
- }
-
- /**
- * Constructs a new BuilderBase from a given {@link DataSourceDesc} instance
- * @param dsd the {@link DataSourceDesc} object whose data will be reused
- * in the new BuilderBase.
- */
- public Builder(@Nullable DataSourceDesc dsd) {
- if (dsd == null) {
- return;
- }
- mMediaId = dsd.mMediaId;
- mStartPositionMs = dsd.mStartPositionMs;
- mEndPositionMs = dsd.mEndPositionMs;
- if (dsd instanceof FileDataSourceDesc) {
- mSourceType = SOURCE_TYPE_FILE;
- mPFD = ((FileDataSourceDesc) dsd).getParcelFileDescriptor();
- mOffset = ((FileDataSourceDesc) dsd).getOffset();
- mLength = ((FileDataSourceDesc) dsd).getLength();
- } else if (dsd instanceof UriDataSourceDesc) {
- mSourceType = SOURCE_TYPE_URI;
- mUri = ((UriDataSourceDesc) dsd).getUri();
- mHeader = ((UriDataSourceDesc) dsd).getHeaders();
- mCookies = ((UriDataSourceDesc) dsd).getCookies();
- } else {
- throw new IllegalStateException("Unknown source type:" + mSourceType);
- }
- }
-
- /**
- * Sets all fields that have been set in the {@link DataSourceDesc} object.
- * <code>IllegalStateException</code> will be thrown if there is conflict between fields.
- *
- * @return {@link DataSourceDesc}
- */
- @NonNull
- public DataSourceDesc build() {
- if (mSourceType == SOURCE_TYPE_UNKNOWN) {
- throw new IllegalStateException("Source is not set.");
- }
- if (mStartPositionMs > mEndPositionMs) {
- throw new IllegalStateException("Illegal start/end position: "
- + mStartPositionMs + " : " + mEndPositionMs);
- }
-
- DataSourceDesc desc;
- if (mSourceType == SOURCE_TYPE_FILE) {
- desc = new FileDataSourceDesc(
- mMediaId, mStartPositionMs, mEndPositionMs, mPFD, mOffset, mLength);
- } else if (mSourceType == SOURCE_TYPE_URI) {
- desc = new UriDataSourceDesc(
- mMediaId, mStartPositionMs, mEndPositionMs, mUri, mHeader, mCookies);
- } else {
- throw new IllegalStateException("Unknown source type:" + mSourceType);
- }
- return desc;
- }
-
- /**
- * Sets the media Id of this data source.
- *
- * @param mediaId the media Id of this data source
- * @return the same Builder instance.
- */
- @NonNull
- public Builder setMediaId(@Nullable String mediaId) {
- mMediaId = mediaId;
- return this;
- }
-
- /**
- * Sets the start position in milliseconds at which the playback will start.
- * Any negative number is treated as 0.
- *
- * @param position the start position in milliseconds at which the playback will start
- * @return the same Builder instance.
- *
- */
- @NonNull
- public Builder setStartPosition(long position) {
- if (position < 0) {
- position = 0;
- }
- mStartPositionMs = position;
- return this;
- }
-
- /**
- * Sets the end position in milliseconds at which the playback will end.
- * Any negative number is treated as maximum duration {@link #LONG_MAX_TIME_MS}
- * of the data source
- *
- * @param position the end position in milliseconds at which the playback will end
- * @return the same Builder instance.
- */
- @NonNull
- public Builder setEndPosition(long position) {
- if (position < 0) {
- position = LONG_MAX_TIME_MS;
- }
- mEndPositionMs = position;
- return this;
- }
-
- /**
- * Sets the data source as a content Uri.
- *
- * @param uri the Content URI of the data you want to play
- * @return the same Builder instance.
- * @throws NullPointerException if context or uri is null.
- */
- @NonNull
- public Builder setDataSource(@NonNull Uri uri) {
- setSourceType(SOURCE_TYPE_URI);
- Media2Utils.checkArgument(uri != null, "uri cannot be null");
- mUri = uri;
- return this;
- }
-
- /**
- * Sets the data source as a content Uri.
- *
- * To provide cookies for the subsequent HTTP requests, you can install your own default
- * cookie handler and use other variants of setDataSource APIs instead. Alternatively, you
- * can use this API to pass the cookies as a list of HttpCookie. If the app has not
- * installed a CookieHandler already, {@link MediaPlayer2} will create a CookieManager
- * and populates its CookieStore with the provided cookies when this data source is passed
- * to {@link MediaPlayer2}. If the app has installed its own handler already, the handler
- * is required to be of CookieManager type such that {@link MediaPlayer2} can update the
- * manager’s CookieStore.
- *
- * <p><strong>Note</strong> that the cross domain redirection is allowed by default,
- * but that can be changed with key/value pairs through the headers parameter with
- * "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value to
- * disallow or allow cross domain redirection.
- *
- * @param uri the Content URI of the data you want to play
- * @param headers the headers to be sent together with the request for the data
- * The headers must not include cookies. Instead, use the cookies param.
- * @param cookies the cookies to be sent together with the request
- * @return the same Builder instance.
- * @throws NullPointerException if context or uri is null.
- * @throws IllegalArgumentException if the cookie handler is not of CookieManager type
- * when cookies are provided.
- */
- @NonNull
- public Builder setDataSource(@NonNull Uri uri, @Nullable Map<String, String> headers,
- @Nullable List<HttpCookie> cookies) {
- setSourceType(SOURCE_TYPE_URI);
- Media2Utils.checkArgument(uri != null, "uri cannot be null");
- if (cookies != null) {
- CookieHandler cookieHandler = CookieHandler.getDefault();
- if (cookieHandler != null && !(cookieHandler instanceof CookieManager)) {
- throw new IllegalArgumentException(
- "The cookie handler has to be of CookieManager type "
- + "when cookies are provided.");
- }
- }
-
- mUri = uri;
- if (headers != null) {
- mHeader = new HashMap<String, String>(headers);
- }
- if (cookies != null) {
- mCookies = new ArrayList<HttpCookie>(cookies);
- }
- return this;
- }
-
- /**
- * Sets the data source (ParcelFileDescriptor) to use. The ParcelFileDescriptor must be
- * seekable (N.B. a LocalSocket is not seekable). When the {@link DataSourceDesc}
- * created by this builder is passed to {@link MediaPlayer2} via
- * {@link MediaPlayer2#setDataSource},
- * {@link MediaPlayer2#setNextDataSource} or
- * {@link MediaPlayer2#setNextDataSources}, MediaPlayer2 will
- * close the ParcelFileDescriptor.
- *
- * @param pfd the ParcelFileDescriptor for the file to play
- * @return the same Builder instance.
- * @throws NullPointerException if pfd is null.
- */
- @NonNull
- public Builder setDataSource(@NonNull ParcelFileDescriptor pfd) {
- setSourceType(SOURCE_TYPE_FILE);
- Media2Utils.checkArgument(pfd != null, "pfd cannot be null.");
- mPFD = pfd;
- return this;
- }
-
- /**
- * Sets the data source (ParcelFileDescriptor) to use. The ParcelFileDescriptor must be
- * seekable (N.B. a LocalSocket is not seekable). When the {@link DataSourceDesc}
- * created by this builder is passed to {@link MediaPlayer2} via
- * {@link MediaPlayer2#setDataSource},
- * {@link MediaPlayer2#setNextDataSource} or
- * {@link MediaPlayer2#setNextDataSources}, MediaPlayer2 will
- * close the ParcelFileDescriptor.
- *
- * Any negative number for offset is treated as 0.
- * Any negative number for length is treated as maximum length of the data source.
- *
- * @param pfd the ParcelFileDescriptor for the file to play
- * @param offset the offset into the file where the data to be played starts, in bytes
- * @param length the length in bytes of the data to be played
- * @return the same Builder instance.
- * @throws NullPointerException if pfd is null.
- */
- @NonNull
- public Builder setDataSource(
- @NonNull ParcelFileDescriptor pfd, long offset, long length) {
- setSourceType(SOURCE_TYPE_FILE);
- if (pfd == null) {
- throw new NullPointerException("pfd cannot be null.");
- }
- if (offset < 0) {
- offset = 0;
- }
- if (length < 0) {
- length = FileDataSourceDesc.FD_LENGTH_UNKNOWN;
- }
- mPFD = pfd;
- mOffset = offset;
- mLength = length;
- return this;
- }
-
- private void setSourceType(int type) {
- if (mSourceType != SOURCE_TYPE_UNKNOWN) {
- throw new IllegalStateException("Source is already set. type=" + mSourceType);
- }
- mSourceType = type;
- }
- }
-}
diff --git a/media/apex/java/android/media/FileDataSourceDesc.java b/media/apex/java/android/media/FileDataSourceDesc.java
deleted file mode 100644
index 2aa2cb7eb1bb..000000000000
--- a/media/apex/java/android/media/FileDataSourceDesc.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright 2018 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.media;
-
-import android.annotation.NonNull;
-import android.os.ParcelFileDescriptor;
-import android.util.Log;
-
-import java.io.IOException;
-
-/**
- * Structure of data source descriptor for sources using file descriptor.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * <p>Users should use {@link Builder} to create {@link FileDataSourceDesc}.
- * @hide
- */
-public class FileDataSourceDesc extends DataSourceDesc {
- private static final String TAG = "FileDataSourceDesc";
-
- /**
- * Used when the length of file descriptor is unknown.
- *
- * @see #getLength()
- */
- public static final long FD_LENGTH_UNKNOWN = LONG_MAX;
-
- private ParcelFileDescriptor mPFD;
- private long mOffset = 0;
- private long mLength = FD_LENGTH_UNKNOWN;
- private int mCount = 0;
- private boolean mClosed = false;
-
- FileDataSourceDesc(String mediaId, long startPositionMs, long endPositionMs,
- ParcelFileDescriptor pfd, long offset, long length) {
- super(mediaId, startPositionMs, endPositionMs);
- mPFD = pfd;
- mOffset = offset;
- mLength = length;
- }
-
- /**
- * Releases the resources held by this {@code FileDataSourceDesc} object.
- */
- @Override
- void close() {
- super.close();
- decCount();
- }
-
- /**
- * Decrements usage count by {@link MediaPlayer2}.
- * If this is the last usage, also releases the file descriptor held by this
- * {@code FileDataSourceDesc} object.
- */
- void decCount() {
- synchronized (this) {
- --mCount;
- if (mCount > 0) {
- return;
- }
-
- try {
- mPFD.close();
- mClosed = true;
- } catch (IOException e) {
- Log.e(TAG, "failed to close pfd: " + e);
- }
- }
- }
-
- /**
- * Increments usage count by {@link MediaPlayer2} if PFD has not been closed.
- */
- void incCount() {
- synchronized (this) {
- if (!mClosed) {
- ++mCount;
- }
- }
- }
-
- /**
- * Return the status of underline ParcelFileDescriptor
- * @return true if underline ParcelFileDescriptor is closed, false otherwise.
- */
- boolean isPFDClosed() {
- synchronized (this) {
- return mClosed;
- }
- }
-
- /**
- * Return the ParcelFileDescriptor of this data source.
- * @return the ParcelFileDescriptor of this data source
- */
- public @NonNull ParcelFileDescriptor getParcelFileDescriptor() {
- return mPFD;
- }
-
- /**
- * Return the offset associated with the ParcelFileDescriptor of this data source.
- * It's meaningful only when it has been set by the {@link Builder}.
- * @return the offset associated with the ParcelFileDescriptor of this data source
- */
- public long getOffset() {
- return mOffset;
- }
-
- /**
- * Return the content length associated with the ParcelFileDescriptor of this data source.
- * {@link #FD_LENGTH_UNKNOWN} means same as the length of source content.
- * @return the content length associated with the ParcelFileDescriptor of this data source
- */
- public long getLength() {
- return mLength;
- }
-}
diff --git a/media/apex/java/android/media/Media2HTTPConnection.java b/media/apex/java/android/media/Media2HTTPConnection.java
deleted file mode 100644
index a369a62b39db..000000000000
--- a/media/apex/java/android/media/Media2HTTPConnection.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Copyright 2017 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.media;
-
-import static android.media.MediaPlayer2.MEDIA_ERROR_UNSUPPORTED;
-
-import android.os.StrictMode;
-import android.util.Log;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.CookieHandler;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.NoRouteToHostException;
-import java.net.ProtocolException;
-import java.net.Proxy;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.net.UnknownServiceException;
-import java.util.HashMap;
-import java.util.Map;
-
-/** @hide */
-public class Media2HTTPConnection {
- private static final String TAG = "Media2HTTPConnection";
- private static final boolean VERBOSE = false;
-
- // connection timeout - 30 sec
- private static final int CONNECT_TIMEOUT_MS = 30 * 1000;
-
- private long mCurrentOffset = -1;
- private URL mURL = null;
- private Map<String, String> mHeaders = null;
- private HttpURLConnection mConnection = null;
- private long mTotalSize = -1;
- private InputStream mInputStream = null;
-
- private boolean mAllowCrossDomainRedirect = true;
- private boolean mAllowCrossProtocolRedirect = true;
-
- // from com.squareup.okhttp.internal.http
- private final static int HTTP_TEMP_REDIRECT = 307;
- private final static int MAX_REDIRECTS = 20;
-
- public Media2HTTPConnection() {
- CookieHandler cookieHandler = CookieHandler.getDefault();
- if (cookieHandler == null) {
- Log.w(TAG, "Media2HTTPConnection: Unexpected. No CookieHandler found.");
- }
- }
-
- public boolean connect(String uri, String headers) {
- if (VERBOSE) {
- Log.d(TAG, "connect: uri=" + uri + ", headers=" + headers);
- }
-
- try {
- disconnect();
- mAllowCrossDomainRedirect = true;
- mURL = new URL(uri);
- mHeaders = convertHeaderStringToMap(headers);
- } catch (MalformedURLException e) {
- return false;
- }
-
- return true;
- }
-
- private boolean parseBoolean(String val) {
- try {
- return Long.parseLong(val) != 0;
- } catch (NumberFormatException e) {
- return "true".equalsIgnoreCase(val) ||
- "yes".equalsIgnoreCase(val);
- }
- }
-
- /* returns true iff header is internal */
- private boolean filterOutInternalHeaders(String key, String val) {
- if ("android-allow-cross-domain-redirect".equalsIgnoreCase(key)) {
- mAllowCrossDomainRedirect = parseBoolean(val);
- // cross-protocol redirects are also controlled by this flag
- mAllowCrossProtocolRedirect = mAllowCrossDomainRedirect;
- } else {
- return false;
- }
- return true;
- }
-
- private Map<String, String> convertHeaderStringToMap(String headers) {
- HashMap<String, String> map = new HashMap<String, String>();
-
- String[] pairs = headers.split("\r\n");
- for (String pair : pairs) {
- int colonPos = pair.indexOf(":");
- if (colonPos >= 0) {
- String key = pair.substring(0, colonPos);
- String val = pair.substring(colonPos + 1);
-
- if (!filterOutInternalHeaders(key, val)) {
- map.put(key, val);
- }
- }
- }
-
- return map;
- }
-
- public void disconnect() {
- teardownConnection();
- mHeaders = null;
- mURL = null;
- }
-
- private void teardownConnection() {
- if (mConnection != null) {
- if (mInputStream != null) {
- try {
- mInputStream.close();
- } catch (IOException e) {
- }
- mInputStream = null;
- }
-
- mConnection.disconnect();
- mConnection = null;
-
- mCurrentOffset = -1;
- }
- }
-
- private static final boolean isLocalHost(URL url) {
- if (url == null) {
- return false;
- }
-
- String host = url.getHost();
-
- if (host == null) {
- return false;
- }
-
- try {
- if (host.equalsIgnoreCase("localhost")) {
- return true;
- }
- if (InetAddress.getByName(host).isLoopbackAddress()) {
- return true;
- }
- } catch (IllegalArgumentException | UnknownHostException e) {
- }
- return false;
- }
-
- private void seekTo(long offset) throws IOException {
- teardownConnection();
-
- try {
- int response;
- int redirectCount = 0;
-
- URL url = mURL;
-
- // do not use any proxy for localhost (127.0.0.1)
- boolean noProxy = isLocalHost(url);
-
- while (true) {
- if (noProxy) {
- mConnection = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
- } else {
- mConnection = (HttpURLConnection)url.openConnection();
- }
- mConnection.setConnectTimeout(CONNECT_TIMEOUT_MS);
-
- // handle redirects ourselves if we do not allow cross-domain redirect
- mConnection.setInstanceFollowRedirects(mAllowCrossDomainRedirect);
-
- if (mHeaders != null) {
- for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
- mConnection.setRequestProperty(
- entry.getKey(), entry.getValue());
- }
- }
-
- if (offset > 0) {
- mConnection.setRequestProperty(
- "Range", "bytes=" + offset + "-");
- }
-
- response = mConnection.getResponseCode();
- if (response != HttpURLConnection.HTTP_MULT_CHOICE &&
- response != HttpURLConnection.HTTP_MOVED_PERM &&
- response != HttpURLConnection.HTTP_MOVED_TEMP &&
- response != HttpURLConnection.HTTP_SEE_OTHER &&
- response != HTTP_TEMP_REDIRECT) {
- // not a redirect, or redirect handled by HttpURLConnection
- break;
- }
-
- if (++redirectCount > MAX_REDIRECTS) {
- throw new NoRouteToHostException("Too many redirects: " + redirectCount);
- }
-
- String method = mConnection.getRequestMethod();
- if (response == HTTP_TEMP_REDIRECT &&
- !method.equals("GET") && !method.equals("HEAD")) {
- // "If the 307 status code is received in response to a
- // request other than GET or HEAD, the user agent MUST NOT
- // automatically redirect the request"
- throw new NoRouteToHostException("Invalid redirect");
- }
- String location = mConnection.getHeaderField("Location");
- if (location == null) {
- throw new NoRouteToHostException("Invalid redirect");
- }
- url = new URL(mURL /* TRICKY: don't use url! */, location);
- if (!url.getProtocol().equals("https") &&
- !url.getProtocol().equals("http")) {
- throw new NoRouteToHostException("Unsupported protocol redirect");
- }
- boolean sameProtocol = mURL.getProtocol().equals(url.getProtocol());
- if (!mAllowCrossProtocolRedirect && !sameProtocol) {
- throw new NoRouteToHostException("Cross-protocol redirects are disallowed");
- }
- boolean sameHost = mURL.getHost().equals(url.getHost());
- if (!mAllowCrossDomainRedirect && !sameHost) {
- throw new NoRouteToHostException("Cross-domain redirects are disallowed");
- }
-
- if (response != HTTP_TEMP_REDIRECT) {
- // update effective URL, unless it is a Temporary Redirect
- mURL = url;
- }
- }
-
- if (mAllowCrossDomainRedirect) {
- // remember the current, potentially redirected URL if redirects
- // were handled by HttpURLConnection
- mURL = mConnection.getURL();
- }
-
- if (response == HttpURLConnection.HTTP_PARTIAL) {
- // Partial content, we cannot just use getContentLength
- // because what we want is not just the length of the range
- // returned but the size of the full content if available.
-
- String contentRange =
- mConnection.getHeaderField("Content-Range");
-
- mTotalSize = -1;
- if (contentRange != null) {
- // format is "bytes xxx-yyy/zzz
- // where "zzz" is the total number of bytes of the
- // content or '*' if unknown.
-
- int lastSlashPos = contentRange.lastIndexOf('/');
- if (lastSlashPos >= 0) {
- String total =
- contentRange.substring(lastSlashPos + 1);
-
- try {
- mTotalSize = Long.parseLong(total);
- } catch (NumberFormatException e) {
- }
- }
- }
- } else if (response != HttpURLConnection.HTTP_OK) {
- throw new IOException();
- } else {
- mTotalSize = mConnection.getContentLength();
- }
-
- if (offset > 0 && response != HttpURLConnection.HTTP_PARTIAL) {
- // Some servers simply ignore "Range" requests and serve
- // data from the start of the content.
- throw new ProtocolException();
- }
-
- mInputStream =
- new BufferedInputStream(mConnection.getInputStream());
-
- mCurrentOffset = offset;
- } catch (IOException e) {
- mTotalSize = -1;
- teardownConnection();
- mCurrentOffset = -1;
-
- throw e;
- }
- }
-
- public int readAt(long offset, byte[] data, int size) {
- StrictMode.ThreadPolicy policy =
- new StrictMode.ThreadPolicy.Builder().permitAll().build();
-
- StrictMode.setThreadPolicy(policy);
-
- try {
- if (offset != mCurrentOffset) {
- seekTo(offset);
- }
-
- int n = mInputStream.read(data, 0, size);
-
- if (n == -1) {
- // InputStream signals EOS using a -1 result, our semantics
- // are to return a 0-length read.
- n = 0;
- }
-
- mCurrentOffset += n;
-
- if (VERBOSE) {
- Log.d(TAG, "readAt " + offset + " / " + size + " => " + n);
- }
-
- return n;
- } catch (ProtocolException e) {
- Log.w(TAG, "readAt " + offset + " / " + size + " => " + e);
- return MEDIA_ERROR_UNSUPPORTED;
- } catch (NoRouteToHostException e) {
- Log.w(TAG, "readAt " + offset + " / " + size + " => " + e);
- return MEDIA_ERROR_UNSUPPORTED;
- } catch (UnknownServiceException e) {
- Log.w(TAG, "readAt " + offset + " / " + size + " => " + e);
- return MEDIA_ERROR_UNSUPPORTED;
- } catch (IOException e) {
- if (VERBOSE) {
- Log.d(TAG, "readAt " + offset + " / " + size + " => -1");
- }
- return -1;
- } catch (Exception e) {
- if (VERBOSE) {
- Log.d(TAG, "unknown exception " + e);
- Log.d(TAG, "readAt " + offset + " / " + size + " => -1");
- }
- return -1;
- }
- }
-
- public long getSize() {
- if (mConnection == null) {
- try {
- seekTo(0);
- } catch (IOException e) {
- return -1;
- }
- }
-
- return mTotalSize;
- }
-
- public String getMIMEType() {
- if (mConnection == null) {
- try {
- seekTo(0);
- } catch (IOException e) {
- return "application/octet-stream";
- }
- }
-
- return mConnection.getContentType();
- }
-
- public String getUri() {
- return mURL.toString();
- }
-}
diff --git a/media/apex/java/android/media/Media2HTTPService.java b/media/apex/java/android/media/Media2HTTPService.java
deleted file mode 100644
index 0d46ce404831..000000000000
--- a/media/apex/java/android/media/Media2HTTPService.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2017 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.media;
-
-import android.util.Log;
-
-import java.net.HttpCookie;
-import java.util.List;
-
-/** @hide */
-public class Media2HTTPService {
- private static final String TAG = "Media2HTTPService";
- private List<HttpCookie> mCookies;
- private Boolean mCookieStoreInitialized = new Boolean(false);
-
- public Media2HTTPService(List<HttpCookie> cookies) {
- mCookies = cookies;
- Log.v(TAG, "Media2HTTPService(" + this + "): Cookies: " + cookies);
- }
-
- public Media2HTTPConnection makeHTTPConnection() {
-
- synchronized (mCookieStoreInitialized) {
- Media2Utils.storeCookies(mCookies);
- }
-
- return new Media2HTTPConnection();
- }
-
- /* package private */ static Media2HTTPService createHTTPService(String path) {
- return createHTTPService(path, null);
- }
-
- // when cookies are provided
- static Media2HTTPService createHTTPService(String path, List<HttpCookie> cookies) {
- if (path.startsWith("http://") || path.startsWith("https://")) {
- return (new Media2HTTPService(cookies));
- } else if (path.startsWith("widevine://")) {
- Log.d(TAG, "Widevine classic is no longer supported");
- }
-
- return null;
- }
-}
diff --git a/media/apex/java/android/media/Media2Utils.java b/media/apex/java/android/media/Media2Utils.java
deleted file mode 100644
index a87e9676d017..000000000000
--- a/media/apex/java/android/media/Media2Utils.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2018 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.media;
-
-import android.util.Log;
-
-import java.net.CookieHandler;
-import java.net.CookieManager;
-import java.net.CookieStore;
-import java.net.HttpCookie;
-import java.util.List;
-
-/** @hide */
-public class Media2Utils {
- private static final String TAG = "Media2Utils";
-
- private Media2Utils() {
- }
-
- /**
- * Ensures that an expression checking an argument is true.
- *
- * @param expression the expression to check
- * @param errorMessage the exception message to use if the check fails; will
- * be converted to a string using {@link String#valueOf(Object)}
- * @throws IllegalArgumentException if {@code expression} is false
- */
- public static void checkArgument(boolean expression, String errorMessage) {
- if (!expression) {
- throw new IllegalArgumentException(errorMessage);
- }
- }
-
- public static synchronized void storeCookies(List<HttpCookie> cookies) {
- CookieHandler cookieHandler = CookieHandler.getDefault();
- if (cookieHandler == null) {
- cookieHandler = new CookieManager();
- CookieHandler.setDefault(cookieHandler);
- Log.v(TAG, "storeCookies: CookieManager created: " + cookieHandler);
- } else {
- Log.v(TAG, "storeCookies: CookieHandler (" + cookieHandler + ") exists.");
- }
-
- if (cookies != null) {
- if (cookieHandler instanceof CookieManager) {
- CookieManager cookieManager = (CookieManager)cookieHandler;
- CookieStore store = cookieManager.getCookieStore();
- for (HttpCookie cookie : cookies) {
- try {
- store.add(null, cookie);
- } catch (Exception e) {
- Log.v(TAG, "storeCookies: CookieStore.add" + cookie, e);
- }
- }
- } else {
- Log.w(TAG, "storeCookies: The installed CookieHandler is not a CookieManager."
- + " Can’t add the provided cookies to the cookie store.");
- }
- } // cookies
-
- Log.v(TAG, "storeCookies: cookieHandler: " + cookieHandler + " Cookies: " + cookies);
-
- }
-}
diff --git a/media/apex/java/android/media/MediaPlayer2.java b/media/apex/java/android/media/MediaPlayer2.java
deleted file mode 100644
index 614d737e3758..000000000000
--- a/media/apex/java/android/media/MediaPlayer2.java
+++ /dev/null
@@ -1,5507 +0,0 @@
-/*
- * Copyright 2017 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.media;
-
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.StringDef;
-import android.annotation.TestApi;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.res.AssetFileDescriptor;
-import android.graphics.Rect;
-import android.graphics.SurfaceTexture;
-import android.media.MediaDrm.KeyRequest;
-import android.media.MediaPlayer2.DrmInfo;
-import android.media.MediaPlayer2Proto.PlayerMessage;
-import android.media.MediaPlayer2Proto.Value;
-import android.media.protobuf.InvalidProtocolBufferException;
-import android.net.Uri;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
-import android.os.Message;
-import android.os.ParcelFileDescriptor;
-import android.os.PersistableBundle;
-import android.os.PowerManager;
-import android.util.Log;
-import android.util.Pair;
-import android.util.Size;
-import android.view.Surface;
-import android.view.SurfaceHolder;
-
-import com.android.internal.annotations.GuardedBy;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.ref.WeakReference;
-import java.net.HttpCookie;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.UUID;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * MediaPlayer2 class can be used to control playback of audio/video files and streams.
- *
- * <p>
- * This API is not generally intended for third party application developers.
- * Use the <a href="{@docRoot}jetpack/androidx.html">AndroidX</a>
- * <a href="{@docRoot}reference/androidx/media2/package-summary.html">Media2 Library</a>
- * for consistent behavior across all devices.
- *
- * <p>Topics covered here are:
- * <ol>
- * <li><a href="#PlayerStates">Player states</a>
- * <li><a href="#InvalidStates">Invalid method calls</a>
- * <li><a href="#Permissions">Permissions</a>
- * <li><a href="#Callbacks">Callbacks</a>
- * </ol>
- *
- *
- * <h3 id="PlayerStates">Player states</h3>
- *
- * <p>The playback control of audio/video files is managed as a state machine.</p>
- * <p><div style="text-align:center;"><img src="../../../images/mediaplayer2_state_diagram.png"
- * alt="MediaPlayer2 State diagram"
- * border="0" /></div></p>
- * <p>The MediaPlayer2 object has five states:</p>
- * <ol>
- * <li><p>{@link #PLAYER_STATE_IDLE}: MediaPlayer2 is in the <strong>Idle</strong>
- * state after it's created, or after calling {@link #reset()}.</p>
- *
- * <p>While in this state, you should call
- * {@link #setDataSource setDataSource}. It is a good
- * programming practice to register an {@link EventCallback#onCallCompleted onCallCompleted}
- * <a href="#Callbacks">callback</a> and watch for {@link #CALL_STATUS_BAD_VALUE} and
- * {@link #CALL_STATUS_ERROR_IO}, which might be caused by <code>setDataSource</code>.
- * </p>
- *
- * <p>Calling {@link #prepare()} transfers a MediaPlayer2 object to
- * the <strong>Prepared</strong> state. Note
- * that {@link #prepare()} is asynchronous. When the preparation completes,
- * if you register an {@link EventCallback#onInfo onInfo} <a href="#Callbacks">callback</a>,
- * the player executes the callback
- * with {@link #MEDIA_INFO_PREPARED} and transitions to the
- * <strong>Prepared</strong> state.</p>
- * </li>
- *
- * <li>{@link #PLAYER_STATE_PREPARED}: A MediaPlayer object must be in the
- * <strong>Prepared</strong> state before playback can be started for the first time.
- * While in this state, you can set player properties
- * such as audio/sound volume and looping by invoking the corresponding set methods.
- * Calling {@link #play()} transfers a MediaPlayer2 object to
- * the <strong>Playing</strong> state.
- * </li>
- *
- * <li>{@link #PLAYER_STATE_PLAYING}:
- * <p>The player plays the data source while in this state.
- * If you register an {@link EventCallback#onInfo onInfo} <a href="#Callbacks">callback</a>,
- * the player regularly executes the callback with
- * {@link #MEDIA_INFO_BUFFERING_UPDATE}.
- * This allows applications to keep track of the buffering status
- * while streaming audio/video.</p>
- *
- * <p> When the playback reaches the end of stream, the behavior depends on whether or
- * not you've enabled looping by calling {@link #loopCurrent}:</p>
- * <ul>
- * <li>If the looping mode was set to <code>false</code>, the player will transfer
- * to the <strong>Paused</strong> state. If you registered an {@link EventCallback#onInfo
- * onInfo} <a href="#Callbacks">callback</a>
- * the player calls the callback with {@link #MEDIA_INFO_DATA_SOURCE_END} and enters
- * the <strong>Paused</strong> state.
- * </li>
- * <li>If the looping mode was set to <code>true</code>,
- * the MediaPlayer2 object remains in the <strong>Playing</strong> state and replays its
- * data source from the beginning.</li>
- * </ul>
- * </li>
- *
- * <li>{@link #PLAYER_STATE_PAUSED}: Audio/video playback pauses while in this state.
- * Call {@link #play()} to resume playback from the position where it paused.</li>
- *
- * <li>{@link #PLAYER_STATE_ERROR}: <p>In general, playback might fail due to various
- * reasons such as unsupported audio/video format, poorly interleaved
- * audio/video, resolution too high, streaming timeout, and others.
- * In addition, due to programming errors, a playback
- * control operation might be performed from an <a href="#InvalidStates">invalid state</a>.
- * In these cases the player transitions to the <strong>Error</strong> state.</p>
- *
- * <p>If you register an {@link EventCallback#onError onError}}
- * <a href="#Callbacks">callback</a>,
- * the callback will be performed when entering the state. When programming errors happen,
- * such as calling {@link #prepare()} and
- * {@link #setDataSource} methods
- * from an <a href="#InvalidStates">invalid state</a>, the callback is called with
- * {@link #CALL_STATUS_INVALID_OPERATION}. The MediaPlayer2 object enters the
- * <strong>Error</strong> state whether or not a callback exists. </p>
- *
- * <p>To recover from an error and reuse a MediaPlayer2 object that is in the <strong>
- * Error</strong> state,
- * call {@link #reset()}. The object will return to the <strong>Idle</strong>
- * state and all state information will be lost.</p>
- * </li>
- * </ol>
- *
- * <p>You should follow these best practices when coding an app that uses MediaPlayer2:</p>
- *
- * <ul>
- *
- * <li>Use <a href="#Callbacks">callbacks</a> to respond to state changes and errors.</li>
- *
- * <li>When a MediaPlayer2 object is no longer being used, call {@link #close()} as soon as
- * possible to release the resources used by the internal player engine associated with the
- * MediaPlayer2. Failure to call {@link #close()} may cause subsequent instances of
- * MediaPlayer2 objects to fallback to software implementations or fail altogether.
- * You cannot use MediaPlayer2
- * after you call {@link #close()}. There is no way to bring it back to any other state.</li>
- *
- * <li>The current playback position can be retrieved with a call to
- * {@link #getCurrentPosition()},
- * which is helpful for applications such as a Music player that need to keep track of the playback
- * progress.</li>
- *
- * <li>The playback position can be adjusted with a call to {@link #seekTo}. Although the
- * asynchronous {@link #seekTo} call returns right away, the actual seek operation may take a
- * while to finish, especially for audio/video being streamed. If you register an
- * {@link EventCallback#onCallCompleted onCallCompleted} <a href="#Callbacks">callback</a>,
- * the callback is
- * called When the seek operation completes with {@link #CALL_COMPLETED_SEEK_TO}.</li>
- *
- * <li>You can call {@link #seekTo} from the <strong>Paused</strong> state.
- * In this case, if you are playing a video stream and
- * the requested position is valid one video frame is displayed.</li>
- *
- * </ul>
- *
- * <h3 id="InvalidStates">Invalid method calls</h3>
- *
- * <p>The only methods you safely call from the <strong>Error</strong> state are
- * {@link #close},
- * {@link #reset},
- * {@link #notifyWhenCommandLabelReached},
- * {@link #clearPendingCommands},
- * {@link #registerEventCallback},
- * {@link #unregisterEventCallback}
- * and {@link #getState}.
- * Any other methods might throw an exception, return meaningless data, or invoke a
- * {@link EventCallback#onCallCompleted onCallCompleted} with an error code.</p>
- *
- * <p>Most methods can be called from any non-Error state. They will either perform their work or
- * silently have no effect. The following table lists the methods that will invoke a
- * {@link EventCallback#onCallCompleted onCallCompleted} with an error code
- * or throw an exception when they are called from the associated invalid states.</p>
- *
- * <table border="0" cellspacing="0" cellpadding="0">
- * <tr><th>Method Name</th>
- * <th>Invalid States</th></tr>
- *
- * <tr><td>setDataSource</td> <td>{Prepared, Paused, Playing}</td></tr>
- * <tr><td>prepare</td> <td>{Prepared, Paused, Playing}</td></tr>
- * <tr><td>play</td> <td>{Idle}</td></tr>
- * <tr><td>pause</td> <td>{Idle}</td></tr>
- * <tr><td>seekTo</td> <td>{Idle}</td></tr>
- * <tr><td>getCurrentPosition</td> <td>{Idle}</td></tr>
- * <tr><td>getDuration</td> <td>{Idle}</td></tr>
- * <tr><td>getBufferedPosition</td> <td>{Idle}</td></tr>
- * <tr><td>getTrackInfo</td> <td>{Idle}</td></tr>
- * <tr><td>getSelectedTrack</td> <td>{Idle}</td></tr>
- * <tr><td>selectTrack</td> <td>{Idle}</td></tr>
- * <tr><td>deselectTrack</td> <td>{Idle}</td></tr>
- * </table>
- *
- * <h3 id="Permissions">Permissions</h3>
- * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
- * when used with network-based content.
- *
- * <h3 id="Callbacks">Callbacks</h3>
- * <p>Many errors do not result in a transition to the <strong>Error</strong> state.
- * It is good programming practice to register callback listeners using
- * {@link #registerEventCallback}.
- * You can receive a callback at any time and from any state.</p>
- *
- * <p>If it's important for your app to respond to state changes (for instance, to update the
- * controls on a transport UI), you should register an
- * {@link EventCallback#onCallCompleted onCallCompleted} and
- * detect state change commands by testing the <code>what</code> parameter for a callback from one
- * of the state transition methods: {@link #CALL_COMPLETED_PREPARE}, {@link #CALL_COMPLETED_PLAY},
- * and {@link #CALL_COMPLETED_PAUSE}.
- * Then check the <code>status</code> parameter. The value {@link #CALL_STATUS_NO_ERROR} indicates a
- * successful transition. Any other value will be an error. Call {@link #getState()} to
- * determine the current state. </p>
- *
- * @hide
- */
-public class MediaPlayer2 implements AutoCloseable, AudioRouting {
- static {
- System.loadLibrary("media2_jni");
- native_init();
- }
-
- private static native void native_init();
-
- private static final int NEXT_SOURCE_STATE_ERROR = -1;
- private static final int NEXT_SOURCE_STATE_INIT = 0;
- private static final int NEXT_SOURCE_STATE_PREPARING = 1;
- private static final int NEXT_SOURCE_STATE_PREPARED = 2;
-
- private static final String TAG = "MediaPlayer2";
-
- private Context mContext;
-
- private long mNativeContext; // accessed by native methods
- private long mNativeSurfaceTexture; // accessed by native methods
- private int mListenerContext; // accessed by native methods
- private SurfaceHolder mSurfaceHolder;
- private PowerManager.WakeLock mWakeLock = null;
- private boolean mScreenOnWhilePlaying;
- private boolean mStayAwake;
-
- private final Object mSrcLock = new Object();
- //--- guarded by |mSrcLock| start
- private SourceInfo mCurrentSourceInfo;
- private final Queue<SourceInfo> mNextSourceInfos = new ConcurrentLinkedQueue<>();
- //--- guarded by |mSrcLock| end
- private final AtomicLong mSrcIdGenerator = new AtomicLong(0);
-
- private volatile float mVolume = 1.0f;
- private Size mVideoSize = new Size(0, 0);
-
- private static ExecutorService sDrmThreadPool = Executors.newCachedThreadPool();
-
- // Creating a dummy audio track, used for keeping session id alive
- private final Object mSessionIdLock = new Object();
- @GuardedBy("mSessionIdLock")
- private AudioTrack mDummyAudioTrack;
-
- private HandlerThread mHandlerThread;
- private final TaskHandler mTaskHandler;
- private final Object mTaskLock = new Object();
- @GuardedBy("mTaskLock")
- private final List<Task> mPendingTasks = new LinkedList<>();
- @GuardedBy("mTaskLock")
- private Task mCurrentTask;
- private final AtomicLong mTaskIdGenerator = new AtomicLong(0);
-
- @GuardedBy("mTaskLock")
- boolean mIsPreviousCommandSeekTo = false;
- // |mPreviousSeekPos| and |mPreviousSeekMode| are valid only when |mIsPreviousCommandSeekTo|
- // is true, and they are accessed on |mHandlerThread| only.
- long mPreviousSeekPos = -1;
- int mPreviousSeekMode = SEEK_PREVIOUS_SYNC;
-
- @GuardedBy("this")
- private boolean mReleased;
-
- private final CloseGuard mGuard = CloseGuard.get();
-
- /**
- * Default constructor.
- * <p>When done with the MediaPlayer2, you should call {@link #close()},
- * to free the resources. If not released, too many MediaPlayer2 instances may
- * result in an exception.</p>
- */
- public MediaPlayer2(@NonNull Context context) {
- mGuard.open("close");
-
- mContext = context;
- mHandlerThread = new HandlerThread("MediaPlayer2TaskThread");
- mHandlerThread.start();
- Looper looper = mHandlerThread.getLooper();
- mTaskHandler = new TaskHandler(this, looper);
- AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
- int sessionId = am.generateAudioSessionId();
- keepAudioSessionIdAlive(sessionId);
-
- /* Native setup requires a weak reference to our object.
- * It's easier to create it here than in C++.
- */
- native_setup(sessionId, new WeakReference<MediaPlayer2>(this));
- }
-
- private native void native_setup(int sessionId, Object mediaplayer2This);
-
- /**
- * Releases the resources held by this {@code MediaPlayer2} object.
- *
- * It is considered good practice to call this method when you're
- * done using the MediaPlayer2. In particular, whenever an Activity
- * of an application is paused (its onPause() method is called),
- * or stopped (its onStop() method is called), this method should be
- * invoked to release the MediaPlayer2 object, unless the application
- * has a special need to keep the object around. In addition to
- * unnecessary resources (such as memory and instances of codecs)
- * being held, failure to call this method immediately if a
- * MediaPlayer2 object is no longer needed may also lead to
- * continuous battery consumption for mobile devices, and playback
- * failure for other applications if no multiple instances of the
- * same codec are supported on a device. Even if multiple instances
- * of the same codec are supported, some performance degradation
- * may be expected when unnecessary multiple instances are used
- * at the same time.
- *
- * {@code close()} may be safely called after a prior {@code close()}.
- * This class implements the Java {@code AutoCloseable} interface and
- * may be used with try-with-resources.
- */
- // This is a synchronous call.
- @Override
- public void close() {
- synchronized (mGuard) {
- mGuard.close();
- }
- release();
- }
-
- private synchronized void release() {
- if (mReleased) {
- return;
- }
- stayAwake(false);
- updateSurfaceScreenOn();
- synchronized (mEventCbLock) {
- mEventCallbackRecords.clear();
- }
- if (mHandlerThread != null) {
- mHandlerThread.quitSafely();
- mHandlerThread = null;
- }
-
- clearSourceInfos();
-
- // Modular DRM clean up
- synchronized (mDrmEventCallbackLock) {
- mDrmEventCallback = null;
- }
- clearMediaDrmObjects();
-
- native_release();
-
- synchronized (mSessionIdLock) {
- mDummyAudioTrack.release();
- }
-
- mReleased = true;
- }
-
- void clearMediaDrmObjects() {
- Collection<MediaDrm> drmObjs = mDrmObjs.values();
- synchronized (mDrmObjs) {
- for (MediaDrm drmObj : drmObjs) {
- drmObj.close();
- }
- mDrmObjs.clear();
- }
- }
-
- private native void native_release();
-
- // Have to declare protected for finalize() since it is protected
- // in the base class Object.
- @Override
- protected void finalize() throws Throwable {
- if (mGuard != null) {
- mGuard.warnIfOpen();
- }
-
- close();
- native_finalize();
- }
-
- private native void native_finalize();
-
- /**
- * Resets the MediaPlayer2 to its uninitialized state. After calling
- * this method, you will have to initialize it again by setting the
- * data source and calling prepare().
- */
- // This is a synchronous call.
- public void reset() {
- clearSourceInfos();
- clearMediaDrmObjects();
-
- stayAwake(false);
- native_reset();
-
- AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
- int sessionId = am.generateAudioSessionId();
- keepAudioSessionIdAlive(sessionId);
-
- // make sure none of the listeners get called anymore
- if (mTaskHandler != null) {
- mTaskHandler.removeCallbacksAndMessages(null);
- }
-
- }
-
- private native void native_reset();
-
- /**
- * Starts or resumes playback. If playback had previously been paused,
- * playback will continue from where it was paused. If playback had
- * reached end of stream and been paused, or never started before,
- * playback will start at the beginning.
- *
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object play() {
- return addTask(new Task(CALL_COMPLETED_PLAY, false) {
- @Override
- void process() {
- stayAwake(true);
- native_start();
- }
- });
- }
-
- private native void native_start() throws IllegalStateException;
-
- /**
- * Prepares the player for playback, asynchronously.
- *
- * After setting the datasource and the display surface, you need to call prepare().
- *
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object prepare() {
- return addTask(new Task(CALL_COMPLETED_PREPARE, true) {
- @Override
- void process() {
- native_prepare();
- }
- });
- }
-
- private native void native_prepare();
-
- /**
- * Pauses playback. Call play() to resume.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object pause() {
- return addTask(new Task(CALL_COMPLETED_PAUSE, false) {
- @Override
- void process() {
- stayAwake(false);
-
- native_pause();
- }
- });
- }
-
- private native void native_pause() throws IllegalStateException;
-
- /**
- * Tries to play next data source if applicable.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object skipToNext() {
- return addTask(new Task(CALL_COMPLETED_SKIP_TO_NEXT, false) {
- @Override
- void process() {
- if (getState() == PLAYER_STATE_PLAYING) {
- native_pause();
- }
- playNextDataSource();
- }
- });
- }
-
- /**
- * Gets the current playback position.
- *
- * @return the current position in milliseconds
- */
- public native long getCurrentPosition();
-
- /**
- * Gets the duration of the current data source.
- * Same as {@link #getDuration(DataSourceDesc)} with
- * {@code dsd = getCurrentDataSource()}.
- *
- * @return the duration in milliseconds, if no duration is available
- * (for example, if streaming live content), -1 is returned.
- * @throws NullPointerException if current data source is null
- */
- public long getDuration() {
- return getDuration(getCurrentDataSource());
- }
-
- /**
- * Gets the duration of the dsd.
- *
- * @param dsd the descriptor of data source of which you want to get duration
- * @return the duration in milliseconds, if no duration is available
- * (for example, if streaming live content), -1 is returned.
- * @throws NullPointerException if dsd is null
- */
- public long getDuration(@NonNull DataSourceDesc dsd) {
- if (dsd == null) {
- throw new NullPointerException("non-null dsd is expected");
- }
- SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo == null) {
- return -1;
- }
-
- return native_getDuration(sourceInfo.mId);
- }
-
- private native long native_getDuration(long srcId);
-
- /**
- * Gets the buffered media source position of current data source.
- * Same as {@link #getBufferedPosition(DataSourceDesc)} with
- * {@code dsd = getCurrentDataSource()}.
- *
- * @return the current buffered media source position in milliseconds
- * @throws NullPointerException if current data source is null
- */
- public long getBufferedPosition() {
- return getBufferedPosition(getCurrentDataSource());
- }
-
- /**
- * Gets the buffered media source position of given dsd.
- * For example a buffering update of 8000 milliseconds when 5000 milliseconds of the content
- * has already been played indicates that the next 3000 milliseconds of the
- * content to play has been buffered.
- *
- * @param dsd the descriptor of data source of which you want to get buffered position
- * @return the current buffered media source position in milliseconds
- * @throws NullPointerException if dsd is null
- */
- public long getBufferedPosition(@NonNull DataSourceDesc dsd) {
- if (dsd == null) {
- throw new NullPointerException("non-null dsd is expected");
- }
- SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo == null) {
- return 0;
- }
-
- // Use cached buffered percent for now.
- int bufferedPercentage = sourceInfo.mBufferedPercentage.get();
-
- long duration = getDuration(dsd);
- if (duration < 0) {
- duration = 0;
- }
-
- return duration * bufferedPercentage / 100;
- }
-
- /**
- * MediaPlayer2 has not been prepared or just has been reset.
- * In this state, MediaPlayer2 doesn't fetch data.
- */
- public static final int PLAYER_STATE_IDLE = 1001;
-
- /**
- * MediaPlayer2 has been just prepared.
- * In this state, MediaPlayer2 just fetches data from media source,
- * but doesn't actively render data.
- */
- public static final int PLAYER_STATE_PREPARED = 1002;
-
- /**
- * MediaPlayer2 is paused.
- * In this state, MediaPlayer2 has allocated resources to construct playback
- * pipeline, but it doesn't actively render data.
- */
- public static final int PLAYER_STATE_PAUSED = 1003;
-
- /**
- * MediaPlayer2 is actively playing back data.
- */
- public static final int PLAYER_STATE_PLAYING = 1004;
-
- /**
- * MediaPlayer2 has hit some fatal error and cannot continue playback.
- */
- public static final int PLAYER_STATE_ERROR = 1005;
-
- /**
- * @hide
- */
- @IntDef(flag = false, prefix = "MEDIAPLAYER2_STATE", value = {
- PLAYER_STATE_IDLE,
- PLAYER_STATE_PREPARED,
- PLAYER_STATE_PAUSED,
- PLAYER_STATE_PLAYING,
- PLAYER_STATE_ERROR })
- @Retention(RetentionPolicy.SOURCE)
- public @interface MediaPlayer2State {}
-
- /**
- * Gets the current player state.
- *
- * @return the current player state.
- */
- public @MediaPlayer2State int getState() {
- return native_getState();
- }
-
- private native int native_getState();
-
- /**
- * Sets the audio attributes for this MediaPlayer2.
- * See {@link AudioAttributes} for how to build and configure an instance of this class.
- * You must call this method before {@link #play()} and {@link #pause()} in order
- * for the audio attributes to become effective thereafter.
- * @param attributes a non-null set of audio attributes
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setAudioAttributes(@NonNull AudioAttributes attributes) {
- return addTask(new Task(CALL_COMPLETED_SET_AUDIO_ATTRIBUTES, false) {
- @Override
- void process() {
- if (attributes == null) {
- final String msg = "Cannot set AudioAttributes to null";
- throw new IllegalArgumentException(msg);
- }
- native_setAudioAttributes(attributes);
- }
- });
- }
-
- // return true if the parameter is set successfully, false otherwise
- private native boolean native_setAudioAttributes(AudioAttributes audioAttributes);
-
- /**
- * Gets the audio attributes for this MediaPlayer2.
- * @return attributes a set of audio attributes
- */
- public @NonNull AudioAttributes getAudioAttributes() {
- return native_getAudioAttributes();
- }
-
- private native AudioAttributes native_getAudioAttributes();
-
- /**
- * Sets the data source as described by a DataSourceDesc.
- * When the data source is of {@link FileDataSourceDesc} type, the {@link ParcelFileDescriptor}
- * in the {@link FileDataSourceDesc} will be closed by the player.
- *
- * @param dsd the descriptor of data source you want to play
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setDataSource(@NonNull DataSourceDesc dsd) {
- return addTask(new Task(CALL_COMPLETED_SET_DATA_SOURCE, false) {
- @Override
- void process() throws IOException {
- checkDataSourceDesc(dsd);
- int state = getState();
- try {
- if (state != PLAYER_STATE_ERROR && state != PLAYER_STATE_IDLE) {
- throw new IllegalStateException("called in wrong state " + state);
- }
-
- synchronized (mSrcLock) {
- setCurrentSourceInfo_l(new SourceInfo(dsd));
- handleDataSource(true /* isCurrent */, dsd, mCurrentSourceInfo.mId);
- }
- } finally {
- dsd.close();
- }
- }
-
- });
- }
-
- /**
- * Sets a single data source as described by a DataSourceDesc which will be played
- * after current data source is finished.
- * When the data source is of {@link FileDataSourceDesc} type, the {@link ParcelFileDescriptor}
- * in the {@link FileDataSourceDesc} will be closed by the player.
- *
- * @param dsd the descriptor of data source you want to play after current one
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setNextDataSource(@NonNull DataSourceDesc dsd) {
- return addTask(new Task(CALL_COMPLETED_SET_NEXT_DATA_SOURCE, false) {
- @Override
- void process() {
- checkDataSourceDesc(dsd);
- synchronized (mSrcLock) {
- clearNextSourceInfos_l();
- mNextSourceInfos.add(new SourceInfo(dsd));
- }
- prepareNextDataSource();
- }
- });
- }
-
- /**
- * Sets a list of data sources to be played sequentially after current data source is done.
- * When the data source is of {@link FileDataSourceDesc} type, the {@link ParcelFileDescriptor}
- * in the {@link FileDataSourceDesc} will be closed by the player.
- *
- * @param dsds the list of data sources you want to play after current one
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setNextDataSources(@NonNull List<DataSourceDesc> dsds) {
- return addTask(new Task(CALL_COMPLETED_SET_NEXT_DATA_SOURCES, false) {
- @Override
- void process() {
- if (dsds == null || dsds.size() == 0) {
- throw new IllegalArgumentException("data source list cannot be null or empty.");
- }
- boolean hasError = false;
- for (DataSourceDesc dsd : dsds) {
- if (dsd == null) {
- hasError = true;
- continue;
- }
- if (dsd instanceof FileDataSourceDesc) {
- FileDataSourceDesc fdsd = (FileDataSourceDesc) dsd;
- if (fdsd.isPFDClosed()) {
- hasError = true;
- continue;
- }
-
- fdsd.incCount();
- }
- }
- if (hasError) {
- for (DataSourceDesc dsd : dsds) {
- if (dsd != null) {
- dsd.close();
- }
- }
- throw new IllegalArgumentException("invalid data source list");
- }
-
- synchronized (mSrcLock) {
- clearNextSourceInfos_l();
- for (DataSourceDesc dsd : dsds) {
- mNextSourceInfos.add(new SourceInfo(dsd));
- }
- }
- prepareNextDataSource();
- }
- });
- }
-
- // throws IllegalArgumentException if dsd is null or underline PFD of dsd has been closed.
- private void checkDataSourceDesc(DataSourceDesc dsd) {
- if (dsd == null) {
- throw new IllegalArgumentException("dsd is expected to be non null");
- }
- if (dsd instanceof FileDataSourceDesc) {
- FileDataSourceDesc fdsd = (FileDataSourceDesc) dsd;
- if (fdsd.isPFDClosed()) {
- throw new IllegalArgumentException("the underline FileDescriptor has been closed");
- }
- fdsd.incCount();
- }
- }
-
- /**
- * Removes all data sources pending to be played.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object clearNextDataSources() {
- return addTask(new Task(CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES, false) {
- @Override
- void process() {
- synchronized (mSrcLock) {
- clearNextSourceInfos_l();
- }
- }
- });
- }
-
- /**
- * Gets the current data source as described by a DataSourceDesc.
- *
- * @return the current DataSourceDesc
- */
- public @Nullable DataSourceDesc getCurrentDataSource() {
- synchronized (mSrcLock) {
- return mCurrentSourceInfo == null ? null : mCurrentSourceInfo.mDSD;
- }
- }
-
- private void handleDataSource(boolean isCurrent, @NonNull DataSourceDesc dsd, long srcId)
- throws IOException {
- Media2Utils.checkArgument(dsd != null, "the DataSourceDesc cannot be null");
-
- if (dsd instanceof FileDataSourceDesc) {
- FileDataSourceDesc fileDSD = (FileDataSourceDesc) dsd;
- ParcelFileDescriptor pfd = fileDSD.getParcelFileDescriptor();
- if (pfd.getStatSize() == -1) {
- // Underlying pipeline doesn't understand '-1' size. Create a wrapper for
- // translation.
- // TODO: Make native code handle '-1' size.
- handleDataSource(isCurrent,
- srcId,
- new ProxyDataSourceCallback(pfd),
- fileDSD.getStartPosition(),
- fileDSD.getEndPosition());
- } else {
- handleDataSource(isCurrent,
- srcId,
- pfd,
- fileDSD.getOffset(),
- fileDSD.getLength(),
- fileDSD.getStartPosition(),
- fileDSD.getEndPosition());
- }
- } else if (dsd instanceof UriDataSourceDesc) {
- UriDataSourceDesc uriDSD = (UriDataSourceDesc) dsd;
- handleDataSource(isCurrent,
- srcId,
- mContext,
- uriDSD.getUri(),
- uriDSD.getHeaders(),
- uriDSD.getCookies(),
- uriDSD.getStartPosition(),
- uriDSD.getEndPosition());
- } else {
- throw new IllegalArgumentException("Unsupported DataSourceDesc. " + dsd.toString());
- }
- }
-
- /**
- * To provide cookies for the subsequent HTTP requests, you can install your own default cookie
- * handler and use other variants of setDataSource APIs instead. Alternatively, you can use
- * this API to pass the cookies as a list of HttpCookie. If the app has not installed
- * a CookieHandler already, this API creates a CookieManager and populates its CookieStore with
- * the provided cookies. If the app has installed its own handler already, this API requires the
- * handler to be of CookieManager type such that the API can update the manager’s CookieStore.
- *
- * <p><strong>Note</strong> that the cross domain redirection is allowed by default,
- * but that can be changed with key/value pairs through the headers parameter with
- * "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value to
- * disallow or allow cross domain redirection.
- *
- * @throws IllegalArgumentException if cookies are provided and the installed handler is not
- * a CookieManager
- * @throws IllegalStateException if it is called in an invalid state
- * @throws NullPointerException if context or uri is null
- * @throws IOException if uri has a file scheme and an I/O error occurs
- */
- private void handleDataSource(
- boolean isCurrent, long srcId,
- @NonNull Context context, @NonNull Uri uri,
- @Nullable Map<String, String> headers, @Nullable List<HttpCookie> cookies,
- long startPos, long endPos)
- throws IOException {
- // The context and URI usually belong to the calling user. Get a resolver for that user.
- final ContentResolver resolver = context.getContentResolver();
- final String scheme = uri.getScheme();
- if (ContentResolver.SCHEME_FILE.equals(scheme)) {
- handleDataSource(isCurrent, srcId, uri.getPath(), null, null, startPos, endPos);
- return;
- }
-
- final int ringToneType = RingtoneManager.getDefaultType(uri);
- try {
- AssetFileDescriptor afd;
- // Try requested Uri locally first
- if (ContentResolver.SCHEME_CONTENT.equals(scheme) && ringToneType != -1) {
- afd = RingtoneManager.openDefaultRingtoneUri(context, uri);
- if (attemptDataSource(isCurrent, srcId, afd, startPos, endPos)) {
- return;
- }
- final Uri actualUri = RingtoneManager.getActualDefaultRingtoneUri(
- context, ringToneType);
- afd = resolver.openAssetFileDescriptor(actualUri, "r");
- } else {
- afd = resolver.openAssetFileDescriptor(uri, "r");
- }
- if (attemptDataSource(isCurrent, srcId, afd, startPos, endPos)) {
- return;
- }
- } catch (NullPointerException | SecurityException | IOException ex) {
- Log.w(TAG, "Couldn't open " + uri == null ? "null uri" : uri.toSafeString(), ex);
- // Fallback to media server
- }
- handleDataSource(isCurrent, srcId, uri.toString(), headers, cookies, startPos, endPos);
- }
-
- private boolean attemptDataSource(boolean isCurrent, long srcId, AssetFileDescriptor afd,
- long startPos, long endPos) throws IOException {
- try {
- if (afd.getDeclaredLength() < 0) {
- handleDataSource(isCurrent,
- srcId,
- ParcelFileDescriptor.dup(afd.getFileDescriptor()),
- 0,
- DataSourceDesc.LONG_MAX,
- startPos,
- endPos);
- } else {
- handleDataSource(isCurrent,
- srcId,
- ParcelFileDescriptor.dup(afd.getFileDescriptor()),
- afd.getStartOffset(),
- afd.getDeclaredLength(),
- startPos,
- endPos);
- }
- return true;
- } catch (NullPointerException | SecurityException | IOException ex) {
- Log.w(TAG, "Couldn't open srcId:" + srcId + ": " + ex);
- return false;
- } finally {
- if (afd != null) {
- afd.close();
- }
- }
- }
-
- private void handleDataSource(
- boolean isCurrent, long srcId,
- String path, Map<String, String> headers, List<HttpCookie> cookies,
- long startPos, long endPos)
- throws IOException {
- String[] keys = null;
- String[] values = null;
-
- if (headers != null) {
- keys = new String[headers.size()];
- values = new String[headers.size()];
-
- int i = 0;
- for (Map.Entry<String, String> entry: headers.entrySet()) {
- keys[i] = entry.getKey();
- values[i] = entry.getValue();
- ++i;
- }
- }
- handleDataSource(isCurrent, srcId, path, keys, values, cookies, startPos, endPos);
- }
-
- private void handleDataSource(boolean isCurrent, long srcId,
- String path, String[] keys, String[] values, List<HttpCookie> cookies,
- long startPos, long endPos)
- throws IOException {
- final Uri uri = Uri.parse(path);
- final String scheme = uri.getScheme();
- if ("file".equals(scheme)) {
- path = uri.getPath();
- } else if (scheme != null) {
- // handle non-file sources
- Media2Utils.storeCookies(cookies);
- nativeHandleDataSourceUrl(
- isCurrent,
- srcId,
- Media2HTTPService.createHTTPService(path),
- path,
- keys,
- values,
- startPos,
- endPos);
- return;
- }
-
- final File file = new File(path);
- if (file.exists()) {
- FileInputStream is = new FileInputStream(file);
- FileDescriptor fd = is.getFD();
- handleDataSource(isCurrent, srcId, ParcelFileDescriptor.dup(fd),
- 0, DataSourceDesc.LONG_MAX, startPos, endPos);
- is.close();
- } else {
- throw new IOException("handleDataSource failed.");
- }
- }
-
- private native void nativeHandleDataSourceUrl(
- boolean isCurrent, long srcId,
- Media2HTTPService httpService, String path, String[] keys, String[] values,
- long startPos, long endPos)
- throws IOException;
-
- /**
- * Sets the data source (FileDescriptor) to use. The FileDescriptor must be
- * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
- * to close the file descriptor. It is safe to do so as soon as this call returns.
- *
- * @throws IllegalStateException if it is called in an invalid state
- * @throws IllegalArgumentException if fd is not a valid FileDescriptor
- * @throws IOException if fd can not be read
- */
- private void handleDataSource(
- boolean isCurrent, long srcId,
- ParcelFileDescriptor pfd, long offset, long length,
- long startPos, long endPos) throws IOException {
- nativeHandleDataSourceFD(isCurrent, srcId, pfd.getFileDescriptor(), offset, length,
- startPos, endPos);
- }
-
- private native void nativeHandleDataSourceFD(boolean isCurrent, long srcId,
- FileDescriptor fd, long offset, long length,
- long startPos, long endPos) throws IOException;
-
- /**
- * @throws IllegalStateException if it is called in an invalid state
- * @throws IllegalArgumentException if dataSource is not a valid DataSourceCallback
- */
- private void handleDataSource(boolean isCurrent, long srcId, DataSourceCallback dataSource,
- long startPos, long endPos) {
- nativeHandleDataSourceCallback(isCurrent, srcId, dataSource, startPos, endPos);
- }
-
- private native void nativeHandleDataSourceCallback(
- boolean isCurrent, long srcId, DataSourceCallback dataSource,
- long startPos, long endPos);
-
- // return true if there is a next data source, false otherwise.
- // This function should be always called on |mHandlerThread|.
- private boolean prepareNextDataSource() {
- HandlerThread handlerThread = mHandlerThread;
- if (handlerThread != null && Looper.myLooper() != handlerThread.getLooper()) {
- Log.e(TAG, "prepareNextDataSource: called on wrong looper");
- }
-
- boolean hasNextDSD;
- int state = getState();
- synchronized (mSrcLock) {
- hasNextDSD = !mNextSourceInfos.isEmpty();
- if (state == PLAYER_STATE_ERROR || state == PLAYER_STATE_IDLE) {
- // Current source has not been prepared yet.
- return hasNextDSD;
- }
-
- SourceInfo nextSource = mNextSourceInfos.peek();
- if (!hasNextDSD || nextSource.mStateAsNextSource != NEXT_SOURCE_STATE_INIT) {
- // There is no next source or it's in preparing or prepared state.
- return hasNextDSD;
- }
-
- try {
- nextSource.mStateAsNextSource = NEXT_SOURCE_STATE_PREPARING;
- handleDataSource(false /* isCurrent */, nextSource.mDSD, nextSource.mId);
- } catch (Exception e) {
- Message msg = mTaskHandler.obtainMessage(
- MEDIA_ERROR, MEDIA_ERROR_IO, MEDIA_ERROR_UNKNOWN, null);
- mTaskHandler.handleMessage(msg, nextSource.mId);
-
- SourceInfo nextSourceInfo = mNextSourceInfos.poll();
- if (nextSource != null) {
- nextSourceInfo.close();
- }
- return prepareNextDataSource();
- }
- }
- return hasNextDSD;
- }
-
- // This function should be always called on |mHandlerThread|.
- private void playNextDataSource() {
- HandlerThread handlerThread = mHandlerThread;
- if (handlerThread != null && Looper.myLooper() != handlerThread.getLooper()) {
- Log.e(TAG, "playNextDataSource: called on wrong looper");
- }
-
- boolean hasNextDSD = false;
- synchronized (mSrcLock) {
- if (!mNextSourceInfos.isEmpty()) {
- hasNextDSD = true;
- SourceInfo nextSourceInfo = mNextSourceInfos.peek();
- if (nextSourceInfo.mStateAsNextSource == NEXT_SOURCE_STATE_PREPARED) {
- // Switch to next source only when it has been prepared.
- setCurrentSourceInfo_l(mNextSourceInfos.poll());
-
- long srcId = mCurrentSourceInfo.mId;
- try {
- nativePlayNextDataSource(srcId);
- } catch (Exception e) {
- Message msg2 = mTaskHandler.obtainMessage(
- MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
- mTaskHandler.handleMessage(msg2, srcId);
- // Keep |mNextSourcePlayPending|
- hasNextDSD = prepareNextDataSource();
- }
- if (hasNextDSD) {
- stayAwake(true);
-
- // Now a new current src is playing.
- // Wait for MEDIA_INFO_DATA_SOURCE_START to prepare next source.
- }
- } else if (nextSourceInfo.mStateAsNextSource == NEXT_SOURCE_STATE_INIT) {
- hasNextDSD = prepareNextDataSource();
- }
- }
- }
-
- if (!hasNextDSD) {
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onInfo(
- MediaPlayer2.this, null, MEDIA_INFO_DATA_SOURCE_LIST_END, 0);
- }
- });
- }
- }
-
- private native void nativePlayNextDataSource(long srcId);
-
- /**
- * Configures the player to loop on the current data source.
- * @param loop true if the current data source is meant to loop.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object loopCurrent(boolean loop) {
- return addTask(new Task(CALL_COMPLETED_LOOP_CURRENT, false) {
- @Override
- void process() {
- setLooping(loop);
- }
- });
- }
-
- private native void setLooping(boolean looping);
-
- /**
- * Sets the volume of the audio of the media to play, expressed as a linear multiplier
- * on the audio samples.
- * Note that this volume is specific to the player, and is separate from stream volume
- * used across the platform.<br>
- * A value of 0.0f indicates muting, a value of 1.0f is the nominal unattenuated and unamplified
- * gain. See {@link #getMaxPlayerVolume()} for the volume range supported by this player.
- * @param volume a value between 0.0f and {@link #getMaxPlayerVolume()}.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setPlayerVolume(float volume) {
- return addTask(new Task(CALL_COMPLETED_SET_PLAYER_VOLUME, false) {
- @Override
- void process() {
- mVolume = volume;
- native_setVolume(volume);
- }
- });
- }
-
- private native void native_setVolume(float volume);
-
- /**
- * Returns the current volume of this player.
- * Note that it does not take into account the associated stream volume.
- * @return the player volume.
- */
- public float getPlayerVolume() {
- return mVolume;
- }
-
- /**
- * @return the maximum volume that can be used in {@link #setPlayerVolume(float)}.
- */
- public float getMaxPlayerVolume() {
- return 1.0f;
- }
-
- /**
- * Insert a task in the command queue to help the client to identify whether a batch
- * of commands has been finished. When this command is processed, a notification
- * {@link EventCallback#onCommandLabelReached onCommandLabelReached} will be fired with the
- * given {@code label}.
- *
- * @see EventCallback#onCommandLabelReached
- *
- * @param label An application specific Object used to help to identify the completeness
- * of a batch of commands.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object notifyWhenCommandLabelReached(@NonNull Object label) {
- return addTask(new Task(CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED, false) {
- @Override
- void process() {
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onCommandLabelReached(
- MediaPlayer2.this, label);
- }
- });
- }
- });
- }
-
- /**
- * Sets the {@link SurfaceHolder} to use for displaying the video
- * portion of the media.
- *
- * Either a surface holder or surface must be set if a display or video sink
- * is needed. Not calling this method or {@link #setSurface(Surface)}
- * when playing back a video will result in only the audio track being played.
- * A null surface holder or surface will result in only the audio track being
- * played.
- *
- * @param sh the SurfaceHolder to use for video display
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- public @NonNull Object setDisplay(@Nullable SurfaceHolder sh) {
- return addTask(new Task(CALL_COMPLETED_SET_DISPLAY, false) {
- @Override
- void process() {
- mSurfaceHolder = sh;
- Surface surface;
- if (sh != null) {
- surface = sh.getSurface();
- } else {
- surface = null;
- }
- native_setVideoSurface(surface);
- updateSurfaceScreenOn();
- }
- });
- }
-
- /**
- * Sets the {@link Surface} to be used as the sink for the video portion of
- * the media. Setting a
- * Surface will un-set any Surface or SurfaceHolder that was previously set.
- * A null surface will result in only the audio track being played.
- *
- * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
- * returned from {@link SurfaceTexture#getTimestamp()} will have an
- * unspecified zero point. These timestamps cannot be directly compared
- * between different media sources, different instances of the same media
- * source, or multiple runs of the same program. The timestamp is normally
- * monotonically increasing and is unaffected by time-of-day adjustments,
- * but it is reset when the position is set.
- *
- * @param surface The {@link Surface} to be used for the video portion of
- * the media.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setSurface(@Nullable Surface surface) {
- return addTask(new Task(CALL_COMPLETED_SET_SURFACE, false) {
- @Override
- void process() {
- if (mScreenOnWhilePlaying && surface != null) {
- Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
- }
- mSurfaceHolder = null;
- native_setVideoSurface(surface);
- updateSurfaceScreenOn();
- }
- });
- }
-
- private native void native_setVideoSurface(Surface surface);
-
- /**
- * Set the low-level power management behavior for this MediaPlayer2. This
- * can be used when the MediaPlayer2 is not playing through a SurfaceHolder
- * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
- * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
- *
- * <p>This function has the MediaPlayer2 access the low-level power manager
- * service to control the device's power usage while playing is occurring.
- * The parameter is a {@link android.os.PowerManager.WakeLock}.
- * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
- * permission.
- * By default, no attempt is made to keep the device awake during playback.
- *
- * @param wakeLock the power wake lock used during playback.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- * @see android.os.PowerManager
- */
- // This is an asynchronous call.
- public @NonNull Object setWakeLock(@NonNull PowerManager.WakeLock wakeLock) {
- return addTask(new Task(CALL_COMPLETED_SET_WAKE_LOCK, false) {
- @Override
- void process() {
- boolean wasHeld = false;
-
- if (mWakeLock != null) {
- if (mWakeLock.isHeld()) {
- wasHeld = true;
- mWakeLock.release();
- }
- }
-
- mWakeLock = wakeLock;
- if (mWakeLock != null) {
- mWakeLock.setReferenceCounted(false);
- if (wasHeld) {
- mWakeLock.acquire();
- }
- }
- }
- });
- }
-
- /**
- * Control whether we should use the attached SurfaceHolder to keep the
- * screen on while video playback is occurring. This is the preferred
- * method over {@link #setWakeLock} where possible, since it doesn't
- * require that the application have permission for low-level wake lock
- * access.
- *
- * @param screenOn Supply true to keep the screen on, false to allow it to turn off.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setScreenOnWhilePlaying(boolean screenOn) {
- return addTask(new Task(CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING, false) {
- @Override
- void process() {
- if (mScreenOnWhilePlaying != screenOn) {
- if (screenOn && mSurfaceHolder == null) {
- Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective"
- + " without a SurfaceHolder");
- }
- mScreenOnWhilePlaying = screenOn;
- updateSurfaceScreenOn();
- }
- }
- });
- }
-
- private void stayAwake(boolean awake) {
- if (mWakeLock != null) {
- if (awake && !mWakeLock.isHeld()) {
- mWakeLock.acquire();
- } else if (!awake && mWakeLock.isHeld()) {
- mWakeLock.release();
- }
- }
- mStayAwake = awake;
- updateSurfaceScreenOn();
- }
-
- private void updateSurfaceScreenOn() {
- if (mSurfaceHolder != null) {
- mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
- }
- }
-
- /**
- * Cancels a pending command.
- *
- * @param token the command to be canceled. This is the returned Object when command is issued.
- * @return {@code false} if the task could not be cancelled; {@code true} otherwise.
- * @throws IllegalArgumentException if argument token is null.
- */
- // This is a synchronous call.
- public boolean cancelCommand(@NonNull Object token) {
- if (token == null) {
- throw new IllegalArgumentException("command token should not be null");
- }
- synchronized (mTaskLock) {
- return mPendingTasks.remove(token);
- }
- }
-
- /**
- * Discards all pending commands.
- */
- // This is a synchronous call.
- public void clearPendingCommands() {
- synchronized (mTaskLock) {
- mPendingTasks.clear();
- }
- }
-
- //--------------------------------------------------------------------------
- // Explicit Routing
- //--------------------
- private AudioDeviceInfo mPreferredDevice = null;
-
- /**
- * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route
- * the output from this MediaPlayer2.
- * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio sink or source.
- * If deviceInfo is null, default routing is restored.
- * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and
- * does not correspond to a valid audio device.
- */
- // This is a synchronous call.
- @Override
- public boolean setPreferredDevice(@Nullable AudioDeviceInfo deviceInfo) {
- boolean status = native_setPreferredDevice(deviceInfo);
- if (status) {
- synchronized (this) {
- mPreferredDevice = deviceInfo;
- }
- }
- return status;
- }
-
- private native boolean native_setPreferredDevice(AudioDeviceInfo device);
-
- /**
- * Returns the selected output specified by {@link #setPreferredDevice}. Note that this
- * is not guaranteed to correspond to the actual device being used for playback.
- */
- @Override
- public @Nullable AudioDeviceInfo getPreferredDevice() {
- synchronized (this) {
- return mPreferredDevice;
- }
- }
-
- /**
- * Returns an {@link AudioDeviceInfo} identifying the current routing of this MediaPlayer2
- * Note: The query is only valid if the MediaPlayer2 is currently playing.
- * If the player is not playing, the returned device can be null or correspond to previously
- * selected device when the player was last active.
- */
- @Override
- public @Nullable native AudioDeviceInfo getRoutedDevice();
-
- /**
- * Adds an {@link AudioRouting.OnRoutingChangedListener} to receive notifications of routing
- * changes on this MediaPlayer2.
- * @param listener The {@link AudioRouting.OnRoutingChangedListener} interface to receive
- * notifications of rerouting events.
- * @param handler Specifies the {@link Handler} object for the thread on which to execute
- * the callback. If <code>null</code>, the handler on the main looper will be used.
- */
- // This is a synchronous call.
- @Override
- public void addOnRoutingChangedListener(@NonNull AudioRouting.OnRoutingChangedListener listener,
- @Nullable Handler handler) {
- if (listener == null) {
- throw new IllegalArgumentException("addOnRoutingChangedListener: listener is NULL");
- }
- RoutingDelegate routingDelegate = new RoutingDelegate(this, listener, handler);
- native_addDeviceCallback(routingDelegate);
- }
-
- private native void native_addDeviceCallback(RoutingDelegate rd);
-
- /**
- * Removes an {@link AudioRouting.OnRoutingChangedListener} which has been previously added
- * to receive rerouting notifications.
- * @param listener The previously added {@link AudioRouting.OnRoutingChangedListener} interface
- * to remove.
- */
- // This is a synchronous call.
- @Override
- public void removeOnRoutingChangedListener(
- @NonNull AudioRouting.OnRoutingChangedListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException("removeOnRoutingChangedListener: listener is NULL");
- }
- native_removeDeviceCallback(listener);
- }
-
- private native void native_removeDeviceCallback(
- AudioRouting.OnRoutingChangedListener listener);
-
- /**
- * Returns the size of the video.
- *
- * @return the size of the video. The width and height of size could be 0 if there is no video,
- * or the size has not been determined yet.
- * The {@code EventCallback} can be registered via
- * {@link #registerEventCallback(Executor, EventCallback)} to provide a
- * notification {@code EventCallback.onVideoSizeChanged} when the size
- * is available.
- */
- public @NonNull Size getVideoSize() {
- return mVideoSize;
- }
-
- /**
- * Return Metrics data about the current player.
- *
- * @return a {@link PersistableBundle} containing the set of attributes and values
- * available for the media being handled by this instance of MediaPlayer2
- * The attributes are descibed in {@link MetricsConstants}.
- *
- * Additional vendor-specific fields may also be present in the return value.
- */
- public @Nullable PersistableBundle getMetrics() {
- PersistableBundle bundle = native_getMetrics();
- return bundle;
- }
-
- private native PersistableBundle native_getMetrics();
-
- /**
- * Gets the current buffering management params used by the source component.
- * Calling it only after {@code setDataSource} has been called.
- * Each type of data source might have different set of default params.
- *
- * @return the current buffering management params used by the source component.
- * @throws IllegalStateException if the internal player engine has not been
- * initialized, or {@code setDataSource} has not been called.
- */
- // TODO: make it public when ready
- @NonNull
- native BufferingParams getBufferingParams();
-
- /**
- * Sets buffering management params.
- * The object sets its internal BufferingParams to the input, except that the input is
- * invalid or not supported.
- * Call it only after {@code setDataSource} has been called.
- * The input is a hint to MediaPlayer2.
- *
- * @param params the buffering management params.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // TODO: make it public when ready
- // This is an asynchronous call.
- @NonNull Object setBufferingParams(@NonNull BufferingParams params) {
- return addTask(new Task(CALL_COMPLETED_SET_BUFFERING_PARAMS, false) {
- @Override
- void process() {
- Media2Utils.checkArgument(params != null, "the BufferingParams cannot be null");
- native_setBufferingParams(params);
- }
- });
- }
-
- private native void native_setBufferingParams(@NonNull BufferingParams params);
-
- /**
- * Sets playback rate using {@link PlaybackParams}. The object sets its internal
- * PlaybackParams to the input. This allows the object to resume at previous speed
- * when play() is called. Speed of zero is not allowed. Calling it does not change
- * the object state.
- *
- * @param params the playback params.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setPlaybackParams(@NonNull PlaybackParams params) {
- return addTask(new Task(CALL_COMPLETED_SET_PLAYBACK_PARAMS, false) {
- @Override
- void process() {
- Media2Utils.checkArgument(params != null, "the PlaybackParams cannot be null");
- native_setPlaybackParams(params);
- }
- });
- }
-
- private native void native_setPlaybackParams(@NonNull PlaybackParams params);
-
- /**
- * Gets the playback params, containing the current playback rate.
- *
- * @return the playback params.
- * @throws IllegalStateException if the internal player engine has not been initialized.
- */
- @NonNull
- public native PlaybackParams getPlaybackParams();
-
- /**
- * Sets A/V sync mode.
- *
- * @param params the A/V sync params to apply
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setSyncParams(@NonNull SyncParams params) {
- return addTask(new Task(CALL_COMPLETED_SET_SYNC_PARAMS, false) {
- @Override
- void process() {
- Media2Utils.checkArgument(params != null, "the SyncParams cannot be null");
- native_setSyncParams(params);
- }
- });
- }
-
- private native void native_setSyncParams(@NonNull SyncParams params);
-
- /**
- * Gets the A/V sync mode.
- *
- * @return the A/V sync params
- * @throws IllegalStateException if the internal player engine has not been initialized.
- */
- @NonNull
- public native SyncParams getSyncParams();
-
- /**
- * Moves the media to specified time position.
- * Same as {@link #seekTo(long, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
- *
- * @param msec the offset in milliseconds from the start to seek to
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object seekTo(long msec) {
- return seekTo(msec, SEEK_PREVIOUS_SYNC /* mode */);
- }
-
- /**
- * Seek modes used in method seekTo(long, int) to move media position
- * to a specified location.
- *
- * Do not change these mode values without updating their counterparts
- * in include/media/IMediaSource.h!
- */
- /**
- * This mode is used with {@link #seekTo(long, int)} to move media position to
- * a sync (or key) frame associated with a data source that is located
- * right before or at the given time.
- *
- * @see #seekTo(long, int)
- */
- public static final int SEEK_PREVIOUS_SYNC = 0x00;
- /**
- * This mode is used with {@link #seekTo(long, int)} to move media position to
- * a sync (or key) frame associated with a data source that is located
- * right after or at the given time.
- *
- * @see #seekTo(long, int)
- */
- public static final int SEEK_NEXT_SYNC = 0x01;
- /**
- * This mode is used with {@link #seekTo(long, int)} to move media position to
- * a sync (or key) frame associated with a data source that is located
- * closest to (in time) or at the given time.
- *
- * @see #seekTo(long, int)
- */
- public static final int SEEK_CLOSEST_SYNC = 0x02;
- /**
- * This mode is used with {@link #seekTo(long, int)} to move media position to
- * a frame (not necessarily a key frame) associated with a data source that
- * is located closest to or at the given time.
- *
- * @see #seekTo(long, int)
- */
- public static final int SEEK_CLOSEST = 0x03;
-
- /** @hide */
- @IntDef(flag = false, prefix = "SEEK", value = {
- SEEK_PREVIOUS_SYNC,
- SEEK_NEXT_SYNC,
- SEEK_CLOSEST_SYNC,
- SEEK_CLOSEST,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SeekMode {}
-
- /**
- * Moves the media to specified time position by considering the given mode.
- * <p>
- * When seekTo is finished, the user will be notified via
- * {@link EventCallback#onCallCompleted} with {@link #CALL_COMPLETED_SEEK_TO}.
- * There is at most one active seekTo processed at any time. If there is a to-be-completed
- * seekTo, new seekTo requests will be queued in such a way that only the last request
- * is kept. When current seekTo is completed, the queued request will be processed if
- * that request is different from just-finished seekTo operation, i.e., the requested
- * position or mode is different.
- *
- * @param msec the offset in milliseconds from the start to seek to.
- * When seeking to the given time position, there is no guarantee that the data source
- * has a frame located at the position. When this happens, a frame nearby will be rendered.
- * If msec is negative, time position zero will be used.
- * If msec is larger than duration, duration will be used.
- * @param mode the mode indicating where exactly to seek to.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object seekTo(long msec, @SeekMode int mode) {
- return addTask(new Task(CALL_COMPLETED_SEEK_TO, true) {
- @Override
- void process() {
- if (mode < SEEK_PREVIOUS_SYNC || mode > SEEK_CLOSEST) {
- final String msg = "Illegal seek mode: " + mode;
- throw new IllegalArgumentException(msg);
- }
- // TODO: pass long to native, instead of truncating here.
- long posMs = msec;
- if (posMs > Integer.MAX_VALUE) {
- Log.w(TAG, "seekTo offset " + posMs + " is too large, cap to "
- + Integer.MAX_VALUE);
- posMs = Integer.MAX_VALUE;
- } else if (posMs < Integer.MIN_VALUE) {
- Log.w(TAG, "seekTo offset " + posMs + " is too small, cap to "
- + Integer.MIN_VALUE);
- posMs = Integer.MIN_VALUE;
- }
-
- synchronized (mTaskLock) {
- if (mIsPreviousCommandSeekTo
- && mPreviousSeekPos == posMs
- && mPreviousSeekMode == mode) {
- throw new CommandSkippedException(
- "same as previous seekTo");
- }
- }
-
- native_seekTo(posMs, mode);
-
- synchronized (mTaskLock) {
- mIsPreviousCommandSeekTo = true;
- mPreviousSeekPos = posMs;
- mPreviousSeekMode = mode;
- }
- }
- });
- }
-
- private native void native_seekTo(long msec, int mode);
-
- /**
- * Get current playback position as a {@link MediaTimestamp}.
- * <p>
- * The MediaTimestamp represents how the media time correlates to the system time in
- * a linear fashion using an anchor and a clock rate. During regular playback, the media
- * time moves fairly constantly (though the anchor frame may be rebased to a current
- * system time, the linear correlation stays steady). Therefore, this method does not
- * need to be called often.
- * <p>
- * To help users get current playback position, this method always anchors the timestamp
- * to the current {@link System#nanoTime system time}, so
- * {@link MediaTimestamp#getAnchorMediaTimeUs} can be used as current playback position.
- *
- * @return a MediaTimestamp object if a timestamp is available, or {@code null} if no timestamp
- * is available, e.g. because the media player has not been initialized.
- *
- * @see MediaTimestamp
- */
- @Nullable
- public MediaTimestamp getTimestamp() {
- try {
- // TODO: get the timestamp from native side
- return new MediaTimestamp(
- getCurrentPosition() * 1000L,
- System.nanoTime(),
- getState() == PLAYER_STATE_PLAYING ? getPlaybackParams().getSpeed() : 0.f);
- } catch (IllegalStateException e) {
- return null;
- }
- }
-
- /**
- * Checks whether the MediaPlayer2 is looping or non-looping.
- *
- * @return true if the MediaPlayer2 is currently looping, false otherwise
- */
- // This is a synchronous call.
- public native boolean isLooping();
-
- /**
- * Sets the audio session ID.
- *
- * @param sessionId the audio session ID.
- * The audio session ID is a system wide unique identifier for the audio stream played by
- * this MediaPlayer2 instance.
- * The primary use of the audio session ID is to associate audio effects to a particular
- * instance of MediaPlayer2: if an audio session ID is provided when creating an audio effect,
- * this effect will be applied only to the audio content of media players within the same
- * audio session and not to the output mix.
- * When created, a MediaPlayer2 instance automatically generates its own audio session ID.
- * However, it is possible to force this player to be part of an already existing audio session
- * by calling this method.
- * This method must be called when player is in {@link #PLAYER_STATE_IDLE} or
- * {@link #PLAYER_STATE_PREPARED} state in order to have sessionId take effect.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setAudioSessionId(int sessionId) {
- final AudioTrack dummyAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
- AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 2,
- AudioTrack.MODE_STATIC, sessionId);
- return addTask(new Task(CALL_COMPLETED_SET_AUDIO_SESSION_ID, false) {
- @Override
- void process() {
- keepAudioSessionIdAlive(dummyAudioTrack);
- native_setAudioSessionId(sessionId);
- }
- });
- }
-
- private native void native_setAudioSessionId(int sessionId);
-
- /**
- * Returns the audio session ID.
- *
- * @return the audio session ID. {@see #setAudioSessionId(int)}
- * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer2 was
- * contructed.
- */
- // This is a synchronous call.
- public native int getAudioSessionId();
-
- /**
- * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
- * effect which can be applied on any sound source that directs a certain amount of its
- * energy to this effect. This amount is defined by setAuxEffectSendLevel().
- * See {@link #setAuxEffectSendLevel(float)}.
- * <p>After creating an auxiliary effect (e.g.
- * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
- * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
- * to attach the player to the effect.
- * <p>To detach the effect from the player, call this method with a null effect id.
- * <p>This method must be called after one of the overloaded <code> setDataSource </code>
- * methods.
- * @param effectId system wide unique id of the effect to attach
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object attachAuxEffect(int effectId) {
- return addTask(new Task(CALL_COMPLETED_ATTACH_AUX_EFFECT, false) {
- @Override
- void process() {
- native_attachAuxEffect(effectId);
- }
- });
- }
-
- private native void native_attachAuxEffect(int effectId);
-
- /**
- * Sets the send level of the player to the attached auxiliary effect.
- * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
- * <p>By default the send level is 0, so even if an effect is attached to the player
- * this method must be called for the effect to be applied.
- * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
- * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
- * so an appropriate conversion from linear UI input x to level is:
- * x == 0 -> level = 0
- * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
- * @param level send level scalar
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- */
- // This is an asynchronous call.
- public @NonNull Object setAuxEffectSendLevel(float level) {
- return addTask(new Task(CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL, false) {
- @Override
- void process() {
- native_setAuxEffectSendLevel(level);
- }
- });
- }
-
- private native void native_setAuxEffectSendLevel(float level);
-
- private static native void native_stream_event_onTearDown(
- long nativeCallbackPtr, long userDataPtr);
- private static native void native_stream_event_onStreamPresentationEnd(
- long nativeCallbackPtr, long userDataPtr);
- private static native void native_stream_event_onStreamDataRequest(
- long jAudioTrackPtr, long nativeCallbackPtr, long userDataPtr);
-
- /* Do not change these values (starting with INVOKE_ID) without updating
- * their counterparts in include/media/mediaplayer2.h!
- */
- private static final int INVOKE_ID_GET_TRACK_INFO = 1;
- private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
- private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
- private static final int INVOKE_ID_SELECT_TRACK = 4;
- private static final int INVOKE_ID_DESELECT_TRACK = 5;
- private static final int INVOKE_ID_GET_SELECTED_TRACK = 7;
-
- /**
- * Invoke a generic method on the native player using opaque protocol
- * buffer message for the request and reply. Both payloads' format is a
- * convention between the java caller and the native player.
- *
- * @param msg PlayerMessage for the extension.
- *
- * @return PlayerMessage with the data returned by the
- * native player.
- */
- private PlayerMessage invoke(PlayerMessage msg) {
- byte[] ret = native_invoke(msg.toByteArray());
- if (ret == null) {
- return null;
- }
- try {
- return PlayerMessage.parseFrom(ret);
- } catch (InvalidProtocolBufferException e) {
- return null;
- }
- }
-
- private native byte[] native_invoke(byte[] request);
-
- /**
- * @hide
- */
- @IntDef(flag = false, prefix = "MEDIA_TRACK_TYPE", value = {
- TrackInfo.MEDIA_TRACK_TYPE_VIDEO,
- TrackInfo.MEDIA_TRACK_TYPE_AUDIO,
- TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface TrackType {}
-
- /**
- * Class for MediaPlayer2 to return each audio/video/subtitle track's metadata.
- *
- * @see MediaPlayer2#getTrackInfo
- */
- public static class TrackInfo {
- /**
- * Gets the track type.
- * @return TrackType which indicates if the track is video, audio, timed text.
- */
- public int getTrackType() {
- return mTrackType;
- }
-
- /**
- * Gets the language code of the track.
- * @return a language code in either way of ISO-639-1 or ISO-639-2.
- * When the language is unknown or could not be determined,
- * ISO-639-2 language code, "und", is returned.
- */
- public @NonNull String getLanguage() {
- String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
- return language == null ? "und" : language;
- }
-
- /**
- * Gets the {@link MediaFormat} of the track. If the format is
- * unknown or could not be determined, null is returned.
- */
- public @Nullable MediaFormat getFormat() {
- if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
- || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
- return mFormat;
- }
- return null;
- }
-
- public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
- public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
- public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
-
- /** @hide */
- public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
-
- public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
- public static final int MEDIA_TRACK_TYPE_METADATA = 5;
-
- final int mId;
- final int mTrackType;
- final MediaFormat mFormat;
-
- static TrackInfo create(int idx, Iterator<Value> in) {
- int trackType = in.next().getInt32Value();
- // TODO: build the full MediaFormat; currently we are using createSubtitleFormat
- // even for audio/video tracks, meaning we only set the mime and language.
- String mime = in.next().getStringValue();
- String language = in.next().getStringValue();
- MediaFormat format = MediaFormat.createSubtitleFormat(mime, language);
-
- if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
- format.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.next().getInt32Value());
- format.setInteger(MediaFormat.KEY_IS_DEFAULT, in.next().getInt32Value());
- format.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.next().getInt32Value());
- }
- return new TrackInfo(idx, trackType, format);
- }
-
- /** @hide */
- TrackInfo(int id, int type, MediaFormat format) {
- mId = id;
- mTrackType = type;
- mFormat = format;
- }
-
- @Override
- public String toString() {
- StringBuilder out = new StringBuilder(128);
- out.append(getClass().getName());
- out.append('{');
- switch (mTrackType) {
- case MEDIA_TRACK_TYPE_VIDEO:
- out.append("VIDEO");
- break;
- case MEDIA_TRACK_TYPE_AUDIO:
- out.append("AUDIO");
- break;
- case MEDIA_TRACK_TYPE_TIMEDTEXT:
- out.append("TIMEDTEXT");
- break;
- case MEDIA_TRACK_TYPE_SUBTITLE:
- out.append("SUBTITLE");
- break;
- default:
- out.append("UNKNOWN");
- break;
- }
- out.append(", " + mFormat.toString());
- out.append("}");
- return out.toString();
- }
- };
-
- /**
- * Returns a List of track information of current data source.
- * Same as {@link #getTrackInfo(DataSourceDesc)} with
- * {@code dsd = getCurrentDataSource()}.
- *
- * @return List of track info. The total number of tracks is the array length.
- * Must be called again if an external timed text source has been added after
- * addTimedTextSource method is called.
- * @throws IllegalStateException if it is called in an invalid state.
- * @throws NullPointerException if current data source is null
- */
- public @NonNull List<TrackInfo> getTrackInfo() {
- return getTrackInfo(getCurrentDataSource());
- }
-
- /**
- * Returns a List of track information.
- *
- * @param dsd the descriptor of data source of which you want to get track info
- * @return List of track info. The total number of tracks is the array length.
- * Must be called again if an external timed text source has been added after
- * addTimedTextSource method is called.
- * @throws IllegalStateException if it is called in an invalid state.
- * @throws NullPointerException if dsd is null
- */
- public @NonNull List<TrackInfo> getTrackInfo(@NonNull DataSourceDesc dsd) {
- if (dsd == null) {
- throw new NullPointerException("non-null dsd is expected");
- }
- SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo == null) {
- return new ArrayList<TrackInfo>(0);
- }
-
- TrackInfo[] trackInfo = getInbandTrackInfo(sourceInfo);
- return (trackInfo != null ? Arrays.asList(trackInfo) : new ArrayList<TrackInfo>(0));
- }
-
- private TrackInfo[] getInbandTrackInfo(SourceInfo sourceInfo) throws IllegalStateException {
- PlayerMessage request = PlayerMessage.newBuilder()
- .addValues(Value.newBuilder().setInt32Value(INVOKE_ID_GET_TRACK_INFO))
- .addValues(Value.newBuilder().setInt64Value(sourceInfo.mId))
- .build();
- PlayerMessage response = invoke(request);
- if (response == null) {
- return null;
- }
- Iterator<Value> in = response.getValuesList().iterator();
- int size = in.next().getInt32Value();
- if (size == 0) {
- return null;
- }
- TrackInfo[] trackInfo = new TrackInfo[size];
- for (int i = 0; i < size; ++i) {
- trackInfo[i] = TrackInfo.create(i, in);
- }
- return trackInfo;
- }
-
- /**
- * Returns the index of the audio, video, or subtitle track currently selected for playback.
- * The return value is an index into the array returned by {@link #getTrackInfo}, and can
- * be used in calls to {@link #selectTrack(TrackInfo)} or {@link #deselectTrack(TrackInfo)}.
- * Same as {@link #getSelectedTrack(DataSourceDesc, int)} with
- * {@code dsd = getCurrentDataSource()}.
- *
- * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
- * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
- * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
- * @return metadata corresponding to the audio, video, or subtitle track currently selected for
- * playback; {@code null} is returned when there is no selected track for {@code trackType} or
- * when {@code trackType} is not one of audio, video, or subtitle.
- * @throws IllegalStateException if called after {@link #close()}
- * @throws NullPointerException if current data source is null
- *
- * @see #getTrackInfo()
- * @see #selectTrack(TrackInfo)
- * @see #deselectTrack(TrackInfo)
- */
- @Nullable
- public TrackInfo getSelectedTrack(@TrackType int trackType) {
- return getSelectedTrack(getCurrentDataSource(), trackType);
- }
-
- /**
- * Returns the index of the audio, video, or subtitle track currently selected for playback.
- * The return value is an index into the array returned by {@link #getTrackInfo}, and can
- * be used in calls to {@link #selectTrack(DataSourceDesc, TrackInfo)} or
- * {@link #deselectTrack(DataSourceDesc, TrackInfo)}.
- *
- * @param dsd the descriptor of data source of which you want to get selected track
- * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
- * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
- * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
- * @return metadata corresponding to the audio, video, or subtitle track currently selected for
- * playback; {@code null} is returned when there is no selected track for {@code trackType} or
- * when {@code trackType} is not one of audio, video, or subtitle.
- * @throws IllegalStateException if called after {@link #close()}
- * @throws NullPointerException if dsd is null
- *
- * @see #getTrackInfo(DataSourceDesc)
- * @see #selectTrack(DataSourceDesc, TrackInfo)
- * @see #deselectTrack(DataSourceDesc, TrackInfo)
- */
- @Nullable
- public TrackInfo getSelectedTrack(@NonNull DataSourceDesc dsd, @TrackType int trackType) {
- if (dsd == null) {
- throw new NullPointerException("non-null dsd is expected");
- }
- SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo == null) {
- return null;
- }
-
- PlayerMessage request = PlayerMessage.newBuilder()
- .addValues(Value.newBuilder().setInt32Value(INVOKE_ID_GET_SELECTED_TRACK))
- .addValues(Value.newBuilder().setInt64Value(sourceInfo.mId))
- .addValues(Value.newBuilder().setInt32Value(trackType))
- .build();
- PlayerMessage response = invoke(request);
- if (response == null) {
- return null;
- }
- // TODO: return full TrackInfo data from native player instead of index
- final int idx = response.getValues(0).getInt32Value();
- final List<TrackInfo> trackInfos = getTrackInfo(dsd);
- return trackInfos.isEmpty() ? null : trackInfos.get(idx);
- }
-
- /**
- * Selects a track of current data source.
- * Same as {@link #selectTrack(DataSourceDesc, TrackInfo)} with
- * {@code dsd = getCurrentDataSource()}.
- *
- * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
- * object can be obtained from {@link #getTrackInfo()}.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- *
- * This is an asynchronous call.
- *
- * @see MediaPlayer2#getTrackInfo()
- */
- @NonNull
- public Object selectTrack(@NonNull TrackInfo trackInfo) {
- return selectTrack(getCurrentDataSource(), trackInfo);
- }
-
- /**
- * Selects a track.
- * <p>
- * If a MediaPlayer2 is in invalid state, it throws an IllegalStateException exception.
- * If a MediaPlayer2 is in <em>Started</em> state, the selected track is presented immediately.
- * If a MediaPlayer2 is not in Started state, it just marks the track to be played.
- * </p>
- * <p>
- * In any valid state, if it is called multiple times on the same type of track (ie. Video,
- * Audio, Timed Text), the most recent one will be chosen.
- * </p>
- * <p>
- * The first audio and video tracks are selected by default if available, even though
- * this method is not called. However, no timed text track will be selected until
- * this function is called.
- * </p>
- * <p>
- * Currently, only timed text tracks or audio tracks can be selected via this method.
- * In addition, the support for selecting an audio track at runtime is pretty limited
- * in that an audio track can only be selected in the <em>Prepared</em> state.
- * </p>
- * @param dsd the descriptor of data source of which you want to select track
- * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
- * object can be obtained from {@link #getTrackInfo()}.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- *
- * This is an asynchronous call.
- *
- * @see MediaPlayer2#getTrackInfo(DataSourceDesc)
- */
- @NonNull
- public Object selectTrack(@NonNull DataSourceDesc dsd, @NonNull TrackInfo trackInfo) {
- return addTask(new Task(CALL_COMPLETED_SELECT_TRACK, false) {
- @Override
- void process() {
- selectOrDeselectTrack(dsd, trackInfo.mId, true /* select */);
- }
- });
- }
-
- /**
- * Deselect a track of current data source.
- * Same as {@link #deselectTrack(DataSourceDesc, TrackInfo)} with
- * {@code dsd = getCurrentDataSource()}.
- *
- * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
- * object can be obtained from {@link #getTrackInfo()}.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- *
- * This is an asynchronous call.
- *
- * @see MediaPlayer2#getTrackInfo()
- */
- @NonNull
- public Object deselectTrack(@NonNull TrackInfo trackInfo) {
- return deselectTrack(getCurrentDataSource(), trackInfo);
- }
-
- /**
- * Deselect a track.
- * <p>
- * Currently, the track must be a timed text track and no audio or video tracks can be
- * deselected. If the timed text track identified by index has not been
- * selected before, it throws an exception.
- * </p>
- * @param dsd the descriptor of data source of which you want to deselect track
- * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
- * object can be obtained from {@link #getTrackInfo()}.
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- *
- * This is an asynchronous call.
- *
- * @see MediaPlayer2#getTrackInfo(DataSourceDesc)
- */
- @NonNull
- public Object deselectTrack(@NonNull DataSourceDesc dsd, @NonNull TrackInfo trackInfo) {
- return addTask(new Task(CALL_COMPLETED_DESELECT_TRACK, false) {
- @Override
- void process() {
- selectOrDeselectTrack(dsd, trackInfo.mId, false /* select */);
- }
- });
- }
-
- private void selectOrDeselectTrack(@NonNull DataSourceDesc dsd, int index, boolean select) {
- if (dsd == null) {
- throw new IllegalArgumentException("non-null dsd is expected");
- }
- SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo == null) {
- return;
- }
-
- PlayerMessage request = PlayerMessage.newBuilder()
- .addValues(Value.newBuilder().setInt32Value(
- select ? INVOKE_ID_SELECT_TRACK : INVOKE_ID_DESELECT_TRACK))
- .addValues(Value.newBuilder().setInt64Value(sourceInfo.mId))
- .addValues(Value.newBuilder().setInt32Value(index))
- .build();
- invoke(request);
- }
-
- /* Do not change these values without updating their counterparts
- * in include/media/mediaplayer2.h!
- */
- private static final int MEDIA_NOP = 0; // interface test message
- private static final int MEDIA_PREPARED = 1;
- private static final int MEDIA_PLAYBACK_COMPLETE = 2;
- private static final int MEDIA_BUFFERING_UPDATE = 3;
- private static final int MEDIA_SEEK_COMPLETE = 4;
- private static final int MEDIA_SET_VIDEO_SIZE = 5;
- private static final int MEDIA_STARTED = 6;
- private static final int MEDIA_PAUSED = 7;
- private static final int MEDIA_STOPPED = 8;
- private static final int MEDIA_SKIPPED = 9;
- private static final int MEDIA_DRM_PREPARED = 10;
- private static final int MEDIA_NOTIFY_TIME = 98;
- private static final int MEDIA_TIMED_TEXT = 99;
- private static final int MEDIA_ERROR = 100;
- private static final int MEDIA_INFO = 200;
- private static final int MEDIA_SUBTITLE_DATA = 201;
- private static final int MEDIA_META_DATA = 202;
- private static final int MEDIA_DRM_INFO = 210;
-
- private class TaskHandler extends Handler {
- private MediaPlayer2 mMediaPlayer;
-
- TaskHandler(MediaPlayer2 mp, Looper looper) {
- super(looper);
- mMediaPlayer = mp;
- }
-
- @Override
- public void handleMessage(Message msg) {
- handleMessage(msg, 0);
- }
-
- public void handleMessage(Message msg, long srcId) {
- if (mMediaPlayer.mNativeContext == 0) {
- Log.w(TAG, "mediaplayer2 went away with unhandled events");
- return;
- }
- final int what = msg.arg1;
- final int extra = msg.arg2;
-
- final SourceInfo sourceInfo = getSourceInfo(srcId);
- if (sourceInfo == null) {
- return;
- }
- final DataSourceDesc dsd = sourceInfo.mDSD;
-
- switch(msg.what) {
- case MEDIA_PREPARED:
- case MEDIA_DRM_PREPARED:
- {
- sourceInfo.mPrepareBarrier--;
- if (sourceInfo.mPrepareBarrier > 0) {
- break;
- } else if (sourceInfo.mPrepareBarrier < 0) {
- Log.w(TAG, "duplicated (drm) prepared events");
- break;
- }
-
- if (dsd != null) {
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onInfo(
- mMediaPlayer, dsd, MEDIA_INFO_PREPARED, 0);
- }
- });
- }
-
- synchronized (mSrcLock) {
- SourceInfo nextSourceInfo = mNextSourceInfos.peek();
- Log.i(TAG, "MEDIA_PREPARED: srcId=" + srcId
- + ", curSrc=" + mCurrentSourceInfo
- + ", nextSrc=" + nextSourceInfo);
-
- if (isCurrentSource(srcId)) {
- prepareNextDataSource();
- } else if (isNextSource(srcId)) {
- nextSourceInfo.mStateAsNextSource = NEXT_SOURCE_STATE_PREPARED;
- if (nextSourceInfo.mPlayPendingAsNextSource) {
- playNextDataSource();
- }
- }
- }
-
- synchronized (mTaskLock) {
- if (mCurrentTask != null
- && mCurrentTask.mMediaCallType == CALL_COMPLETED_PREPARE
- && mCurrentTask.mDSD == dsd
- && mCurrentTask.mNeedToWaitForEventToComplete) {
- mCurrentTask.sendCompleteNotification(CALL_STATUS_NO_ERROR);
- mCurrentTask = null;
- processPendingTask_l();
- }
- }
- return;
- }
-
- case MEDIA_DRM_INFO:
- {
- if (msg.obj == null) {
- Log.w(TAG, "MEDIA_DRM_INFO msg.obj=NULL");
- } else if (msg.obj instanceof byte[]) {
- // The PlayerMessage was parsed already in postEventFromNative
-
- final DrmInfo drmInfo;
- synchronized (sourceInfo) {
- if (sourceInfo.mDrmInfo != null) {
- drmInfo = sourceInfo.mDrmInfo.makeCopy();
- } else {
- drmInfo = null;
- }
- }
-
- // notifying the client outside the lock
- DrmPreparationInfo drmPrepareInfo = null;
- if (drmInfo != null) {
- try {
- drmPrepareInfo = sendDrmEventWait(
- new DrmEventNotifier<DrmPreparationInfo>() {
- @Override
- public DrmPreparationInfo notifyWait(
- DrmEventCallback callback) {
- return callback.onDrmInfo(mMediaPlayer, dsd,
- drmInfo);
- }
- });
- } catch (InterruptedException | ExecutionException
- | TimeoutException e) {
- Log.w(TAG, "Exception while waiting for DrmPreparationInfo", e);
- }
- }
- if (sourceInfo.mDrmHandle.setPreparationInfo(drmPrepareInfo)) {
- sourceInfo.mPrepareBarrier++;
- final Task prepareDrmTask;
- prepareDrmTask = newPrepareDrmTask(dsd, drmPrepareInfo.mUUID);
- mTaskHandler.post(new Runnable() {
- @Override
- public void run() {
- // Run as simple Runnable, not Task
- try {
- prepareDrmTask.process();
- } catch (NoDrmSchemeException | IOException e) {
- final String errMsg;
- errMsg = "Unexpected Exception during prepareDrm";
- throw new RuntimeException(errMsg, e);
- }
- }
- });
- } else {
- Log.w(TAG, "No valid DrmPreparationInfo set");
- }
- } else {
- Log.w(TAG, "MEDIA_DRM_INFO msg.obj of unexpected type " + msg.obj);
- }
- return;
- }
-
- case MEDIA_PLAYBACK_COMPLETE:
- {
- if (isCurrentSource(srcId)) {
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onInfo(
- mMediaPlayer, dsd, MEDIA_INFO_DATA_SOURCE_END, 0);
- }
- });
- stayAwake(false);
-
- synchronized (mSrcLock) {
- SourceInfo nextSourceInfo = mNextSourceInfos.peek();
- if (nextSourceInfo != null) {
- nextSourceInfo.mPlayPendingAsNextSource = true;
- }
- Log.i(TAG, "MEDIA_PLAYBACK_COMPLETE: srcId=" + srcId
- + ", curSrc=" + mCurrentSourceInfo
- + ", nextSrc=" + nextSourceInfo);
- }
-
- playNextDataSource();
- }
-
- return;
- }
-
- case MEDIA_STOPPED:
- case MEDIA_STARTED:
- case MEDIA_PAUSED:
- case MEDIA_SKIPPED:
- case MEDIA_NOTIFY_TIME:
- {
- // Do nothing. The client should have enough information with
- // {@link EventCallback#onMediaTimeDiscontinuity}.
- break;
- }
-
- case MEDIA_BUFFERING_UPDATE:
- {
- final int percent = msg.arg1;
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onInfo(
- mMediaPlayer, dsd, MEDIA_INFO_BUFFERING_UPDATE, percent);
- }
- });
-
- SourceInfo src = getSourceInfo(srcId);
- if (src != null) {
- src.mBufferedPercentage.set(percent);
- }
-
- return;
- }
-
- case MEDIA_SEEK_COMPLETE:
- {
- synchronized (mTaskLock) {
- if (!mPendingTasks.isEmpty()
- && mPendingTasks.get(0).mMediaCallType != CALL_COMPLETED_SEEK_TO
- && getState() == PLAYER_STATE_PLAYING) {
- mIsPreviousCommandSeekTo = false;
- }
-
- if (mCurrentTask != null
- && mCurrentTask.mMediaCallType == CALL_COMPLETED_SEEK_TO
- && mCurrentTask.mNeedToWaitForEventToComplete) {
- mCurrentTask.sendCompleteNotification(CALL_STATUS_NO_ERROR);
- mCurrentTask = null;
- processPendingTask_l();
- }
- }
- return;
- }
-
- case MEDIA_SET_VIDEO_SIZE:
- {
- final int width = msg.arg1;
- final int height = msg.arg2;
-
- mVideoSize = new Size(width, height);
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onVideoSizeChanged(
- mMediaPlayer, dsd, mVideoSize);
- }
- });
- return;
- }
-
- case MEDIA_ERROR:
- {
- Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onError(
- mMediaPlayer, dsd, what, extra);
- }
- });
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onInfo(
- mMediaPlayer, dsd, MEDIA_INFO_DATA_SOURCE_END, 0);
- }
- });
- stayAwake(false);
- return;
- }
-
- case MEDIA_INFO:
- {
- switch (msg.arg1) {
- case MEDIA_INFO_VIDEO_TRACK_LAGGING:
- Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
- break;
- }
-
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onInfo(
- mMediaPlayer, dsd, what, extra);
- }
- });
-
- if (msg.arg1 == MEDIA_INFO_DATA_SOURCE_START) {
- if (isCurrentSource(srcId)) {
- prepareNextDataSource();
- }
- }
-
- // No real default action so far.
- return;
- }
-
- case MEDIA_TIMED_TEXT:
- {
- final TimedText text;
- if (msg.obj instanceof byte[]) {
- PlayerMessage playerMsg;
- try {
- playerMsg = PlayerMessage.parseFrom((byte[]) msg.obj);
- } catch (InvalidProtocolBufferException e) {
- Log.w(TAG, "Failed to parse timed text.", e);
- return;
- }
- text = TimedTextUtil.parsePlayerMessage(playerMsg);
- } else {
- text = null;
- }
-
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onTimedText(
- mMediaPlayer, dsd, text);
- }
- });
- return;
- }
-
- case MEDIA_SUBTITLE_DATA:
- {
- if (msg.obj instanceof byte[]) {
- PlayerMessage playerMsg;
- try {
- playerMsg = PlayerMessage.parseFrom((byte[]) msg.obj);
- } catch (InvalidProtocolBufferException e) {
- Log.w(TAG, "Failed to parse subtitle data.", e);
- return;
- }
- Iterator<Value> in = playerMsg.getValuesList().iterator();
- final int trackIndex = in.next().getInt32Value();
- TrackInfo trackInfo = getTrackInfo(dsd).get(trackIndex);
- final long startTimeUs = in.next().getInt64Value();
- final long durationTimeUs = in.next().getInt64Value();
- final byte[] subData = in.next().getBytesValue().toByteArray();
- SubtitleData data = new SubtitleData(trackInfo,
- startTimeUs, durationTimeUs, subData);
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onSubtitleData(
- mMediaPlayer, dsd, data);
- }
- });
- }
- return;
- }
-
- case MEDIA_META_DATA:
- {
- final TimedMetaData data;
- if (msg.obj instanceof byte[]) {
- PlayerMessage playerMsg;
- try {
- playerMsg = PlayerMessage.parseFrom((byte[]) msg.obj);
- } catch (InvalidProtocolBufferException e) {
- Log.w(TAG, "Failed to parse timed meta data.", e);
- return;
- }
- Iterator<Value> in = playerMsg.getValuesList().iterator();
- data = new TimedMetaData(
- in.next().getInt64Value(), // timestampUs
- in.next().getBytesValue().toByteArray()); // metaData
- } else {
- data = null;
- }
-
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onTimedMetaDataAvailable(
- mMediaPlayer, dsd, data);
- }
- });
- return;
- }
-
- case MEDIA_NOP: // interface test message - ignore
- {
- break;
- }
-
- default:
- {
- Log.e(TAG, "Unknown message type " + msg.what);
- return;
- }
- }
- }
- }
-
- /*
- * Called from native code when an interesting event happens. This method
- * just uses the TaskHandler system to post the event back to the main app thread.
- * We use a weak reference to the original MediaPlayer2 object so that the native
- * code is safe from the object disappearing from underneath it. (This is
- * the cookie passed to native_setup().)
- */
- private static void postEventFromNative(Object mediaplayer2Ref, long srcId,
- int what, int arg1, int arg2, byte[] obj) {
- final MediaPlayer2 mp = (MediaPlayer2) ((WeakReference) mediaplayer2Ref).get();
- if (mp == null) {
- return;
- }
-
- final SourceInfo sourceInfo = mp.getSourceInfo(srcId);
- switch (what) {
- case MEDIA_DRM_INFO:
- // We need to derive mDrmInfo before prepare() returns so processing it here
- // before the notification is sent to TaskHandler below. TaskHandler runs in the
- // notification looper so its handleMessage might process the event after prepare()
- // has returned.
- Log.v(TAG, "postEventFromNative MEDIA_DRM_INFO");
- if (obj != null && sourceInfo != null) {
- PlayerMessage playerMsg;
- try {
- playerMsg = PlayerMessage.parseFrom(obj);
- } catch (InvalidProtocolBufferException e) {
- Log.w(TAG, "MEDIA_DRM_INFO failed to parse msg.obj " + obj);
- break;
- }
- DrmInfo drmInfo = DrmInfo.create(playerMsg);
- synchronized (sourceInfo) {
- sourceInfo.mDrmInfo = drmInfo;
- }
- } else {
- Log.w(TAG, "MEDIA_DRM_INFO sourceInfo " + sourceInfo
- + " msg.obj of unexpected type " + obj);
- }
- break;
-
- case MEDIA_PREPARED:
- // By this time, we've learned about DrmInfo's presence or absence. This is meant
- // mainly for prepare() use case. For prepare(), this still can run to a race
- // condition b/c MediaPlayerNative releases the prepare() lock before calling notify
- // so we also set mDrmInfoResolved in prepare().
- if (sourceInfo != null) {
- synchronized (sourceInfo) {
- sourceInfo.mDrmInfoResolved = true;
- }
- }
- break;
- }
-
- if (mp.mTaskHandler != null) {
- Message m = mp.mTaskHandler.obtainMessage(what, arg1, arg2, obj);
-
- mp.mTaskHandler.post(new Runnable() {
- @Override
- public void run() {
- mp.mTaskHandler.handleMessage(m, srcId);
- }
- });
- }
- }
-
- /**
- * Class encapsulating subtitle data, as received through the
- * {@link EventCallback#onSubtitleData} interface.
- * <p>
- * A {@link SubtitleData} object includes:
- * <ul>
- * <li> track metadadta in a {@link TrackInfo} object</li>
- * <li> the start time (in microseconds) of the data</li>
- * <li> the duration (in microseconds) of the data</li>
- * <li> the actual data.</li>
- * </ul>
- * The data is stored in a byte-array, and is encoded in one of the supported in-band
- * subtitle formats. The subtitle encoding is determined by the MIME type of the
- * {@link TrackInfo} of the subtitle track, one of
- * {@link MediaFormat#MIMETYPE_TEXT_CEA_608}, {@link MediaFormat#MIMETYPE_TEXT_CEA_708},
- * {@link MediaFormat#MIMETYPE_TEXT_VTT}.
- */
- public static final class SubtitleData {
-
- private TrackInfo mTrackInfo;
- private long mStartTimeUs;
- private long mDurationUs;
- private byte[] mData;
-
- private SubtitleData(TrackInfo trackInfo, long startTimeUs, long durationUs, byte[] data) {
- mTrackInfo = trackInfo;
- mStartTimeUs = startTimeUs;
- mDurationUs = durationUs;
- mData = (data != null ? data : new byte[0]);
- }
-
- /**
- * @return metadata of track which contains this subtitle data
- */
- @NonNull
- public TrackInfo getTrackInfo() {
- return mTrackInfo;
- }
-
- /**
- * @return media time at which the subtitle should start to be displayed in microseconds
- */
- public long getStartTimeUs() {
- return mStartTimeUs;
- }
-
- /**
- * @return the duration in microsecond during which the subtitle should be displayed
- */
- public long getDurationUs() {
- return mDurationUs;
- }
-
- /**
- * Returns the encoded data for the subtitle content.
- * Encoding format depends on the subtitle type, refer to
- * <a href="https://en.wikipedia.org/wiki/CEA-708">CEA 708</a>,
- * <a href="https://en.wikipedia.org/wiki/EIA-608">CEA/EIA 608</a> and
- * <a href="https://www.w3.org/TR/webvtt1/">WebVTT</a>, defined by the MIME type
- * of the subtitle track.
- * @return the encoded subtitle data
- */
- @NonNull
- public byte[] getData() {
- return mData;
- }
- }
-
- /**
- * Interface definition for callbacks to be invoked when the player has the corresponding
- * events.
- */
- public static class EventCallback {
- /**
- * Called to indicate the video size
- *
- * The video size (width and height) could be 0 if there was no video,
- * or the value was not determined yet.
- *
- * @param mp the MediaPlayer2 associated with this callback
- * @param dsd the DataSourceDesc of this data source
- * @param size the size of the video
- */
- public void onVideoSizeChanged(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @NonNull Size size) { }
-
- /**
- * Called to indicate an avaliable timed text
- *
- * @param mp the MediaPlayer2 associated with this callback
- * @param dsd the DataSourceDesc of this data source
- * @param text the timed text sample which contains the text
- * needed to be displayed and the display format.
- * @hide
- */
- public void onTimedText(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @NonNull TimedText text) { }
-
- /**
- * Called to indicate avaliable timed metadata
- * <p>
- * This method will be called as timed metadata is extracted from the media,
- * in the same order as it occurs in the media. The timing of this event is
- * not controlled by the associated timestamp.
- * <p>
- * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
- * {@link TimedMetaData}.
- *
- * @see MediaPlayer2#selectTrack
- * @see MediaPlayer2.OnTimedMetaDataAvailableListener
- * @see TimedMetaData
- *
- * @param mp the MediaPlayer2 associated with this callback
- * @param dsd the DataSourceDesc of this data source
- * @param data the timed metadata sample associated with this event
- */
- public void onTimedMetaDataAvailable(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @NonNull TimedMetaData data) { }
-
- /**
- * Called to indicate an error.
- *
- * @param mp the MediaPlayer2 the error pertains to
- * @param dsd the DataSourceDesc of this data source
- * @param what the type of error that has occurred.
- * @param extra an extra code, specific to the error. Typically
- * implementation dependent.
- */
- public void onError(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @MediaError int what, int extra) { }
-
- /**
- * Called to indicate an info or a warning.
- *
- * @param mp the MediaPlayer2 the info pertains to.
- * @param dsd the DataSourceDesc of this data source
- * @param what the type of info or warning.
- * @param extra an extra code, specific to the info. Typically
- * implementation dependent.
- */
- public void onInfo(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @MediaInfo int what, int extra) { }
-
- /**
- * Called to acknowledge an API call.
- *
- * @param mp the MediaPlayer2 the call was made on.
- * @param dsd the DataSourceDesc of this data source
- * @param what the enum for the API call.
- * @param status the returned status code for the call.
- */
- public void onCallCompleted(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @CallCompleted int what,
- @CallStatus int status) { }
-
- /**
- * Called to indicate media clock has changed.
- *
- * @param mp the MediaPlayer2 the media time pertains to.
- * @param dsd the DataSourceDesc of this data source
- * @param timestamp the new media clock.
- */
- public void onMediaTimeDiscontinuity(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @NonNull MediaTimestamp timestamp) { }
-
- /**
- * Called to indicate {@link #notifyWhenCommandLabelReached(Object)} has been processed.
- *
- * @param mp the MediaPlayer2 {@link #notifyWhenCommandLabelReached(Object)} was called on.
- * @param label the application specific Object given by
- * {@link #notifyWhenCommandLabelReached(Object)}.
- */
- public void onCommandLabelReached(@NonNull MediaPlayer2 mp, @NonNull Object label) { }
-
- /**
- * Called when when a player subtitle track has new subtitle data available.
- * @param mp the player that reports the new subtitle data
- * @param dsd the DataSourceDesc of this data source
- * @param data the subtitle data
- */
- public void onSubtitleData(
- @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @NonNull SubtitleData data) { }
- }
-
- private final Object mEventCbLock = new Object();
- private ArrayList<Pair<Executor, EventCallback>> mEventCallbackRecords =
- new ArrayList<Pair<Executor, EventCallback>>();
-
- /**
- * Registers the callback to be invoked for various events covered by {@link EventCallback}.
- *
- * @param executor the executor through which the callback should be invoked
- * @param eventCallback the callback that will be run
- */
- // This is a synchronous call.
- public void registerEventCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull EventCallback eventCallback) {
- if (eventCallback == null) {
- throw new IllegalArgumentException("Illegal null EventCallback");
- }
- if (executor == null) {
- throw new IllegalArgumentException(
- "Illegal null Executor for the EventCallback");
- }
- synchronized (mEventCbLock) {
- for (Pair<Executor, EventCallback> cb : mEventCallbackRecords) {
- if (cb.first == executor && cb.second == eventCallback) {
- Log.w(TAG, "The callback has been registered before.");
- return;
- }
- }
- mEventCallbackRecords.add(new Pair(executor, eventCallback));
- }
- }
-
- /**
- * Unregisters the {@link EventCallback}.
- *
- * @param eventCallback the callback to be unregistered
- */
- // This is a synchronous call.
- public void unregisterEventCallback(@NonNull EventCallback eventCallback) {
- synchronized (mEventCbLock) {
- for (Pair<Executor, EventCallback> cb : mEventCallbackRecords) {
- if (cb.second == eventCallback) {
- mEventCallbackRecords.remove(cb);
- }
- }
- }
- }
-
- private void sendEvent(final EventNotifier notifier) {
- synchronized (mEventCbLock) {
- try {
- for (Pair<Executor, EventCallback> cb : mEventCallbackRecords) {
- cb.first.execute(() -> notifier.notify(cb.second));
- }
- } catch (RejectedExecutionException e) {
- // The executor has been shut down.
- Log.w(TAG, "The executor has been shut down. Ignoring event.");
- }
- }
- }
-
- private void sendDrmEvent(final DrmEventNotifier notifier) {
- synchronized (mDrmEventCallbackLock) {
- try {
- Pair<Executor, DrmEventCallback> cb = mDrmEventCallback;
- if (cb != null) {
- cb.first.execute(() -> notifier.notify(cb.second));
- }
- } catch (RejectedExecutionException e) {
- // The executor has been shut down.
- Log.w(TAG, "The executor has been shut down. Ignoring drm event.");
- }
- }
- }
-
- private <T> T sendDrmEventWait(final DrmEventNotifier<T> notifier)
- throws InterruptedException, ExecutionException, TimeoutException {
- return sendDrmEventWait(notifier, 0);
- }
-
- private <T> T sendDrmEventWait(final DrmEventNotifier<T> notifier, final long timeoutMs)
- throws InterruptedException, ExecutionException, TimeoutException {
- synchronized (mDrmEventCallbackLock) {
- Pair<Executor, DrmEventCallback> cb = mDrmEventCallback;
- if (cb != null) {
- CompletableFuture<T> ret = new CompletableFuture<>();
- cb.first.execute(() -> ret.complete(notifier.notifyWait(cb.second)));
- return timeoutMs <= 0 ? ret.get() : ret.get(timeoutMs, TimeUnit.MILLISECONDS);
- }
- }
- return null;
- }
-
- private interface EventNotifier {
- void notify(EventCallback callback);
- }
-
- private interface DrmEventNotifier<T> {
- default void notify(DrmEventCallback callback) { }
- default T notifyWait(DrmEventCallback callback) {
- return null;
- }
- }
-
- /* Do not change these values without updating their counterparts
- * in include/media/MediaPlayer2Types.h!
- */
- /** Unspecified media player error.
- * @see EventCallback#onError
- */
- public static final int MEDIA_ERROR_UNKNOWN = 1;
-
- /**
- * The video is streamed and its container is not valid for progressive
- * playback i.e the video's index (e.g moov atom) is not at the start of the
- * file.
- * @see EventCallback#onError
- */
- public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
-
- /** File or network related operation errors. */
- public static final int MEDIA_ERROR_IO = -1004;
- /** Bitstream is not conforming to the related coding standard or file spec. */
- public static final int MEDIA_ERROR_MALFORMED = -1007;
- /** Bitstream is conforming to the related coding standard or file spec, but
- * the media framework does not support the feature. */
- public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
- /** Some operation takes too long to complete, usually more than 3-5 seconds. */
- public static final int MEDIA_ERROR_TIMED_OUT = -110;
-
- /** Unspecified low-level system error. This value originated from UNKNOWN_ERROR in
- * system/core/include/utils/Errors.h
- * @see EventCallback#onError
- * @hide
- */
- public static final int MEDIA_ERROR_SYSTEM = -2147483648;
-
- /**
- * @hide
- */
- @IntDef(flag = false, prefix = "MEDIA_ERROR", value = {
- MEDIA_ERROR_UNKNOWN,
- MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK,
- MEDIA_ERROR_IO,
- MEDIA_ERROR_MALFORMED,
- MEDIA_ERROR_UNSUPPORTED,
- MEDIA_ERROR_TIMED_OUT,
- MEDIA_ERROR_SYSTEM
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface MediaError {}
-
- /* Do not change these values without updating their counterparts
- * in include/media/MediaPlayer2Types.h!
- */
- /** Unspecified media player info.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_UNKNOWN = 1;
-
- /** The player just started the playback of this datas source.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_DATA_SOURCE_START = 2;
-
- /** The player just pushed the very first video frame for rendering.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
-
- /** The player just rendered the very first audio sample.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_AUDIO_RENDERING_START = 4;
-
- /** The player just completed the playback of this data source.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_DATA_SOURCE_END = 5;
-
- /** The player just completed the playback of all data sources set by {@link #setDataSource},
- * {@link #setNextDataSource} and {@link #setNextDataSources}.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_DATA_SOURCE_LIST_END = 6;
-
- /** The player just completed an iteration of playback loop. This event is sent only when
- * looping is enabled by {@link #loopCurrent}.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_DATA_SOURCE_REPEAT = 7;
-
- /** The player just prepared a data source.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_PREPARED = 100;
-
- /** The video is too complex for the decoder: it can't decode frames fast
- * enough. Possibly only the audio plays fine at this stage.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
-
- /** MediaPlayer2 is temporarily pausing playback internally in order to
- * buffer more data.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_BUFFERING_START = 701;
-
- /** MediaPlayer2 is resuming playback after filling buffers.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_BUFFERING_END = 702;
-
- /** Estimated network bandwidth information (kbps) is available; currently this event fires
- * simultaneously as {@link #MEDIA_INFO_BUFFERING_START} and {@link #MEDIA_INFO_BUFFERING_END}
- * when playing network files.
- * @see EventCallback#onInfo
- * @hide
- */
- public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
-
- /**
- * Update status in buffering a media source received through progressive downloading.
- * The received buffering percentage indicates how much of the content has been buffered
- * or played. For example a buffering update of 80 percent when half the content
- * has already been played indicates that the next 30 percent of the
- * content to play has been buffered.
- *
- * The {@code extra} parameter in {@code EventCallback.onInfo} is the
- * percentage (0-100) of the content that has been buffered or played thus far.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_BUFFERING_UPDATE = 704;
-
- /** Bad interleaving means that a media has been improperly interleaved or
- * not interleaved at all, e.g has all the video samples first then all the
- * audio ones. Video is playing but a lot of disk seeks may be happening.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
-
- /** The media cannot be seeked (e.g live stream)
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
-
- /** A new set of metadata is available.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_METADATA_UPDATE = 802;
-
- /** Informs that audio is not playing. Note that playback of the video
- * is not interrupted.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_AUDIO_NOT_PLAYING = 804;
-
- /** Informs that video is not playing. Note that playback of the audio
- * is not interrupted.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_VIDEO_NOT_PLAYING = 805;
-
- /** Failed to handle timed text track properly.
- * @see EventCallback#onInfo
- *
- * {@hide}
- */
- public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
-
- /** Subtitle track was not supported by the media framework.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
-
- /** Reading the subtitle track takes too long.
- * @see EventCallback#onInfo
- */
- public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
-
- /**
- * @hide
- */
- @IntDef(flag = false, prefix = "MEDIA_INFO", value = {
- MEDIA_INFO_UNKNOWN,
- MEDIA_INFO_DATA_SOURCE_START,
- MEDIA_INFO_VIDEO_RENDERING_START,
- MEDIA_INFO_AUDIO_RENDERING_START,
- MEDIA_INFO_DATA_SOURCE_END,
- MEDIA_INFO_DATA_SOURCE_LIST_END,
- MEDIA_INFO_PREPARED,
- MEDIA_INFO_VIDEO_TRACK_LAGGING,
- MEDIA_INFO_BUFFERING_START,
- MEDIA_INFO_BUFFERING_END,
- MEDIA_INFO_NETWORK_BANDWIDTH,
- MEDIA_INFO_BUFFERING_UPDATE,
- MEDIA_INFO_BAD_INTERLEAVING,
- MEDIA_INFO_NOT_SEEKABLE,
- MEDIA_INFO_METADATA_UPDATE,
- MEDIA_INFO_AUDIO_NOT_PLAYING,
- MEDIA_INFO_VIDEO_NOT_PLAYING,
- MEDIA_INFO_TIMED_TEXT_ERROR,
- MEDIA_INFO_UNSUPPORTED_SUBTITLE,
- MEDIA_INFO_SUBTITLE_TIMED_OUT
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface MediaInfo {}
-
- //--------------------------------------------------------------------------
- /** The player just completed a call {@link #attachAuxEffect}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_ATTACH_AUX_EFFECT = 1;
-
- /** The player just completed a call {@link #deselectTrack}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_DESELECT_TRACK = 2;
-
- /** The player just completed a call {@link #loopCurrent}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_LOOP_CURRENT = 3;
-
- /** The player just completed a call {@link #pause}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_PAUSE = 4;
-
- /** The player just completed a call {@link #play}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_PLAY = 5;
-
- /** The player just completed a call {@link #prepare}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_PREPARE = 6;
-
- /** The player just completed a call {@link #seekTo}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SEEK_TO = 14;
-
- /** The player just completed a call {@link #selectTrack}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SELECT_TRACK = 15;
-
- /** The player just completed a call {@link #setAudioAttributes}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_AUDIO_ATTRIBUTES = 16;
-
- /** The player just completed a call {@link #setAudioSessionId}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_AUDIO_SESSION_ID = 17;
-
- /** The player just completed a call {@link #setAuxEffectSendLevel}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL = 18;
-
- /** The player just completed a call {@link #setDataSource}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_DATA_SOURCE = 19;
-
- /** The player just completed a call {@link #setNextDataSource}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCE = 22;
-
- /** The player just completed a call {@link #setNextDataSources}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCES = 23;
-
- /** The player just completed a call {@link #setPlaybackParams}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_PLAYBACK_PARAMS = 24;
-
- /** The player just completed a call {@link #setPlayerVolume}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_PLAYER_VOLUME = 26;
-
- /** The player just completed a call {@link #setSurface}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_SURFACE = 27;
-
- /** The player just completed a call {@link #setSyncParams}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_SYNC_PARAMS = 28;
-
- /** The player just completed a call {@link #skipToNext}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SKIP_TO_NEXT = 29;
-
- /** The player just completed a call {@link #clearNextDataSources}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES = 30;
-
- /** The player just completed a call {@link #setBufferingParams}.
- * @see EventCallback#onCallCompleted
- * @hide
- */
- public static final int CALL_COMPLETED_SET_BUFFERING_PARAMS = 31;
-
- /** The player just completed a call {@link #setDisplay}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_DISPLAY = 33;
-
- /** The player just completed a call {@link #setWakeLock}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_WAKE_LOCK = 34;
-
- /** The player just completed a call {@link #setScreenOnWhilePlaying}.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING = 35;
-
- /**
- * The start of the methods which have separate call complete callback.
- * @hide
- */
- public static final int SEPARATE_CALL_COMPLETED_CALLBACK_START = 1000;
-
- /** The player just completed a call {@link #notifyWhenCommandLabelReached}.
- * @see EventCallback#onCommandLabelReached
- * @hide
- */
- public static final int CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED =
- SEPARATE_CALL_COMPLETED_CALLBACK_START;
-
- /** The player just completed a call {@link #prepareDrm}.
- * @see DrmEventCallback#onDrmPrepared
- * @hide
- */
- public static final int CALL_COMPLETED_PREPARE_DRM =
- SEPARATE_CALL_COMPLETED_CALLBACK_START + 1;
-
- /**
- * @hide
- */
- @IntDef(flag = false, prefix = "CALL_COMPLETED", value = {
- CALL_COMPLETED_ATTACH_AUX_EFFECT,
- CALL_COMPLETED_DESELECT_TRACK,
- CALL_COMPLETED_LOOP_CURRENT,
- CALL_COMPLETED_PAUSE,
- CALL_COMPLETED_PLAY,
- CALL_COMPLETED_PREPARE,
- CALL_COMPLETED_SEEK_TO,
- CALL_COMPLETED_SELECT_TRACK,
- CALL_COMPLETED_SET_AUDIO_ATTRIBUTES,
- CALL_COMPLETED_SET_AUDIO_SESSION_ID,
- CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL,
- CALL_COMPLETED_SET_DATA_SOURCE,
- CALL_COMPLETED_SET_NEXT_DATA_SOURCE,
- CALL_COMPLETED_SET_NEXT_DATA_SOURCES,
- CALL_COMPLETED_SET_PLAYBACK_PARAMS,
- CALL_COMPLETED_SET_PLAYER_VOLUME,
- CALL_COMPLETED_SET_SURFACE,
- CALL_COMPLETED_SET_SYNC_PARAMS,
- CALL_COMPLETED_SKIP_TO_NEXT,
- CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES,
- CALL_COMPLETED_SET_BUFFERING_PARAMS,
- CALL_COMPLETED_SET_DISPLAY,
- CALL_COMPLETED_SET_WAKE_LOCK,
- CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING,
- CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED,
- CALL_COMPLETED_PREPARE_DRM,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface CallCompleted {}
-
- /** Status code represents that call is completed without an error.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_NO_ERROR = 0;
-
- /** Status code represents that call is ended with an unknown error.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_ERROR_UNKNOWN = Integer.MIN_VALUE;
-
- /** Status code represents that the player is not in valid state for the operation.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_INVALID_OPERATION = 1;
-
- /** Status code represents that the argument is illegal.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_BAD_VALUE = 2;
-
- /** Status code represents that the operation is not allowed.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_PERMISSION_DENIED = 3;
-
- /** Status code represents a file or network related operation error.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_ERROR_IO = 4;
-
- /** Status code represents that the call has been skipped. For example, a {@link #seekTo}
- * request may be skipped if it is followed by another {@link #seekTo} request.
- * @see EventCallback#onCallCompleted
- */
- public static final int CALL_STATUS_SKIPPED = 5;
-
- /** Status code represents that DRM operation is called before preparing a DRM scheme through
- * {@code prepareDrm}.
- * @see EventCallback#onCallCompleted
- */
- // TODO: change @code to @link when DRM is unhidden
- public static final int CALL_STATUS_NO_DRM_SCHEME = 6;
-
- /**
- * @hide
- */
- @IntDef(flag = false, prefix = "CALL_STATUS", value = {
- CALL_STATUS_NO_ERROR,
- CALL_STATUS_ERROR_UNKNOWN,
- CALL_STATUS_INVALID_OPERATION,
- CALL_STATUS_BAD_VALUE,
- CALL_STATUS_PERMISSION_DENIED,
- CALL_STATUS_ERROR_IO,
- CALL_STATUS_SKIPPED,
- CALL_STATUS_NO_DRM_SCHEME})
- @Retention(RetentionPolicy.SOURCE)
- public @interface CallStatus {}
-
- // Modular DRM begin
-
- /**
- * An immutable structure per {@link DataSourceDesc} with settings required to initiate a DRM
- * protected playback session.
- *
- * @see DrmPreparationInfo.Builder
- */
- public static final class DrmPreparationInfo {
-
- /**
- * Mutable builder to create a {@link MediaPlayer2.DrmPreparationInfo} object.
- *
- * {@link Builder#Builder(UUID) UUID} must not be null; {@link #setKeyType keyType}
- * must be one of {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
- * <p>
- * When {@link #setKeyType keyType} is {@link MediaDrm#KEY_TYPE_STREAMING},
- * {@link #setInitData(byte[]) initData} and {@link #setMimeType(String) mimeType}
- * must not be null; When {@link #setKeyType keyType} is {@link MediaDrm#KEY_TYPE_OFFLINE},
- * {@link #setKeySetId(byte[]) keySetId} must not be null.
- */
- public static final class Builder {
-
- private final UUID mUUID;
- private byte[] mKeySetId;
- private byte[] mInitData;
- private String mMimeType;
- private int mKeyType;
- private Map<String, String> mOptionalParameters;
-
- /**
- * @param uuid UUID of the crypto scheme selected to decrypt content. An UUID can be
- * retrieved from the source listening to {@link DrmEventCallback#onDrmInfo}.
- */
- public Builder(@NonNull UUID uuid) {
- this.mUUID = uuid;
- }
-
- /**
- * Set identifier of a persisted offline key obtained from
- * {@link MediaPlayer2.DrmEventCallback#onDrmPrepared}.
- *
- * A {@code keySetId} can be used to restore persisted offline keys into a new playback
- * session of a DRM protected data source. When {@code keySetId} is set,
- * {@code initData}, {@code mimeType}, {@code keyType}, {@code optionalParameters} are
- * ignored.
- *
- * @param keySetId identifier of a persisted offline key
- * @return this
- */
- public @NonNull Builder setKeySetId(@Nullable byte[] keySetId) {
- this.mKeySetId = keySetId;
- return this;
- }
-
- /**
- * Set container-specific DRM initialization data. Its meaning is interpreted based on
- * {@code mimeType}. For example, it could contain the content ID, key ID or other data
- * obtained from the content metadata that is required to generate a
- * {@link MediaDrm.KeyRequest}.
- *
- * @param initData container-specific DRM initialization data
- * @return this
- */
- public @NonNull Builder setInitData(@Nullable byte[] initData) {
- this.mInitData = initData;
- return this;
- }
-
- /**
- * Set mime type of the content
- *
- * @param mimeType mime type to the content
- * @return this
- */
- public @NonNull Builder setMimeType(@Nullable String mimeType) {
- this.mMimeType = mimeType;
- return this;
- }
-
- /**
- * Set type of the key request. The request may be to acquire keys
- * for streaming, {@link MediaDrm#KEY_TYPE_STREAMING}, or for offline content,
- * {@link MediaDrm#KEY_TYPE_OFFLINE}. Releasing previously acquired keys
- * ({@link MediaDrm#KEY_TYPE_RELEASE}) is not allowed.
- *
- * @param keyType type of the key request
- * @return this
- */
- public @NonNull Builder setKeyType(@MediaPlayer2.MediaDrmKeyType int keyType) {
- this.mKeyType = keyType;
- return this;
- }
-
- /**
- * Set optional parameters to be included in a {@link MediaDrm.KeyRequest} message sent
- * to the license server.
- *
- * @param optionalParameters optional parameters to be included in a key request
- * @return this
- */
- public @NonNull Builder setOptionalParameters(
- @Nullable Map<String, String> optionalParameters) {
- this.mOptionalParameters = optionalParameters;
- return this;
- }
-
- /**
- * @return an immutable {@link DrmPreparationInfo} based on settings of this builder
- */
- @NonNull
- public DrmPreparationInfo build() {
- final DrmPreparationInfo info = new DrmPreparationInfo(mUUID, mKeySetId, mInitData,
- mMimeType, mKeyType, mOptionalParameters);
- if (!info.isValid()) {
- throw new IllegalArgumentException("invalid DrmPreparationInfo");
- }
- return info;
- }
-
- }
-
- private final UUID mUUID;
- private final byte[] mKeySetId;
- private final byte[] mInitData;
- private final String mMimeType;
- private final int mKeyType;
- private final Map<String, String> mOptionalParameters;
-
- private DrmPreparationInfo(UUID mUUID, byte[] mKeySetId, byte[] mInitData, String mMimeType,
- int mKeyType, Map<String, String> optionalParameters) {
- this.mUUID = mUUID;
- this.mKeySetId = mKeySetId;
- this.mInitData = mInitData;
- this.mMimeType = mMimeType;
- this.mKeyType = mKeyType;
- this.mOptionalParameters = optionalParameters;
- }
-
- boolean isValid() {
- if (mUUID == null) {
- return false;
- }
- if (mKeySetId != null) {
- // offline restore case
- return true;
- }
- if (mInitData != null && mMimeType != null) {
- // new streaming license case
- return true;
- }
- return false;
- }
-
- /**
- * @return UUID of the crypto scheme selected to decrypt content.
- */
- @NonNull
- public UUID getUuid() {
- return mUUID;
- }
-
- /**
- * @return identifier of the persisted offline key.
- */
- @Nullable
- public byte[] getKeySetId() {
- return mKeySetId;
- }
-
- /**
- * @return container-specific DRM initialization data.
- */
- @Nullable
- public byte[] getInitData() {
- return mInitData;
- }
-
- /**
- * @return mime type of the content
- */
- @Nullable
- public String getMimeType() {
- return mMimeType;
- }
-
- /**
- * @return type of the key request.
- */
- @MediaPlayer2.MediaDrmKeyType
- public int getKeyType() {
- return mKeyType;
- }
-
- /**
- * @return optional parameters to be included in the {@link MediaDrm.KeyRequest}.
- */
- @Nullable
- public Map<String, String> getOptionalParameters() {
- return mOptionalParameters;
- }
- }
-
- /**
- * Interface definition for callbacks to be invoked when the player has the corresponding
- * DRM events.
- */
- public static abstract class DrmEventCallback {
-
- /**
- * Called to indicate DRM info is available. Return a {@link DrmPreparationInfo} object that
- * bundles DRM initialization parameters.
- *
- * @param mp the {@code MediaPlayer2} associated with this callback
- * @param dsd the {@link DataSourceDesc} of this data source
- * @param drmInfo DRM info of the source including PSSH, and subset of crypto schemes
- * supported by this device
- * @return a {@link DrmPreparationInfo} object to initialize DRM playback, or null to skip
- * DRM initialization
- */
- @Nullable
- public abstract DrmPreparationInfo onDrmInfo(@NonNull MediaPlayer2 mp,
- @NonNull DataSourceDesc dsd, @NonNull DrmInfo drmInfo);
-
- /**
- * Called to give the app the opportunity to configure DRM before the session is created.
- *
- * This facilitates configuration of the properties, like 'securityLevel', which
- * has to be set after DRM scheme creation but before the DRM session is opened.
- *
- * The only allowed DRM calls in this listener are
- * {@link MediaDrm#getPropertyString(String)},
- * {@link MediaDrm#getPropertyByteArray(String)},
- * {@link MediaDrm#setPropertyString(String, String)},
- * {@link MediaDrm#setPropertyByteArray(String, byte[])},
- * {@link MediaDrm#setOnExpirationUpdateListener},
- * and {@link MediaDrm#setOnKeyStatusChangeListener}.
- *
- * @param mp the {@code MediaPlayer2} associated with this callback
- * @param dsd the {@link DataSourceDesc} of this data source
- * @param drm handle to get/set DRM properties and listeners for this data source
- */
- public void onDrmConfig(@NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @NonNull MediaDrm drm) { }
-
- /**
- * Called to indicate the DRM session for {@code dsd} is ready for key request/response
- *
- * @param mp the {@code MediaPlayer2} associated with this callback
- * @param dsd the {@link DataSourceDesc} of this data source
- * @param request a {@link MediaDrm.KeyRequest} prepared using the
- * {@link DrmPreparationInfo} returned from
- * {@link #onDrmInfo(MediaPlayer2, DataSourceDesc, DrmInfo)}
- * @return the response to {@code request} (from license server); returning {@code null} or
- * throwing an {@link RuntimeException} from this callback would trigger an
- * {@link EventCallback#onError}.
- */
- @NonNull
- public abstract byte[] onDrmKeyRequest(@NonNull MediaPlayer2 mp,
- @NonNull DataSourceDesc dsd, @NonNull MediaDrm.KeyRequest request);
-
- /**
- * Called to notify the client that {@code mp} is ready to decrypt DRM protected data source
- * {@code dsd} or if there is an error during DRM preparation
- *
- * @param mp the {@code MediaPlayer2} associated with this callback
- * @param dsd the {@link DataSourceDesc} of this data source
- * @param status the result of DRM preparation.
- * @param keySetId optional identifier that can be used to restore DRM playback initiated
- * with a {@link MediaDrm#KEY_TYPE_OFFLINE} key request.
- *
- * @see DrmPreparationInfo.Builder#setKeySetId(byte[])
- */
- public void onDrmPrepared(@NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
- @PrepareDrmStatusCode int status, @Nullable byte[] keySetId) { }
-
- }
-
- private final Object mDrmEventCallbackLock = new Object();
- private Pair<Executor, DrmEventCallback> mDrmEventCallback;
-
- /**
- * Registers the callback to be invoked for various DRM events.
- *
- * This is a synchronous call.
- *
- * @param eventCallback the callback that will be run
- * @param executor the executor through which the callback should be invoked
- */
- public void setDrmEventCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull DrmEventCallback eventCallback) {
- if (eventCallback == null) {
- throw new IllegalArgumentException("Illegal null EventCallback");
- }
- if (executor == null) {
- throw new IllegalArgumentException(
- "Illegal null Executor for the EventCallback");
- }
- synchronized (mDrmEventCallbackLock) {
- mDrmEventCallback = new Pair<Executor, DrmEventCallback>(executor, eventCallback);
- }
- }
-
- /**
- * Clear the {@link DrmEventCallback}.
- *
- * This is a synchronous call.
- */
- public void clearDrmEventCallback() {
- synchronized (mDrmEventCallbackLock) {
- mDrmEventCallback = null;
- }
- }
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * DRM preparation has succeeded.
- */
- public static final int PREPARE_DRM_STATUS_SUCCESS = 0;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * The device required DRM provisioning but couldn't reach the provisioning server.
- */
- public static final int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR = 1;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * The device required DRM provisioning but the provisioning server denied the request.
- */
- public static final int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR = 2;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * The DRM preparation has failed .
- */
- public static final int PREPARE_DRM_STATUS_PREPARATION_ERROR = 3;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * The crypto scheme UUID is not supported by the device.
- */
- public static final int PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME = 4;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * The hardware resources are not available, due to being in use.
- */
- public static final int PREPARE_DRM_STATUS_RESOURCE_BUSY = 5;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * Restoring persisted offline keys failed.
- */
- public static final int PREPARE_DRM_STATUS_RESTORE_ERROR = 6;
-
- /**
- * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
- * <p>
- *
- * Error during key request/response exchange with license server.
- */
- public static final int PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR = 7;
-
- /** @hide */
- @IntDef(flag = false, prefix = "PREPARE_DRM_STATUS", value = {
- PREPARE_DRM_STATUS_SUCCESS,
- PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR,
- PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR,
- PREPARE_DRM_STATUS_PREPARATION_ERROR,
- PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME,
- PREPARE_DRM_STATUS_RESOURCE_BUSY,
- PREPARE_DRM_STATUS_RESTORE_ERROR,
- PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface PrepareDrmStatusCode {}
-
- /** @hide */
- @IntDef({
- MediaDrm.KEY_TYPE_STREAMING,
- MediaDrm.KEY_TYPE_OFFLINE,
- MediaDrm.KEY_TYPE_RELEASE,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface MediaDrmKeyType {}
-
- /** @hide */
- @StringDef({
- MediaDrm.PROPERTY_VENDOR,
- MediaDrm.PROPERTY_VERSION,
- MediaDrm.PROPERTY_DESCRIPTION,
- MediaDrm.PROPERTY_ALGORITHMS,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface MediaDrmStringProperty {}
-
- /**
- * Retrieves the DRM Info associated with the given source
- *
- * @param dsd The DRM protected data source
- *
- * @throws IllegalStateException if called before being prepared
- * @hide
- */
- @TestApi
- public DrmInfo getDrmInfo(@NonNull DataSourceDesc dsd) {
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- DrmInfo drmInfo = null;
-
- // there is not much point if the app calls getDrmInfo within an OnDrmInfoListener;
- // regardless below returns drmInfo anyway instead of raising an exception
- synchronized (sourceInfo) {
- if (!sourceInfo.mDrmInfoResolved && sourceInfo.mDrmInfo == null) {
- final String msg = "The Player has not been prepared yet";
- Log.v(TAG, msg);
- throw new IllegalStateException(msg);
- }
-
- if (sourceInfo.mDrmInfo != null) {
- drmInfo = sourceInfo.mDrmInfo.makeCopy();
- }
- } // synchronized
-
- return drmInfo;
- }
- return null;
- }
-
- /**
- * Prepares the DRM for the given data source
- * <p>
- * If {@link DrmEventCallback} is registered, it will be called during
- * preparation to allow configuration of the DRM properties before opening the
- * DRM session. It should be used only for a series of
- * {@link #getDrmPropertyString(DataSourceDesc, String)} and
- * {@link #setDrmPropertyString(DataSourceDesc, String, String)} calls
- * and refrain from any lengthy operation.
- * <p>
- * If the device has not been provisioned before, this call also provisions the device
- * which involves accessing the provisioning server and can take a variable time to
- * complete depending on the network connectivity.
- * When needed, the provisioning will be launched in the background.
- * The listener {@link DrmEventCallback#onDrmPrepared}
- * will be called when provisioning and preparation are finished. The application should
- * check the status code returned with {@link DrmEventCallback#onDrmPrepared} to proceed.
- * <p>
- * The registered {@link DrmEventCallback#onDrmPrepared} is called to indicate the DRM
- * session being ready. The application should not make any assumption about its call
- * sequence (e.g., before or after prepareDrm returns).
- * <p>
- *
- * @param dsd The DRM protected data source
- *
- * @param uuid The UUID of the crypto scheme. If not known beforehand, it can be retrieved
- * from the source listening to {@link DrmEventCallback#onDrmInfo}.
- *
- * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
- * @hide
- */
- // This is an asynchronous call.
- @TestApi
- public @NonNull Object prepareDrm(@NonNull DataSourceDesc dsd, @NonNull UUID uuid) {
- return addTask(newPrepareDrmTask(dsd, uuid));
- }
-
- private Task newPrepareDrmTask(DataSourceDesc dsd, UUID uuid) {
- return new Task(CALL_COMPLETED_PREPARE_DRM, true) {
- @Override
- void process() {
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- int status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
- boolean finishPrepare = true;
-
- if (sourceInfo == null) {
- Log.e(TAG, "prepareDrm(): DataSource not found.");
- } else if (sourceInfo.mDrmInfo == null) {
- // only allowing if tied to a protected source;
- // might relax for releasing offline keys
- Log.e(TAG, "prepareDrm(): Wrong usage: The player must be prepared and "
- + "DRM info be retrieved before this call.");
- } else {
- status = PREPARE_DRM_STATUS_SUCCESS;
- }
-
- try {
- if (status == PREPARE_DRM_STATUS_SUCCESS) {
- sourceInfo.mDrmHandle.prepare(uuid);
- }
- } catch (ResourceBusyException e) {
- status = PREPARE_DRM_STATUS_RESOURCE_BUSY;
- } catch (UnsupportedSchemeException e) {
- status = PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME;
- } catch (NotProvisionedException e) {
- Log.w(TAG, "prepareDrm: NotProvisionedException");
-
- // handle provisioning internally; it'll reset mPrepareDrmInProgress
- status = sourceInfo.mDrmHandle.handleProvisioninig(uuid, mTaskId);
-
- if (status == PREPARE_DRM_STATUS_SUCCESS) {
- // License will be setup in provisioning
- finishPrepare = false;
- } else {
- synchronized (sourceInfo.mDrmHandle) {
- sourceInfo.mDrmHandle.cleanDrmObj();
- }
-
- switch (status) {
- case PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR:
- Log.e(TAG, "prepareDrm: Provisioning was required but failed "
- + "due to a network error.");
- break;
-
- case PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR:
- Log.e(TAG, "prepareDrm: Provisioning was required but the request "
- + "was denied by the server.");
- break;
-
- case PREPARE_DRM_STATUS_PREPARATION_ERROR:
- default:
- Log.e(TAG, "prepareDrm: Post-provisioning preparation failed.");
- break;
- }
- }
- } catch (Exception e) {
- status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
- }
-
- if (finishPrepare) {
- sourceInfo.mDrmHandle.finishPrepare(status);
- synchronized (mTaskLock) {
- mCurrentTask = null;
- processPendingTask_l();
- }
- }
-
- }
- };
- }
-
- /**
- * Releases the DRM session for the given data source
- * <p>
- * The player has to have an active DRM session and be in stopped, or prepared
- * state before this call is made.
- * A {@link #reset()} call will release the DRM session implicitly.
- *
- * @param dsd The DRM protected data source
- *
- * @throws NoDrmSchemeException if there is no active DRM session to release
- * @hide
- */
- // This is a synchronous call.
- @TestApi
- public void releaseDrm(@NonNull DataSourceDesc dsd)
- throws NoDrmSchemeException {
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- sourceInfo.mDrmHandle.release();
- }
- }
-
- private native void native_releaseDrm(long mSrcId);
-
- /**
- * A key request/response exchange occurs between the app and a license server
- * to obtain or release keys used to decrypt the given data source.
- * <p>
- * {@code getDrmKeyRequest()} is used to obtain an opaque key request byte array that is
- * delivered to the license server. The opaque key request byte array is returned
- * in KeyRequest.data. The recommended URL to deliver the key request to is
- * returned in {@code KeyRequest.defaultUrl}.
- * <p>
- * After the app has received the key request response from the server,
- * it should deliver to the response to the DRM engine plugin using the method
- * {@link #provideDrmKeyResponse(DataSourceDesc, byte[], byte[])}.
- *
- * @param dsd the DRM protected data source
- *
- * @param keySetId is the key-set identifier of the offline keys being released when keyType is
- * {@link MediaDrm#KEY_TYPE_RELEASE}. It should be set to null for other key requests, when
- * keyType is {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
- *
- * @param initData is the container-specific initialization data when the keyType is
- * {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}. Its meaning is
- * interpreted based on the mime type provided in the mimeType parameter. It could
- * contain, for example, the content ID, key ID or other data obtained from the content
- * metadata that is required in generating the key request.
- * When the keyType is {@link MediaDrm#KEY_TYPE_RELEASE}, it should be set to null.
- *
- * @param mimeType identifies the mime type of the content
- *
- * @param keyType specifies the type of the request. The request may be to acquire
- * keys for streaming, {@link MediaDrm#KEY_TYPE_STREAMING}, or for offline content
- * {@link MediaDrm#KEY_TYPE_OFFLINE}, or to release previously acquired
- * keys ({@link MediaDrm#KEY_TYPE_RELEASE}), which are identified by a keySetId.
- *
- * @param optionalParameters are included in the key request message to
- * allow a client application to provide additional message parameters to the server.
- * This may be {@code null} if no additional parameters are to be sent.
- *
- * @throws NoDrmSchemeException if there is no active DRM session
- * @hide
- */
- @TestApi
- public MediaDrm.KeyRequest getDrmKeyRequest(
- @NonNull DataSourceDesc dsd,
- @Nullable byte[] keySetId, @Nullable byte[] initData,
- @Nullable String mimeType, @MediaDrmKeyType int keyType,
- @Nullable Map<String, String> optionalParameters)
- throws NoDrmSchemeException {
- Log.v(TAG, "getDrmKeyRequest: " +
- " keySetId: " + keySetId + " initData:" + initData + " mimeType: " + mimeType +
- " keyType: " + keyType + " optionalParameters: " + optionalParameters);
-
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- return sourceInfo.mDrmHandle.getDrmKeyRequest(
- keySetId, initData, mimeType, keyType, optionalParameters);
- }
- return null;
- }
-
- /**
- * A key response is received from the license server by the app for the given DRM protected
- * data source, then provided to the DRM engine plugin using {@code provideDrmKeyResponse}.
- * <p>
- * When the response is for an offline key request, a key-set identifier is returned that
- * can be used to later restore the keys to a new session with the method
- * {@link #restoreDrmKeys(DataSourceDesc, byte[])}.
- * When the response is for a streaming or release request, null is returned.
- *
- * @param dsd the DRM protected data source
- *
- * @param keySetId When the response is for a release request, keySetId identifies the saved
- * key associated with the release request (i.e., the same keySetId passed to the earlier
- * {@link # getDrmKeyRequest(DataSourceDesc, byte[], byte[], String, int, Map)} call).
- * It MUST be null when the response is for either streaming or offline key requests.
- *
- * @param response the byte array response from the server
- *
- * @throws NoDrmSchemeException if there is no active DRM session
- * @throws DeniedByServerException if the response indicates that the
- * server rejected the request
- * @hide
- */
- // This is a synchronous call.
- @TestApi
- public byte[] provideDrmKeyResponse(
- @NonNull DataSourceDesc dsd,
- @Nullable byte[] keySetId, @NonNull byte[] response)
- throws NoDrmSchemeException, DeniedByServerException {
- Log.v(TAG, "provideDrmKeyResponse: keySetId: " + keySetId + " response: " + response);
-
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- return sourceInfo.mDrmHandle.provideDrmKeyResponse(keySetId, response);
- }
- return null;
- }
-
- /**
- * Restore persisted offline keys into a new session for the given DRM protected data source.
- * {@code keySetId} identifies the keys to load, obtained from a prior call to
- * {@link #provideDrmKeyResponse(DataSourceDesc, byte[], byte[])}.
- *
- * @param dsd the DRM protected data source
- *
- * @param keySetId identifies the saved key set to restore
- *
- * @throws NoDrmSchemeException if there is no active DRM session
- * @hide
- */
- // This is a synchronous call.
- @TestApi
- public void restoreDrmKeys(
- @NonNull DataSourceDesc dsd,
- @NonNull byte[] keySetId)
- throws NoDrmSchemeException {
- Log.v(TAG, "restoreDrmKeys: keySetId: " + keySetId);
-
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- sourceInfo.mDrmHandle.restoreDrmKeys(keySetId);
- }
- }
-
- /**
- * Read a DRM engine plugin String property value, given the DRM protected data source
- * and property name string.
- *
- * @param dsd the DRM protected data source
- *
- * @param propertyName the property name
- *
- * Standard fields names are:
- * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
- * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
- *
- * @throws NoDrmSchemeException if there is no active DRM session
- * @hide
- */
- @TestApi
- public String getDrmPropertyString(
- @NonNull DataSourceDesc dsd,
- @NonNull @MediaDrmStringProperty String propertyName)
- throws NoDrmSchemeException {
- Log.v(TAG, "getDrmPropertyString: propertyName: " + propertyName);
-
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- return sourceInfo.mDrmHandle.getDrmPropertyString(propertyName);
- }
- return null;
- }
-
- /**
- * Set a DRM engine plugin String property value for the given data source.
- *
- * @param dsd the DRM protected data source
- * @param propertyName the property name
- * @param value the property value
- *
- * Standard fields names are:
- * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
- * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
- *
- * @throws NoDrmSchemeException if there is no active DRM session
- * @hide
- */
- // This is a synchronous call.
- @TestApi
- public void setDrmPropertyString(
- @NonNull DataSourceDesc dsd,
- @NonNull @MediaDrmStringProperty String propertyName, @NonNull String value)
- throws NoDrmSchemeException {
- // TODO: this implementation only works when dsd is the only data source
- Log.v(TAG, "setDrmPropertyString: propertyName: " + propertyName + " value: " + value);
-
- final SourceInfo sourceInfo = getSourceInfo(dsd);
- if (sourceInfo != null) {
- sourceInfo.mDrmHandle.setDrmPropertyString(propertyName, value);
- }
- }
-
- /**
- * Encapsulates the DRM properties of the source.
- */
- public static final class DrmInfo {
- private Map<UUID, byte[]> mMapPssh;
- private UUID[] mSupportedSchemes;
-
- /**
- * Returns the PSSH info of the data source for each supported DRM scheme.
- */
- public @NonNull Map<UUID, byte[]> getPssh() {
- return mMapPssh;
- }
-
- /**
- * Returns the intersection of the data source and the device DRM schemes.
- * It effectively identifies the subset of the source's DRM schemes which
- * are supported by the device too.
- */
- public @NonNull List<UUID> getSupportedSchemes() {
- return Arrays.asList(mSupportedSchemes);
- }
-
- private DrmInfo(Map<UUID, byte[]> pssh, UUID[] supportedSchemes) {
- mMapPssh = pssh;
- mSupportedSchemes = supportedSchemes;
- }
-
- private static DrmInfo create(PlayerMessage msg) {
- Log.v(TAG, "DrmInfo.create(" + msg + ")");
-
- Iterator<Value> in = msg.getValuesList().iterator();
- byte[] pssh = in.next().getBytesValue().toByteArray();
-
- Log.v(TAG, "DrmInfo.create() PSSH: " + DrmInfo.arrToHex(pssh));
- Map<UUID, byte[]> mapPssh = DrmInfo.parsePSSH(pssh, pssh.length);
- Log.v(TAG, "DrmInfo.create() PSSH: " + mapPssh);
-
- int supportedDRMsCount = in.next().getInt32Value();
- UUID[] supportedSchemes = new UUID[supportedDRMsCount];
- for (int i = 0; i < supportedDRMsCount; i++) {
- byte[] uuid = new byte[16];
- in.next().getBytesValue().copyTo(uuid, 0);
-
- supportedSchemes[i] = DrmInfo.bytesToUUID(uuid);
-
- Log.v(TAG, "DrmInfo() supportedScheme[" + i + "]: " + supportedSchemes[i]);
- }
-
- Log.v(TAG, "DrmInfo.create() psshsize: " + pssh.length
- + " supportedDRMsCount: " + supportedDRMsCount);
- return new DrmInfo(mapPssh, supportedSchemes);
- }
-
- private DrmInfo makeCopy() {
- return new DrmInfo(this.mMapPssh, this.mSupportedSchemes);
- }
-
- private static String arrToHex(byte[] bytes) {
- String out = "0x";
- for (int i = 0; i < bytes.length; i++) {
- out += String.format("%02x", bytes[i]);
- }
-
- return out;
- }
-
- private static UUID bytesToUUID(byte[] uuid) {
- long msb = 0, lsb = 0;
- for (int i = 0; i < 8; i++) {
- msb |= (((long) uuid[i] & 0xff) << (8 * (7 - i)));
- lsb |= (((long) uuid[i + 8] & 0xff) << (8 * (7 - i)));
- }
-
- return new UUID(msb, lsb);
- }
-
- private static Map<UUID, byte[]> parsePSSH(byte[] pssh, int psshsize) {
- Map<UUID, byte[]> result = new HashMap<UUID, byte[]>();
-
- final int uuidSize = 16;
- final int dataLenSize = 4;
-
- int len = psshsize;
- int numentries = 0;
- int i = 0;
-
- while (len > 0) {
- if (len < uuidSize) {
- Log.w(TAG, String.format("parsePSSH: len is too short to parse "
- + "UUID: (%d < 16) pssh: %d", len, psshsize));
- return null;
- }
-
- byte[] subset = Arrays.copyOfRange(pssh, i, i + uuidSize);
- UUID uuid = bytesToUUID(subset);
- i += uuidSize;
- len -= uuidSize;
-
- // get data length
- if (len < 4) {
- Log.w(TAG, String.format("parsePSSH: len is too short to parse "
- + "datalen: (%d < 4) pssh: %d", len, psshsize));
- return null;
- }
-
- subset = Arrays.copyOfRange(pssh, i, i + dataLenSize);
- int datalen = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN)
- ? ((subset[3] & 0xff) << 24) | ((subset[2] & 0xff) << 16)
- | ((subset[1] & 0xff) << 8) | (subset[0] & 0xff) :
- ((subset[0] & 0xff) << 24) | ((subset[1] & 0xff) << 16)
- | ((subset[2] & 0xff) << 8) | (subset[3] & 0xff);
- i += dataLenSize;
- len -= dataLenSize;
-
- if (len < datalen) {
- Log.w(TAG, String.format("parsePSSH: len is too short to parse "
- + "data: (%d < %d) pssh: %d", len, datalen, psshsize));
- return null;
- }
-
- byte[] data = Arrays.copyOfRange(pssh, i, i + datalen);
-
- // skip the data
- i += datalen;
- len -= datalen;
-
- Log.v(TAG, String.format("parsePSSH[%d]: <%s, %s> pssh: %d",
- numentries, uuid, arrToHex(data), psshsize));
- numentries++;
- result.put(uuid, data);
- }
-
- return result;
- }
- }; // DrmInfo
-
- /**
- * Thrown when a DRM method is called when there is no active DRM session.
- * Extends MediaDrm.MediaDrmException
- */
- public static final class NoDrmSchemeException extends MediaDrmException {
- public NoDrmSchemeException(@Nullable String detailMessage) {
- super(detailMessage);
- }
- }
-
- private native void native_prepareDrm(
- long srcId, @NonNull byte[] uuid, @NonNull byte[] drmSessionId);
-
- // Instantiated from the native side
- @SuppressWarnings("unused")
- private static class StreamEventCallback extends AudioTrack.StreamEventCallback {
- public long mJAudioTrackPtr;
- public long mNativeCallbackPtr;
- public long mUserDataPtr;
-
- StreamEventCallback(long jAudioTrackPtr, long nativeCallbackPtr, long userDataPtr) {
- super();
- mJAudioTrackPtr = jAudioTrackPtr;
- mNativeCallbackPtr = nativeCallbackPtr;
- mUserDataPtr = userDataPtr;
- }
-
- @Override
- public void onTearDown(AudioTrack track) {
- native_stream_event_onTearDown(mNativeCallbackPtr, mUserDataPtr);
- }
-
- @Override
- public void onPresentationEnded(AudioTrack track) {
- native_stream_event_onStreamPresentationEnd(mNativeCallbackPtr, mUserDataPtr);
- }
-
- @Override
- public void onDataRequest(AudioTrack track, int size) {
- native_stream_event_onStreamDataRequest(
- mJAudioTrackPtr, mNativeCallbackPtr, mUserDataPtr);
- }
- }
-
- /**
- * Returns a byte[] containing the remainder of 'in', closing it when done.
- */
- private static byte[] readInputStreamFully(InputStream in) throws IOException {
- try {
- return readInputStreamFullyNoClose(in);
- } finally {
- in.close();
- }
- }
-
- /**
- * Returns a byte[] containing the remainder of 'in'.
- */
- private static byte[] readInputStreamFullyNoClose(InputStream in) throws IOException {
- ByteArrayOutputStream bytes = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int count;
- while ((count = in.read(buffer)) != -1) {
- bytes.write(buffer, 0, count);
- }
- return bytes.toByteArray();
- }
-
- private static byte[] getByteArrayFromUUID(@NonNull UUID uuid) {
- long msb = uuid.getMostSignificantBits();
- long lsb = uuid.getLeastSignificantBits();
-
- byte[] uuidBytes = new byte[16];
- for (int i = 0; i < 8; ++i) {
- uuidBytes[i] = (byte) (msb >>> (8 * (7 - i)));
- uuidBytes[8 + i] = (byte) (lsb >>> (8 * (7 - i)));
- }
-
- return uuidBytes;
- }
-
- private static class TimedTextUtil {
- // These keys must be in sync with the keys in TextDescription2.h
- private static final int KEY_START_TIME = 7; // int
- private static final int KEY_STRUCT_TEXT_POS = 14; // TextPos
- private static final int KEY_STRUCT_TEXT = 16; // Text
- private static final int KEY_GLOBAL_SETTING = 101;
- private static final int KEY_LOCAL_SETTING = 102;
-
- private static TimedText parsePlayerMessage(PlayerMessage playerMsg) {
- if (playerMsg.getValuesCount() == 0) {
- return null;
- }
-
- String textChars = null;
- Rect textBounds = null;
- Iterator<Value> in = playerMsg.getValuesList().iterator();
- int type = in.next().getInt32Value();
- if (type == KEY_LOCAL_SETTING) {
- type = in.next().getInt32Value();
- if (type != KEY_START_TIME) {
- return null;
- }
- int startTimeMs = in.next().getInt32Value();
-
- type = in.next().getInt32Value();
- if (type != KEY_STRUCT_TEXT) {
- return null;
- }
-
- byte[] text = in.next().getBytesValue().toByteArray();
- if (text == null || text.length == 0) {
- textChars = null;
- } else {
- textChars = new String(text);
- }
-
- } else if (type != KEY_GLOBAL_SETTING) {
- Log.w(TAG, "Invalid timed text key found: " + type);
- return null;
- }
- if (in.hasNext()) {
- type = in.next().getInt32Value();
- if (type == KEY_STRUCT_TEXT_POS) {
- int top = in.next().getInt32Value();
- int left = in.next().getInt32Value();
- int bottom = in.next().getInt32Value();
- int right = in.next().getInt32Value();
- textBounds = new Rect(left, top, right, bottom);
- }
- }
- return null;
- /* TimedText c-tor usage is temporarily commented out.
- * TODO(b/117527789): use SUBTITLE path for MEDIA_MIMETYPE_TEXT_3GPP track
- * and remove TimedText path from MediaPlayer2.
- return new TimedText(textChars, textBounds);
- */
- }
- }
-
- private Object addTask(Task task) {
- synchronized (mTaskLock) {
- mPendingTasks.add(task);
- processPendingTask_l();
- }
- return task;
- }
-
- @GuardedBy("mTaskLock")
- private void processPendingTask_l() {
- if (mCurrentTask != null) {
- return;
- }
- if (!mPendingTasks.isEmpty()) {
- Task task = mPendingTasks.remove(0);
- mCurrentTask = task;
- mTaskHandler.post(task);
- }
- }
-
- private abstract class Task implements Runnable {
- final long mTaskId = mTaskIdGenerator.getAndIncrement();
- private final int mMediaCallType;
- private final boolean mNeedToWaitForEventToComplete;
- private DataSourceDesc mDSD;
-
- Task(int mediaCallType, boolean needToWaitForEventToComplete) {
- mMediaCallType = mediaCallType;
- mNeedToWaitForEventToComplete = needToWaitForEventToComplete;
- }
-
- abstract void process() throws IOException, NoDrmSchemeException;
-
- @Override
- public void run() {
- int status = CALL_STATUS_NO_ERROR;
- try {
- if (mMediaCallType != CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED
- && getState() == PLAYER_STATE_ERROR) {
- status = CALL_STATUS_INVALID_OPERATION;
- } else {
- if (mMediaCallType == CALL_COMPLETED_SEEK_TO) {
- synchronized (mTaskLock) {
- if (!mPendingTasks.isEmpty()) {
- Task nextTask = mPendingTasks.get(0);
- if (nextTask.mMediaCallType == mMediaCallType) {
- throw new CommandSkippedException(
- "consecutive seekTo is skipped except last one");
- }
- }
- }
- }
- process();
- }
- } catch (IllegalStateException e) {
- status = CALL_STATUS_INVALID_OPERATION;
- } catch (IllegalArgumentException e) {
- status = CALL_STATUS_BAD_VALUE;
- } catch (SecurityException e) {
- status = CALL_STATUS_PERMISSION_DENIED;
- } catch (IOException e) {
- status = CALL_STATUS_ERROR_IO;
- } catch (NoDrmSchemeException e) {
- status = CALL_STATUS_NO_DRM_SCHEME;
- } catch (CommandSkippedException e) {
- status = CALL_STATUS_SKIPPED;
- } catch (Exception e) {
- status = CALL_STATUS_ERROR_UNKNOWN;
- }
- mDSD = getCurrentDataSource();
-
- if (mMediaCallType != CALL_COMPLETED_SEEK_TO) {
- synchronized (mTaskLock) {
- mIsPreviousCommandSeekTo = false;
- }
- }
-
- // TODO: Make native implementations asynchronous and let them send notifications.
- if (!mNeedToWaitForEventToComplete || status != CALL_STATUS_NO_ERROR) {
-
- sendCompleteNotification(status);
-
- synchronized (mTaskLock) {
- mCurrentTask = null;
- processPendingTask_l();
- }
- }
- }
-
- private void sendCompleteNotification(int status) {
- // In {@link #notifyWhenCommandLabelReached} case, a separate callback
- // {@link #onCommandLabelReached} is already called in {@code process()}.
- // CALL_COMPLETED_PREPARE_DRM is sent via DrmEventCallback#onDrmPrepared
- if (mMediaCallType == CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED
- || mMediaCallType == CALL_COMPLETED_PREPARE_DRM) {
- return;
- }
- sendEvent(new EventNotifier() {
- @Override
- public void notify(EventCallback callback) {
- callback.onCallCompleted(
- MediaPlayer2.this, mDSD, mMediaCallType, status);
- }
- });
- }
- };
-
- private final class CommandSkippedException extends RuntimeException {
- CommandSkippedException(String detailMessage) {
- super(detailMessage);
- }
- };
-
- // Modular DRM
- private final Map<UUID, MediaDrm> mDrmObjs = Collections.synchronizedMap(new HashMap<>());
- private class DrmHandle {
-
- static final int PROVISION_TIMEOUT_MS = 60000;
-
- final DataSourceDesc mDSD;
- final long mSrcId;
-
- //--- guarded by |this| start
- MediaDrm mDrmObj;
- byte[] mDrmSessionId;
- UUID mActiveDrmUUID;
- boolean mDrmConfigAllowed;
- boolean mDrmProvisioningInProgress;
- boolean mPrepareDrmInProgress;
- Future<?> mProvisionResult;
- DrmPreparationInfo mPrepareInfo;
- //--- guarded by |this| end
-
- DrmHandle(DataSourceDesc dsd, long srcId) {
- mDSD = dsd;
- mSrcId = srcId;
- }
-
- void prepare(UUID uuid) throws UnsupportedSchemeException,
- ResourceBusyException, NotProvisionedException, InterruptedException,
- ExecutionException, TimeoutException {
- Log.v(TAG, "prepareDrm: uuid: " + uuid);
-
- synchronized (this) {
- if (mActiveDrmUUID != null) {
- final String msg = "prepareDrm(): Wrong usage: There is already "
- + "an active DRM scheme with " + uuid;
- Log.e(TAG, msg);
- throw new IllegalStateException(msg);
- }
-
- if (mPrepareDrmInProgress) {
- final String msg = "prepareDrm(): Wrong usage: There is already "
- + "a pending prepareDrm call.";
- Log.e(TAG, msg);
- throw new IllegalStateException(msg);
- }
-
- if (mDrmProvisioningInProgress) {
- final String msg = "prepareDrm(): Unexpectd: Provisioning already in progress";
- Log.e(TAG, msg);
- throw new IllegalStateException(msg);
- }
-
- // shouldn't need this; just for safeguard
- cleanDrmObj();
-
- mPrepareDrmInProgress = true;
-
- try {
- // only creating the DRM object to allow pre-openSession configuration
- prepareDrm_createDrmStep(uuid);
- } catch (Exception e) {
- Log.w(TAG, "prepareDrm(): Exception ", e);
- mPrepareDrmInProgress = false;
- throw e;
- }
-
- mDrmConfigAllowed = true;
- } // synchronized
-
- // call the callback outside the lock
- sendDrmEventWait(new DrmEventNotifier<Void>() {
- @Override
- public Void notifyWait(DrmEventCallback callback) {
- callback.onDrmConfig(MediaPlayer2.this, mDSD, mDrmObj);
- return null;
- }
- });
-
- synchronized (this) {
- mDrmConfigAllowed = false;
- boolean earlyExit = false;
-
- try {
- prepareDrm_openSessionStep(uuid);
-
- this.mActiveDrmUUID = uuid;
- mPrepareDrmInProgress = false;
- } catch (IllegalStateException e) {
- final String msg = "prepareDrm(): Wrong usage: The player must be "
- + "in the prepared state to call prepareDrm().";
- Log.e(TAG, msg);
- earlyExit = true;
- mPrepareDrmInProgress = false;
- throw new IllegalStateException(msg);
- } catch (NotProvisionedException e) {
- Log.w(TAG, "prepareDrm: NotProvisionedException", e);
- throw e;
- } catch (Exception e) {
- Log.e(TAG, "prepareDrm: Exception " + e);
- earlyExit = true;
- mPrepareDrmInProgress = false;
- throw e;
- } finally {
- if (earlyExit) { // clean up object if didn't succeed
- cleanDrmObj();
- }
- } // finally
- } // synchronized
- }
-
- void prepareDrm_createDrmStep(UUID uuid)
- throws UnsupportedSchemeException {
- Log.v(TAG, "prepareDrm_createDrmStep: UUID: " + uuid);
-
- try {
- mDrmObj = mDrmObjs.computeIfAbsent(uuid, scheme -> {
- try {
- return new MediaDrm(scheme);
- } catch (UnsupportedSchemeException e) {
- throw new IllegalArgumentException(e);
- }
- });
- Log.v(TAG, "prepareDrm_createDrmStep: Created mDrmObj=" + mDrmObj);
- } catch (Exception e) { // UnsupportedSchemeException
- Log.e(TAG, "prepareDrm_createDrmStep: MediaDrm failed with " + e);
- throw e;
- }
- }
-
- void prepareDrm_openSessionStep(UUID uuid)
- throws NotProvisionedException, ResourceBusyException {
- Log.v(TAG, "prepareDrm_openSessionStep: uuid: " + uuid);
-
- // TODO:
- // don't need an open session for a future specialKeyReleaseDrm mode but we should do
- // it anyway so it raises provisioning error if needed. We'd rather handle provisioning
- // at prepareDrm/openSession rather than getDrmKeyRequest/provideDrmKeyResponse
- try {
- mDrmSessionId = mDrmObj.openSession();
- Log.v(TAG, "prepareDrm_openSessionStep: mDrmSessionId=" + mDrmSessionId);
-
- // Sending it down to native/mediaserver to create the crypto object
- // This call could simply fail due to bad player state, e.g., after play().
- final MediaPlayer2 mp2 = MediaPlayer2.this;
- mp2.native_prepareDrm(mSrcId, getByteArrayFromUUID(uuid), mDrmSessionId);
- Log.v(TAG, "prepareDrm_openSessionStep: native_prepareDrm/Crypto succeeded");
-
- } catch (Exception e) { //ResourceBusyException, NotProvisionedException
- Log.e(TAG, "prepareDrm_openSessionStep: open/crypto failed with " + e);
- throw e;
- }
-
- }
-
- int handleProvisioninig(UUID uuid, long taskId) {
- synchronized (this) {
- if (mDrmProvisioningInProgress) {
- Log.e(TAG, "handleProvisioninig: Unexpected mDrmProvisioningInProgress");
- return PREPARE_DRM_STATUS_PREPARATION_ERROR;
- }
-
- MediaDrm.ProvisionRequest provReq = mDrmObj.getProvisionRequest();
- if (provReq == null) {
- Log.e(TAG, "handleProvisioninig: getProvisionRequest returned null.");
- return PREPARE_DRM_STATUS_PREPARATION_ERROR;
- }
-
- Log.v(TAG, "handleProvisioninig provReq "
- + " data: " + provReq.getData() + " url: " + provReq.getDefaultUrl());
-
- // networking in a background thread
- mDrmProvisioningInProgress = true;
-
- mProvisionResult = sDrmThreadPool.submit(newProvisioningTask(uuid, taskId));
-
- return PREPARE_DRM_STATUS_SUCCESS;
- }
- }
-
- void provision(UUID uuid, long taskId) {
-
- MediaDrm.ProvisionRequest provReq = mDrmObj.getProvisionRequest();
- String urlStr = provReq.getDefaultUrl();
- urlStr += "&signedRequest=" + new String(provReq.getData());
- Log.v(TAG, "handleProvisioninig: Thread is initialised url: " + urlStr);
-
- byte[] response = null;
- boolean provisioningSucceeded = false;
- int status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
- try {
- URL url = new URL(urlStr);
- final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- try {
- connection.setRequestMethod("POST");
- connection.setDoOutput(false);
- connection.setDoInput(true);
- connection.setConnectTimeout(PROVISION_TIMEOUT_MS);
- connection.setReadTimeout(PROVISION_TIMEOUT_MS);
-
- connection.connect();
- response = readInputStreamFully(connection.getInputStream());
-
- Log.v(TAG, "handleProvisioninig: Thread run: response " +
- response.length + " " + response);
- } catch (Exception e) {
- status = PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR;
- Log.w(TAG, "handleProvisioninig: Thread run: connect " + e + " url: " + url);
- } finally {
- connection.disconnect();
- }
- } catch (Exception e) {
- status = PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR;
- Log.w(TAG, "handleProvisioninig: Thread run: openConnection " + e);
- }
-
- if (response != null) {
- try {
- mDrmObj.provideProvisionResponse(response);
- Log.v(TAG, "handleProvisioninig: Thread run: " +
- "provideProvisionResponse SUCCEEDED!");
-
- provisioningSucceeded = true;
- } catch (Exception e) {
- status = PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR;
- Log.w(TAG, "handleProvisioninig: Thread run: " +
- "provideProvisionResponse " + e);
- }
- }
-
- boolean succeeded = false;
-
- synchronized (this) {
- // continuing with prepareDrm
- if (provisioningSucceeded) {
- succeeded = resumePrepare(uuid);
- status = (succeeded) ?
- PREPARE_DRM_STATUS_SUCCESS :
- PREPARE_DRM_STATUS_PREPARATION_ERROR;
- }
- mDrmProvisioningInProgress = false;
- mPrepareDrmInProgress = false;
- if (!succeeded) {
- cleanDrmObj(); // cleaning up if it hasn't gone through while in the lock
- }
- } // synchronized
-
- // calling the callback outside the lock
- finishPrepare(status);
-
- synchronized (mTaskLock) {
- if (mCurrentTask != null
- && mCurrentTask.mTaskId == taskId
- && mCurrentTask.mMediaCallType == CALL_COMPLETED_PREPARE_DRM
- && mCurrentTask.mNeedToWaitForEventToComplete) {
- mCurrentTask = null;
- processPendingTask_l();
- }
- }
- }
-
- Runnable newProvisioningTask(UUID uuid, long taskId) {
- return new Runnable() {
- @Override
- public void run() {
- provision(uuid, taskId);
- }
- };
- }
-
- boolean resumePrepare(UUID uuid) {
- Log.v(TAG, "resumePrepareDrm: uuid: " + uuid);
-
- // mDrmLock is guaranteed to be held
- boolean success = false;
- try {
- // resuming
- prepareDrm_openSessionStep(uuid);
-
- this.mActiveDrmUUID = uuid;
-
- success = true;
- } catch (Exception e) {
- Log.w(TAG, "handleProvisioninig: Thread run native_prepareDrm resume failed:" + e);
- // mDrmObj clean up is done by the caller
- }
-
- return success;
- }
-
- synchronized boolean setPreparationInfo(DrmPreparationInfo prepareInfo) {
- if (prepareInfo == null || !prepareInfo.isValid() || mPrepareInfo != null) {
- return false;
- }
- mPrepareInfo = prepareInfo;
- return true;
- }
-
- void finishPrepare(int status) {
- if (status != PREPARE_DRM_STATUS_SUCCESS) {
- notifyPrepared(status, null);
- return;
- }
-
- if (mPrepareInfo == null) {
- // Deprecated: this can only happen when using MediaPlayer Version 1 APIs
- notifyPrepared(status, null);
- return;
- }
-
- final byte[] keySetId = mPrepareInfo.mKeySetId;
- if (keySetId != null) {
- try {
- mDrmObj.restoreKeys(mDrmSessionId, keySetId);
- notifyPrepared(PREPARE_DRM_STATUS_SUCCESS, keySetId);
- } catch (Exception e) {
- notifyPrepared(PREPARE_DRM_STATUS_RESTORE_ERROR, keySetId);
- }
- return;
- }
-
- sDrmThreadPool.submit(newKeyExchangeTask());
- }
-
- Runnable newKeyExchangeTask() {
- return new Runnable() {
- @Override
- public void run() {
- final byte[] initData = mPrepareInfo.mInitData;
- final String mimeType = mPrepareInfo.mMimeType;
- final int keyType = mPrepareInfo.mKeyType;
- final Map<String, String> optionalParams = mPrepareInfo.mOptionalParameters;
- byte[] keySetId = null;
- try {
- KeyRequest req;
- req = getDrmKeyRequest(null, initData, mimeType, keyType, optionalParams);
- byte[] response = sendDrmEventWait(new DrmEventNotifier<byte[]>() {
- @Override
- public byte[] notifyWait(DrmEventCallback callback) {
- final MediaPlayer2 mp = MediaPlayer2.this;
- return callback.onDrmKeyRequest(mp, mDSD, req);
- }
- });
- keySetId = provideDrmKeyResponse(null, response);
- } catch (Exception e) {
- }
- if (keySetId == null) {
- notifyPrepared(PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR, null);
- } else {
- notifyPrepared(PREPARE_DRM_STATUS_SUCCESS, keySetId);
- }
- }
- };
- }
-
- void notifyPrepared(final int status, byte[] keySetId) {
-
- Message msg;
- if (status == PREPARE_DRM_STATUS_SUCCESS) {
- msg = mTaskHandler.obtainMessage(
- MEDIA_DRM_PREPARED, 0, 0, null);
- } else {
- msg = mTaskHandler.obtainMessage(
- MEDIA_ERROR, status, MEDIA_ERROR_UNKNOWN, null);
- }
- mTaskHandler.post(new Runnable() {
- @Override
- public void run() {
- mTaskHandler.handleMessage(msg, mSrcId);
- }
- });
-
- sendDrmEvent(new DrmEventNotifier() {
- @Override
- public void notify(DrmEventCallback callback) {
- callback.onDrmPrepared(MediaPlayer2.this, mDSD, status,
- keySetId);
- }
- });
-
- }
-
- void cleanDrmObj() {
- // the caller holds mDrmLock
- Log.v(TAG, "cleanDrmObj: mDrmObj=" + mDrmObj + " mDrmSessionId=" + mDrmSessionId);
-
- if (mDrmSessionId != null) {
- mDrmObj.closeSession(mDrmSessionId);
- mDrmSessionId = null;
- }
- }
-
- void release() throws NoDrmSchemeException {
- synchronized (this) {
- Log.v(TAG, "releaseDrm:");
-
- if (mActiveDrmUUID == null) {
- Log.e(TAG, "releaseDrm(): No active DRM scheme to release.");
- throw new NoDrmSchemeException(
- "releaseDrm: No active DRM scheme to release.");
- }
-
- try {
- // we don't have the player's state in this layer. The below call raises
- // exception if we're in a non-stopped/prepared state.
-
- // for cleaning native/mediaserver crypto object
- native_releaseDrm(mSrcId);
-
- // for cleaning client-side MediaDrm object; only called if above has succeeded
- cleanDrmObj();
-
- this.mActiveDrmUUID = null;
- } catch (IllegalStateException e) {
- Log.w(TAG, "releaseDrm: Exception ", e);
- throw new IllegalStateException(
- "releaseDrm: The player is not in a valid state.");
- } catch (Exception e) {
- Log.e(TAG, "releaseDrm: Exception ", e);
- }
- } // synchronized
- }
-
- void cleanup() {
- synchronized (this) {
- Log.v(TAG, "cleanupDrm: " +
- " mProvisioningTask=" + mProvisionResult +
- " mPrepareDrmInProgress=" + mPrepareDrmInProgress +
- " mActiveDrmScheme=" + mActiveDrmUUID);
-
- if (mProvisionResult != null) {
- // timeout; relying on HttpUrlConnection
- try {
- mProvisionResult.get();
- }
- catch (InterruptedException | ExecutionException e) {
- Log.w(TAG, "resetDrmState: ProvThread.join Exception " + e);
- }
- }
-
- // set to false to avoid duplicate release calls
- this.mActiveDrmUUID = null;
-
- native_releaseDrm(mSrcId);
- cleanDrmObj();
- } // synchronized
- }
-
- Runnable newCleanupTask() {
- return new Runnable() {
- @Override
- public void run() {
- cleanup();
- }
- };
- }
-
- MediaDrm.KeyRequest getDrmKeyRequest(
- byte[] keySetId, byte[] initData,
- String mimeType, int keyType,
- Map<String, String> optionalParameters)
- throws NoDrmSchemeException {
- synchronized (this) {
- if (mActiveDrmUUID == null) {
- Log.e(TAG, "getDrmKeyRequest NoDrmSchemeException");
- throw new NoDrmSchemeException(
- "getDrmKeyRequest: Has to set a DRM scheme first.");
- }
-
- try {
- byte[] scope = (keyType != MediaDrm.KEY_TYPE_RELEASE) ?
- mDrmSessionId : // sessionId for KEY_TYPE_STREAMING/OFFLINE
- keySetId; // keySetId for KEY_TYPE_RELEASE
-
- HashMap<String, String> hmapOptionalParameters =
- (optionalParameters != null)
- ? new HashMap<String, String>(optionalParameters)
- : null;
-
- MediaDrm.KeyRequest request = mDrmObj.getKeyRequest(
- scope, initData, mimeType, keyType, hmapOptionalParameters);
- Log.v(TAG, "getDrmKeyRequest: --> request: " + request);
-
- return request;
-
- } catch (NotProvisionedException e) {
- Log.w(TAG, "getDrmKeyRequest NotProvisionedException: " +
- "Unexpected. Shouldn't have reached here.");
- throw new IllegalStateException("getDrmKeyRequest: provisioning error.");
- } catch (Exception e) {
- Log.w(TAG, "getDrmKeyRequest Exception " + e);
- throw e;
- }
-
- }
- }
-
- byte[] provideDrmKeyResponse(byte[] keySetId, byte[] response)
- throws NoDrmSchemeException, DeniedByServerException {
- synchronized (this) {
-
- if (mActiveDrmUUID == null) {
- Log.e(TAG, "getDrmKeyRequest NoDrmSchemeException");
- throw new NoDrmSchemeException(
- "getDrmKeyRequest: Has to set a DRM scheme first.");
- }
-
- try {
- byte[] scope = (keySetId == null) ?
- mDrmSessionId : // sessionId for KEY_TYPE_STREAMING/OFFLINE
- keySetId; // keySetId for KEY_TYPE_RELEASE
-
- byte[] keySetResult = mDrmObj.provideKeyResponse(scope, response);
-
- Log.v(TAG, "provideDrmKeyResponse: keySetId: " + keySetId
- + " response: " + response + " --> " + keySetResult);
-
-
- return keySetResult;
-
- } catch (NotProvisionedException e) {
- Log.w(TAG, "provideDrmKeyResponse NotProvisionedException: " +
- "Unexpected. Shouldn't have reached here.");
- throw new IllegalStateException("provideDrmKeyResponse: " +
- "Unexpected provisioning error.");
- } catch (Exception e) {
- Log.w(TAG, "provideDrmKeyResponse Exception " + e);
- throw e;
- }
- }
- }
-
- void restoreDrmKeys(byte[] keySetId)
- throws NoDrmSchemeException {
- synchronized (this) {
- if (mActiveDrmUUID == null) {
- Log.w(TAG, "restoreDrmKeys NoDrmSchemeException");
- throw new NoDrmSchemeException(
- "restoreDrmKeys: Has to set a DRM scheme first.");
- }
-
- try {
- mDrmObj.restoreKeys(mDrmSessionId, keySetId);
- } catch (Exception e) {
- Log.w(TAG, "restoreKeys Exception " + e);
- throw e;
- }
- }
- }
-
- String getDrmPropertyString(String propertyName)
- throws NoDrmSchemeException {
- String v;
- synchronized (this) {
-
- if (mActiveDrmUUID == null && !mDrmConfigAllowed) {
- Log.w(TAG, "getDrmPropertyString NoDrmSchemeException");
- throw new NoDrmSchemeException(
- "getDrmPropertyString: Has to prepareDrm() first.");
- }
-
- try {
- v = mDrmObj.getPropertyString(propertyName);
- } catch (Exception e) {
- Log.w(TAG, "getDrmPropertyString Exception " + e);
- throw e;
- }
- } // synchronized
-
- Log.v(TAG, "getDrmPropertyString: propertyName: " + propertyName + " --> value: " + v);
-
- return v;
- }
-
- void setDrmPropertyString(String propertyName, String value)
- throws NoDrmSchemeException {
- synchronized (this) {
-
- if ( mActiveDrmUUID == null && !mDrmConfigAllowed ) {
- Log.w(TAG, "setDrmPropertyString NoDrmSchemeException");
- throw new NoDrmSchemeException(
- "setDrmPropertyString: Has to prepareDrm() first.");
- }
-
- try {
- mDrmObj.setPropertyString(propertyName, value);
- } catch ( Exception e ) {
- Log.w(TAG, "setDrmPropertyString Exception " + e);
- throw e;
- }
- }
- }
-
- }
-
- final class SourceInfo {
- final DataSourceDesc mDSD;
- final long mId = mSrcIdGenerator.getAndIncrement();
- AtomicInteger mBufferedPercentage = new AtomicInteger(0);
- boolean mClosed = false;
- int mPrepareBarrier = 1;
-
- // m*AsNextSource (below) only applies to pending data sources in the playlist;
- // the meanings of mCurrentSourceInfo.{mStateAsNextSource,mPlayPendingAsNextSource}
- // are undefined.
- int mStateAsNextSource = NEXT_SOURCE_STATE_INIT;
- boolean mPlayPendingAsNextSource = false;
-
- // Modular DRM
- final DrmHandle mDrmHandle;
- DrmInfo mDrmInfo;
- boolean mDrmInfoResolved;
-
- SourceInfo(DataSourceDesc dsd) {
- this.mDSD = dsd;
- mDrmHandle = new DrmHandle(dsd, mId);
- }
-
- void close() {
- synchronized (this) {
- if (!mClosed) {
- if (mDSD != null) {
- mDSD.close();
- }
- mClosed = true;
- }
- }
- }
-
- @Override
- public String toString() {
- return String.format("%s(%d)", SourceInfo.class.getName(), mId);
- }
-
- }
-
- private SourceInfo getSourceInfo(long srcId) {
- synchronized (mSrcLock) {
- if (isCurrentSource(srcId)) {
- return mCurrentSourceInfo;
- }
- if (isNextSource(srcId)) {
- return mNextSourceInfos.peek();
- }
- }
- return null;
- }
-
- private SourceInfo getSourceInfo(DataSourceDesc dsd) {
- synchronized (mSrcLock) {
- if (isCurrentSource(dsd)) {
- return mCurrentSourceInfo;
- }
- if (isNextSource(dsd)) {
- return mNextSourceInfos.peek();
- }
- }
- return null;
- }
-
- private boolean isCurrentSource(long srcId) {
- synchronized (mSrcLock) {
- return mCurrentSourceInfo != null && mCurrentSourceInfo.mId == srcId;
- }
- }
-
- private boolean isCurrentSource(DataSourceDesc dsd) {
- synchronized (mSrcLock) {
- return mCurrentSourceInfo != null && mCurrentSourceInfo.mDSD == dsd;
- }
- }
-
- private boolean isNextSource(long srcId) {
- SourceInfo nextSourceInfo = mNextSourceInfos.peek();
- return nextSourceInfo != null && nextSourceInfo.mId == srcId;
- }
-
- private boolean isNextSource(DataSourceDesc dsd) {
- SourceInfo nextSourceInfo = mNextSourceInfos.peek();
- return nextSourceInfo != null && nextSourceInfo.mDSD == dsd;
- }
-
- @GuardedBy("mSrcLock")
- private void setCurrentSourceInfo_l(SourceInfo sourceInfo) {
- cleanupSourceInfo(mCurrentSourceInfo);
- mCurrentSourceInfo = sourceInfo;
- }
-
- @GuardedBy("mSrcLock")
- private void clearNextSourceInfos_l() {
- while (!mNextSourceInfos.isEmpty()) {
- cleanupSourceInfo(mNextSourceInfos.poll());
- }
- }
-
- private void cleanupSourceInfo(SourceInfo sourceInfo) {
- if (sourceInfo != null) {
- sourceInfo.close();
- Runnable task = sourceInfo.mDrmHandle.newCleanupTask();
- sDrmThreadPool.submit(task);
- }
- }
-
- private void clearSourceInfos() {
- synchronized (mSrcLock) {
- setCurrentSourceInfo_l(null);
- clearNextSourceInfos_l();
- }
- }
-
- public static final class MetricsConstants {
- private MetricsConstants() {}
-
- /**
- * Key to extract the MIME type of the video track
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is a String.
- */
- public static final String MIME_TYPE_VIDEO = "android.media.mediaplayer.video.mime";
-
- /**
- * Key to extract the codec being used to decode the video track
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is a String.
- */
- public static final String CODEC_VIDEO = "android.media.mediaplayer.video.codec";
-
- /**
- * Key to extract the width (in pixels) of the video track
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is an integer.
- */
- public static final String WIDTH = "android.media.mediaplayer.width";
-
- /**
- * Key to extract the height (in pixels) of the video track
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is an integer.
- */
- public static final String HEIGHT = "android.media.mediaplayer.height";
-
- /**
- * Key to extract the count of video frames played
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is an integer.
- */
- public static final String FRAMES = "android.media.mediaplayer.frames";
-
- /**
- * Key to extract the count of video frames dropped
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is an integer.
- */
- public static final String FRAMES_DROPPED = "android.media.mediaplayer.dropped";
-
- /**
- * Key to extract the MIME type of the audio track
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is a String.
- */
- public static final String MIME_TYPE_AUDIO = "android.media.mediaplayer.audio.mime";
-
- /**
- * Key to extract the codec being used to decode the audio track
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is a String.
- */
- public static final String CODEC_AUDIO = "android.media.mediaplayer.audio.codec";
-
- /**
- * Key to extract the duration (in milliseconds) of the
- * media being played
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is a long.
- */
- public static final String DURATION = "android.media.mediaplayer.durationMs";
-
- /**
- * Key to extract the playing time (in milliseconds) of the
- * media being played
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is a long.
- */
- public static final String PLAYING = "android.media.mediaplayer.playingMs";
-
- /**
- * Key to extract the count of errors encountered while
- * playing the media
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is an integer.
- */
- public static final String ERRORS = "android.media.mediaplayer.err";
-
- /**
- * Key to extract an (optional) error code detected while
- * playing the media
- * from the {@link MediaPlayer2#getMetrics} return value.
- * The value is an integer.
- */
- public static final String ERROR_CODE = "android.media.mediaplayer.errcode";
-
- }
-
- private void keepAudioSessionIdAlive(int sessionId) {
- synchronized (mSessionIdLock) {
- if (mDummyAudioTrack != null) {
- if (mDummyAudioTrack.getAudioSessionId() == sessionId) {
- return;
- }
- mDummyAudioTrack.release();
- }
- // TODO: parameters can be optimized
- mDummyAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
- AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 2,
- AudioTrack.MODE_STATIC, sessionId);
- }
- }
-
- private void keepAudioSessionIdAlive(AudioTrack at) {
- synchronized (mSessionIdLock) {
- if (mDummyAudioTrack != null) {
- if (mDummyAudioTrack.getAudioSessionId() == at.getAudioSessionId()) {
- at.release();
- return;
- }
- mDummyAudioTrack.release();
- }
- mDummyAudioTrack = at;
- }
- }
-}
diff --git a/media/apex/java/android/media/MediaPlayer2Utils.java b/media/apex/java/android/media/MediaPlayer2Utils.java
deleted file mode 100644
index ac34260f9bcf..000000000000
--- a/media/apex/java/android/media/MediaPlayer2Utils.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2018 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.media;
-
-/**
- * Helper class used by native code to reduce JNI calls from native side.
- * @hide
- */
-public class MediaPlayer2Utils {
- /**
- * Returns whether audio offloading is supported for the given audio format.
- *
- * @param encoding the type of encoding defined in {@link AudioFormat}
- * @param sampleRate the sampling rate of the stream
- * @param channelMask the channel mask defined in {@link AudioFormat}
- */
- // @CalledByNative
- public static boolean isOffloadedAudioPlaybackSupported(
- int encoding, int sampleRate, int channelMask) {
- final AudioFormat format = new AudioFormat.Builder()
- .setEncoding(encoding)
- .setSampleRate(sampleRate)
- .setChannelMask(channelMask)
- .build();
- //TODO MP2 needs to pass AudioAttributes for this query, instead of using default attr
- return AudioManager.isOffloadedPlaybackSupported(format,
- (new AudioAttributes.Builder()).build());
- }
-}
diff --git a/media/apex/java/android/media/UriDataSourceDesc.java b/media/apex/java/android/media/UriDataSourceDesc.java
deleted file mode 100644
index adf7a7ddddb9..000000000000
--- a/media/apex/java/android/media/UriDataSourceDesc.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 2018 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.media;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.Uri;
-
-import java.net.HttpCookie;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Structure of data source descriptor for sources using URI.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * <p>Users should use {@link Builder} to change {@link UriDataSourceDesc}.
- * @hide
- */
-public class UriDataSourceDesc extends DataSourceDesc {
- private Uri mUri;
- private Map<String, String> mHeader;
- private List<HttpCookie> mCookies;
-
- UriDataSourceDesc(String mediaId, long startPositionMs, long endPositionMs,
- Uri uri, Map<String, String> header, List<HttpCookie> cookies) {
- super(mediaId, startPositionMs, endPositionMs);
- mUri = uri;
- mHeader = header;
- mCookies = cookies;
- }
-
- /**
- * Return the Uri of this data source.
- * @return the Uri of this data source
- */
- public @NonNull Uri getUri() {
- return mUri;
- }
-
- /**
- * Return the Uri headers of this data source.
- * @return the Uri headers of this data source
- */
- public @Nullable Map<String, String> getHeaders() {
- if (mHeader == null) {
- return null;
- }
- return new HashMap<String, String>(mHeader);
- }
-
- /**
- * Return the Uri cookies of this data source.
- * @return the Uri cookies of this data source
- */
- public @Nullable List<HttpCookie> getCookies() {
- if (mCookies == null) {
- return null;
- }
- return new ArrayList<HttpCookie>(mCookies);
- }
-}
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index 84fe27de15ab..378064d63af4 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -113,88 +113,6 @@ cc_library_shared {
],
}
-cc_library_shared {
- name: "libmedia2_jni",
-
- srcs: [
- "android_media_DataSourceCallback.cpp",
- "android_media_MediaMetricsJNI.cpp",
- "android_media_MediaPlayer2.cpp",
- "android_media_SyncParams.cpp",
- ],
-
- shared_libs: [
- // NDK or LLNDK or NDK-compliant
- "libandroid",
- "libbinder_ndk",
- "libcgrouprc",
- "libmediandk",
- "libmediametrics",
- "libnativehelper_compat_libc++",
- "liblog",
- "libvndksupport",
- ],
-
- header_libs: [
- "libhardware_headers",
- "libnativewindow_headers",
- ],
-
- static_libs: [
- // MediaCas
- "android.hidl.allocator@1.0",
- "android.hidl.memory@1.0",
- "libhidlbase",
- "libhidlmemory",
- "libbinderthreadstate",
-
- // MediaPlayer2 implementation
- "libbase",
- "libcrypto",
- "libcutils",
- "libjsoncpp",
- "libmedia_player2_util",
- "libmediaplayer2",
- "libmediaplayer2-protos",
- "libmediandk_utils",
- "libmediautils",
- "libprocessgroup",
- "libprotobuf-cpp-lite",
- "libstagefright_esds",
- "libstagefright_foundation_without_imemory",
- "libstagefright_httplive",
- "libstagefright_id3",
- "libstagefright_mpeg2support",
- "libstagefright_nuplayer2",
- "libstagefright_player2",
- "libstagefright_rtsp_player2",
- "libstagefright_timedtext2",
- "libutils",
- "libmedia2_jni_core",
- ],
-
- group_static_libs: true,
-
- include_dirs: [
- "frameworks/base/core/jni",
- "frameworks/native/include/media/openmax",
- "system/media/camera/include",
- ],
-
- export_include_dirs: ["."],
-
- cflags: [
- "-Wall",
- "-Werror",
- "-Wno-error=deprecated-declarations",
- "-Wunused",
- "-Wunreachable-code",
- "-fvisibility=hidden",
- ],
-
- ldflags: ["-Wl,--exclude-libs=ALL,-error-limit=0"],
-}
-
subdirs = [
"audioeffect",
"soundpool",
diff --git a/media/jni/android_media_DataSourceCallback.cpp b/media/jni/android_media_DataSourceCallback.cpp
deleted file mode 100644
index c91d4095a32f..000000000000
--- a/media/jni/android_media_DataSourceCallback.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright 2017, 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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "JDataSourceCallback-JNI"
-#include <utils/Log.h>
-
-#include "android_media_DataSourceCallback.h"
-
-#include "log/log.h"
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-
-#include <drm/drm_framework_common.h>
-#include <mediaplayer2/JavaVMHelper.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <nativehelper/ScopedLocalRef.h>
-
-namespace android {
-
-static const size_t kBufferSize = 64 * 1024;
-
-JDataSourceCallback::JDataSourceCallback(JNIEnv* env, jobject source)
- : mJavaObjStatus(OK),
- mSizeIsCached(false),
- mCachedSize(0) {
- mDataSourceCallbackObj = env->NewGlobalRef(source);
- CHECK(mDataSourceCallbackObj != NULL);
-
- ScopedLocalRef<jclass> media2DataSourceClass(env, env->GetObjectClass(mDataSourceCallbackObj));
- CHECK(media2DataSourceClass.get() != NULL);
-
- mReadAtMethod = env->GetMethodID(media2DataSourceClass.get(), "readAt", "(J[BII)I");
- CHECK(mReadAtMethod != NULL);
- mGetSizeMethod = env->GetMethodID(media2DataSourceClass.get(), "getSize", "()J");
- CHECK(mGetSizeMethod != NULL);
- mCloseMethod = env->GetMethodID(media2DataSourceClass.get(), "close", "()V");
- CHECK(mCloseMethod != NULL);
-
- ScopedLocalRef<jbyteArray> tmp(env, env->NewByteArray(kBufferSize));
- mByteArrayObj = (jbyteArray)env->NewGlobalRef(tmp.get());
- CHECK(mByteArrayObj != NULL);
-}
-
-JDataSourceCallback::~JDataSourceCallback() {
- JNIEnv* env = JavaVMHelper::getJNIEnv();
- env->DeleteGlobalRef(mDataSourceCallbackObj);
- env->DeleteGlobalRef(mByteArrayObj);
-}
-
-status_t JDataSourceCallback::initCheck() const {
- return OK;
-}
-
-ssize_t JDataSourceCallback::readAt(off64_t offset, void *data, size_t size) {
- Mutex::Autolock lock(mLock);
-
- if (mJavaObjStatus != OK) {
- return -1;
- }
- if (size > kBufferSize) {
- size = kBufferSize;
- }
-
- JNIEnv* env = JavaVMHelper::getJNIEnv();
- jint numread = env->CallIntMethod(mDataSourceCallbackObj, mReadAtMethod,
- (jlong)offset, mByteArrayObj, (jint)0, (jint)size);
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred in readAt()");
- jniLogException(env, ANDROID_LOG_WARN, LOG_TAG);
- env->ExceptionClear();
- mJavaObjStatus = UNKNOWN_ERROR;
- return -1;
- }
- if (numread < 0) {
- if (numread != -1) {
- ALOGW("An error occurred in readAt()");
- mJavaObjStatus = UNKNOWN_ERROR;
- return -1;
- } else {
- // numread == -1 indicates EOF
- return 0;
- }
- }
- if ((size_t)numread > size) {
- ALOGE("readAt read too many bytes.");
- mJavaObjStatus = UNKNOWN_ERROR;
- return -1;
- }
-
- ALOGV("readAt %lld / %zu => %d.", (long long)offset, size, numread);
- env->GetByteArrayRegion(mByteArrayObj, 0, numread, (jbyte*)data);
- return numread;
-}
-
-status_t JDataSourceCallback::getSize(off64_t* size) {
- Mutex::Autolock lock(mLock);
-
- if (mJavaObjStatus != OK) {
- return UNKNOWN_ERROR;
- }
- if (mSizeIsCached) {
- *size = mCachedSize;
- return OK;
- }
-
- JNIEnv* env = JavaVMHelper::getJNIEnv();
- *size = env->CallLongMethod(mDataSourceCallbackObj, mGetSizeMethod);
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred in getSize()");
- jniLogException(env, ANDROID_LOG_WARN, LOG_TAG);
- env->ExceptionClear();
- // After returning an error, size shouldn't be used by callers.
- *size = UNKNOWN_ERROR;
- mJavaObjStatus = UNKNOWN_ERROR;
- return UNKNOWN_ERROR;
- }
-
- // The minimum size should be -1, which indicates unknown size.
- if (*size < 0) {
- *size = -1;
- }
-
- mCachedSize = *size;
- mSizeIsCached = true;
- return OK;
-}
-
-void JDataSourceCallback::close() {
- Mutex::Autolock lock(mLock);
-
- JNIEnv* env = JavaVMHelper::getJNIEnv();
- env->CallVoidMethod(mDataSourceCallbackObj, mCloseMethod);
- // The closed state is effectively the same as an error state.
- mJavaObjStatus = UNKNOWN_ERROR;
-}
-
-String8 JDataSourceCallback::toString() {
- return String8::format("JDataSourceCallback(pid %d, uid %d)", getpid(), getuid());
-}
-
-String8 JDataSourceCallback::getMIMEType() const {
- return String8("application/octet-stream");
-}
-
-} // namespace android
diff --git a/media/jni/android_media_DataSourceCallback.h b/media/jni/android_media_DataSourceCallback.h
deleted file mode 100644
index 5bde682754f3..000000000000
--- a/media/jni/android_media_DataSourceCallback.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2017, 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.
- */
-
-#ifndef _ANDROID_MEDIA_DATASOURCECALLBACK_H_
-#define _ANDROID_MEDIA_DATASOURCECALLBACK_H_
-
-#include "jni.h"
-
-#include <media/DataSource.h>
-#include <media/stagefright/foundation/ABase.h>
-#include <utils/Errors.h>
-#include <utils/Mutex.h>
-
-namespace android {
-
-// The native counterpart to a Java android.media.DataSourceCallback. It inherits from
-// DataSource.
-//
-// If the java DataSource returns an error or throws an exception it
-// will be considered to be in a broken state, and the only further call this
-// will make is to close().
-class JDataSourceCallback : public DataSource {
-public:
- JDataSourceCallback(JNIEnv *env, jobject source);
- virtual ~JDataSourceCallback();
-
- virtual status_t initCheck() const override;
- virtual ssize_t readAt(off64_t offset, void *data, size_t size) override;
- virtual status_t getSize(off64_t *size) override;
-
- virtual String8 toString() override;
- virtual String8 getMIMEType() const override;
- virtual void close() override;
-private:
- // Protect all member variables with mLock because this object will be
- // accessed on different threads.
- Mutex mLock;
-
- // The status of the java DataSource. Set to OK unless an error occurred or
- // close() was called.
- status_t mJavaObjStatus;
- // Only call the java getSize() once so the app can't change the size on us.
- bool mSizeIsCached;
- off64_t mCachedSize;
-
- jobject mDataSourceCallbackObj;
- jmethodID mReadAtMethod;
- jmethodID mGetSizeMethod;
- jmethodID mCloseMethod;
- jbyteArray mByteArrayObj;
-
- DISALLOW_EVIL_CONSTRUCTORS(JDataSourceCallback);
-};
-
-} // namespace android
-
-#endif // _ANDROID_MEDIA_DATASOURCECALLBACK_H_
diff --git a/media/jni/android_media_MediaMetricsJNI.cpp b/media/jni/android_media_MediaMetricsJNI.cpp
index de60b085b87d..e7487c3cbc67 100644
--- a/media/jni/android_media_MediaMetricsJNI.cpp
+++ b/media/jni/android_media_MediaMetricsJNI.cpp
@@ -23,9 +23,8 @@
#include <media/MediaAnalyticsItem.h>
-// This source file is compiled and linked into both:
+// This source file is compiled and linked into:
// core/jni/ (libandroid_runtime.so)
-// media/jni (libmedia2_jni.so)
namespace android {
diff --git a/media/jni/android_media_MediaPlayer2.cpp b/media/jni/android_media_MediaPlayer2.cpp
deleted file mode 100644
index 306916121740..000000000000
--- a/media/jni/android_media_MediaPlayer2.cpp
+++ /dev/null
@@ -1,1477 +0,0 @@
-/*
-**
-** Copyright 2017, 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.
-*/
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "MediaPlayer2-JNI"
-#include "utils/Log.h"
-
-#include <sys/stat.h>
-
-#include <media/AudioResamplerPublic.h>
-#include <media/DataSourceDesc.h>
-#include <media/MediaHTTPService.h>
-#include <media/MediaAnalyticsItem.h>
-#include <media/NdkWrapper.h>
-#include <media/stagefright/Utils.h>
-#include <media/stagefright/foundation/ByteUtils.h> // for FOURCC definition
-#include <mediaplayer2/JAudioTrack.h>
-#include <mediaplayer2/JavaVMHelper.h>
-#include <mediaplayer2/JMedia2HTTPService.h>
-#include <mediaplayer2/mediaplayer2.h>
-#include <stdio.h>
-#include <assert.h>
-#include <limits.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <utils/threads.h>
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-#include "android/native_window_jni.h"
-#include "log/log.h"
-#include "utils/Errors.h" // for status_t
-#include "utils/KeyedVector.h"
-#include "utils/String8.h"
-#include "android_media_BufferingParams.h"
-#include "android_media_DataSourceCallback.h"
-#include "android_media_MediaMetricsJNI.h"
-#include "android_media_PlaybackParams.h"
-#include "android_media_SyncParams.h"
-#include "android_media_VolumeShaper.h"
-
-#include "android_os_Parcel.h"
-#include "android_util_Binder.h"
-#include <binder/Parcel.h>
-
-#include "mediaplayer2.pb.h"
-
-using android::media::MediaPlayer2Proto::PlayerMessage;
-
-// Modular DRM begin
-#define FIND_CLASS(var, className) \
-var = env->FindClass(className); \
-LOG_FATAL_IF(! (var), "Unable to find class " className);
-
-#define GET_METHOD_ID(var, clazz, fieldName, fieldDescriptor) \
-var = env->GetMethodID(clazz, fieldName, fieldDescriptor); \
-LOG_FATAL_IF(! (var), "Unable to find method " fieldName);
-
-struct StateExceptionFields {
- jmethodID init;
- jclass classId;
-};
-
-static StateExceptionFields gStateExceptionFields;
-// Modular DRM end
-
-// ----------------------------------------------------------------------------
-
-using namespace android;
-
-using media::VolumeShaper;
-
-// ----------------------------------------------------------------------------
-
-struct fields_t {
- jfieldID context; // passed from Java to native, used for creating JWakeLock
- jfieldID nativeContext; // mNativeContext in MediaPlayer2.java
- jfieldID surface_texture;
-
- jmethodID post_event;
-
- jmethodID proxyConfigGetHost;
- jmethodID proxyConfigGetPort;
- jmethodID proxyConfigGetExclusionList;
-};
-static fields_t fields;
-
-static BufferingParams::fields_t gBufferingParamsFields;
-static PlaybackParams::fields_t gPlaybackParamsFields;
-static SyncParams::fields_t gSyncParamsFields;
-static VolumeShaperHelper::fields_t gVolumeShaperFields;
-
-static Mutex sLock;
-
-static bool ConvertKeyValueArraysToKeyedVector(
- JNIEnv *env, jobjectArray keys, jobjectArray values,
- KeyedVector<String8, String8>* keyedVector) {
-
- int nKeyValuePairs = 0;
- bool failed = false;
- if (keys != NULL && values != NULL) {
- nKeyValuePairs = env->GetArrayLength(keys);
- failed = (nKeyValuePairs != env->GetArrayLength(values));
- }
-
- if (!failed) {
- failed = ((keys != NULL && values == NULL) ||
- (keys == NULL && values != NULL));
- }
-
- if (failed) {
- ALOGE("keys and values arrays have different length");
- jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
- return false;
- }
-
- for (int i = 0; i < nKeyValuePairs; ++i) {
- // No need to check on the ArrayIndexOutOfBoundsException, since
- // it won't happen here.
- jstring key = (jstring) env->GetObjectArrayElement(keys, i);
- jstring value = (jstring) env->GetObjectArrayElement(values, i);
-
- const char* keyStr = env->GetStringUTFChars(key, NULL);
- if (!keyStr) { // OutOfMemoryError
- return false;
- }
-
- const char* valueStr = env->GetStringUTFChars(value, NULL);
- if (!valueStr) { // OutOfMemoryError
- env->ReleaseStringUTFChars(key, keyStr);
- return false;
- }
-
- keyedVector->add(String8(keyStr), String8(valueStr));
-
- env->ReleaseStringUTFChars(key, keyStr);
- env->ReleaseStringUTFChars(value, valueStr);
- env->DeleteLocalRef(key);
- env->DeleteLocalRef(value);
- }
- return true;
-}
-
-// ----------------------------------------------------------------------------
-// ref-counted object for callbacks
-class JNIMediaPlayer2Listener: public MediaPlayer2Listener
-{
-public:
- JNIMediaPlayer2Listener(JNIEnv* env, jobject thiz, jobject weak_thiz);
- ~JNIMediaPlayer2Listener();
- virtual void notify(int64_t srcId, int msg, int ext1, int ext2,
- const PlayerMessage *obj = NULL) override;
-private:
- JNIMediaPlayer2Listener();
- jclass mClass; // Reference to MediaPlayer2 class
- jobject mObject; // Weak ref to MediaPlayer2 Java object to call on
-};
-
-JNIMediaPlayer2Listener::JNIMediaPlayer2Listener(JNIEnv* env, jobject thiz, jobject weak_thiz)
-{
-
- // Hold onto the MediaPlayer2 class for use in calling the static method
- // that posts events to the application thread.
- jclass clazz = env->GetObjectClass(thiz);
- if (clazz == NULL) {
- ALOGE("Can't find android/media/MediaPlayer2");
- jniThrowException(env, "java/lang/Exception", NULL);
- return;
- }
- mClass = (jclass)env->NewGlobalRef(clazz);
-
- // We use a weak reference so the MediaPlayer2 object can be garbage collected.
- // The reference is only used as a proxy for callbacks.
- mObject = env->NewGlobalRef(weak_thiz);
-}
-
-JNIMediaPlayer2Listener::~JNIMediaPlayer2Listener()
-{
- // remove global references
- JNIEnv *env = JavaVMHelper::getJNIEnv();
- env->DeleteGlobalRef(mObject);
- env->DeleteGlobalRef(mClass);
-}
-
-void JNIMediaPlayer2Listener::notify(int64_t srcId, int msg, int ext1, int ext2,
- const PlayerMessage* obj)
-{
- JNIEnv *env = JavaVMHelper::getJNIEnv();
- if (obj != NULL) {
- int size = obj->ByteSize();
- jbyte* temp = new jbyte[size];
- obj->SerializeToArray(temp, size);
-
- // return the response as a byte array.
- jbyteArray out = env->NewByteArray(size);
- env->SetByteArrayRegion(out, 0, size, temp);
- env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
- srcId, msg, ext1, ext2, out);
- delete[] temp;
- } else {
- env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
- srcId, msg, ext1, ext2, NULL);
- }
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred while notifying an event.");
- jniLogException(env, ANDROID_LOG_WARN, LOG_TAG);
- env->ExceptionClear();
- }
-}
-
-// ----------------------------------------------------------------------------
-
-static sp<MediaPlayer2> getMediaPlayer(JNIEnv* env, jobject thiz)
-{
- Mutex::Autolock l(sLock);
- MediaPlayer2* const p = (MediaPlayer2*)env->GetLongField(thiz, fields.nativeContext);
- return sp<MediaPlayer2>(p);
-}
-
-static sp<MediaPlayer2> setMediaPlayer(JNIEnv* env, jobject thiz, const sp<MediaPlayer2>& player)
-{
- Mutex::Autolock l(sLock);
- sp<MediaPlayer2> old = (MediaPlayer2*)env->GetLongField(thiz, fields.nativeContext);
- if (player.get()) {
- player->incStrong((void*)setMediaPlayer);
- }
- if (old != 0) {
- old->decStrong((void*)setMediaPlayer);
- }
- env->SetLongField(thiz, fields.nativeContext, (jlong)player.get());
- return old;
-}
-
-// If exception is NULL and opStatus is not OK, this method sends an error
-// event to the client application; otherwise, if exception is not NULL and
-// opStatus is not OK, this method throws the given exception to the client
-// application.
-static void process_media_player_call(
- JNIEnv *env, jobject thiz, status_t opStatus, const char* exception, const char *message)
-{
- if (exception == NULL) { // Don't throw exception. Instead, send an event.
- if (opStatus != (status_t) OK) {
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp != 0) {
- int64_t srcId = 0;
- mp->getSrcId(&srcId);
- mp->notify(srcId, MEDIA2_ERROR, opStatus, 0);
- }
- }
- } else { // Throw exception!
- if ( opStatus == (status_t) INVALID_OPERATION ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- } else if ( opStatus == (status_t) BAD_VALUE ) {
- jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
- } else if ( opStatus == (status_t) PERMISSION_DENIED ) {
- jniThrowException(env, "java/lang/SecurityException", NULL);
- } else if ( opStatus != (status_t) OK ) {
- if (strlen(message) > 230) {
- // if the message is too long, don't bother displaying the status code
- jniThrowException( env, exception, message);
- } else {
- char msg[256];
- // append the status code to the message
- sprintf(msg, "%s: status=0x%X", message, opStatus);
- jniThrowException( env, exception, msg);
- }
- }
- }
-}
-
-static void
-android_media_MediaPlayer2_handleDataSourceUrl(
- JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId,
- jobject httpServiceObj, jstring path, jobjectArray keys, jobjectArray values,
- jlong startPos, jlong endPos) {
-
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- if (path == NULL) {
- jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
- return;
- }
-
- const char *tmp = env->GetStringUTFChars(path, NULL);
- if (tmp == NULL) { // Out of memory
- return;
- }
- ALOGV("handleDataSourceUrl: path %s, srcId %lld, start %lld, end %lld",
- tmp, (long long)srcId, (long long)startPos, (long long)endPos);
-
- if (strncmp(tmp, "content://", 10) == 0) {
- ALOGE("handleDataSourceUrl: content scheme is not supported in native code");
- jniThrowException(env, "java/io/IOException",
- "content scheme is not supported in native code");
- return;
- }
-
- sp<DataSourceDesc> dsd = new DataSourceDesc();
- dsd->mId = srcId;
- dsd->mType = DataSourceDesc::TYPE_URL;
- dsd->mUrl = tmp;
- dsd->mStartPositionMs = startPos;
- dsd->mEndPositionMs = endPos;
-
- env->ReleaseStringUTFChars(path, tmp);
- tmp = NULL;
-
- // We build a KeyedVector out of the key and val arrays
- if (!ConvertKeyValueArraysToKeyedVector(
- env, keys, values, &dsd->mHeaders)) {
- return;
- }
-
- sp<MediaHTTPService> httpService;
- if (httpServiceObj != NULL) {
- httpService = new JMedia2HTTPService(env, httpServiceObj);
- }
- dsd->mHttpService = httpService;
-
- status_t err;
- if (isCurrent) {
- err = mp->setDataSource(dsd);
- } else {
- err = mp->prepareNextDataSource(dsd);
- }
- process_media_player_call(env, thiz, err,
- "java/io/IOException", "handleDataSourceUrl failed." );
-}
-
-static void
-android_media_MediaPlayer2_handleDataSourceFD(
- JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId,
- jobject fileDescriptor, jlong offset, jlong length,
- jlong startPos, jlong endPos) {
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- if (fileDescriptor == NULL) {
- jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
- return;
- }
- int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
- ALOGV("handleDataSourceFD: srcId=%lld, fd=%d (%s), offset=%lld, length=%lld, "
- "start=%lld, end=%lld",
- (long long)srcId, fd, nameForFd(fd).c_str(), (long long)offset, (long long)length,
- (long long)startPos, (long long)endPos);
-
- struct stat sb;
- int ret = fstat(fd, &sb);
- if (ret != 0) {
- ALOGE("handleDataSourceFD: fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
- jniThrowException(env, "java/io/IOException", "handleDataSourceFD failed fstat");
- return;
- }
-
- ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
- ALOGV("st_mode = %u", sb.st_mode);
- ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
- ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
- ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
-
- if (offset >= sb.st_size) {
- ALOGE("handleDataSourceFD: offset is out of range");
- jniThrowException(env, "java/lang/IllegalArgumentException",
- "handleDataSourceFD failed, offset is out of range.");
- return;
- }
- if (offset + length > sb.st_size) {
- length = sb.st_size - offset;
- ALOGV("handleDataSourceFD: adjusted length = %lld", (long long)length);
- }
-
- sp<DataSourceDesc> dsd = new DataSourceDesc();
- dsd->mId = srcId;
- dsd->mType = DataSourceDesc::TYPE_FD;
- dsd->mFD = fd;
- dsd->mFDOffset = offset;
- dsd->mFDLength = length;
- dsd->mStartPositionMs = startPos;
- dsd->mEndPositionMs = endPos;
-
- status_t err;
- if (isCurrent) {
- err = mp->setDataSource(dsd);
- } else {
- err = mp->prepareNextDataSource(dsd);
- }
- process_media_player_call(env, thiz, err,
- "java/io/IOException", "handleDataSourceFD failed." );
-}
-
-static void
-android_media_MediaPlayer2_handleDataSourceCallback(
- JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId, jobject dataSource,
- jlong startPos, jlong endPos)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- if (dataSource == NULL) {
- jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
- return;
- }
- sp<DataSource> callbackDataSource = new JDataSourceCallback(env, dataSource);
- sp<DataSourceDesc> dsd = new DataSourceDesc();
- dsd->mId = srcId;
- dsd->mType = DataSourceDesc::TYPE_CALLBACK;
- dsd->mCallbackSource = callbackDataSource;
- dsd->mStartPositionMs = startPos;
- dsd->mEndPositionMs = endPos;
-
- status_t err;
- if (isCurrent) {
- err = mp->setDataSource(dsd);
- } else {
- err = mp->prepareNextDataSource(dsd);
- }
- process_media_player_call(env, thiz, err,
- "java/lang/RuntimeException", "handleDataSourceCallback failed." );
-}
-
-static sp<ANativeWindowWrapper>
-getVideoSurfaceTexture(JNIEnv* env, jobject thiz) {
- ANativeWindow * const p = (ANativeWindow*)env->GetLongField(thiz, fields.surface_texture);
- return new ANativeWindowWrapper(p);
-}
-
-static void
-decVideoSurfaceRef(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- return;
- }
-
- ANativeWindow * const old_anw = (ANativeWindow*)env->GetLongField(thiz, fields.surface_texture);
- if (old_anw != NULL) {
- ANativeWindow_release(old_anw);
- env->SetLongField(thiz, fields.surface_texture, (jlong)NULL);
- }
-}
-
-static void
-setVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface, jboolean mediaPlayerMustBeAlive)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- if (mediaPlayerMustBeAlive) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- }
- return;
- }
-
- decVideoSurfaceRef(env, thiz);
-
- ANativeWindow* anw = NULL;
- if (jsurface) {
- anw = ANativeWindow_fromSurface(env, jsurface);
- if (anw == NULL) {
- jniThrowException(env, "java/lang/IllegalArgumentException",
- "The surface has been released");
- return;
- }
- }
-
- env->SetLongField(thiz, fields.surface_texture, (jlong)anw);
-
- // This will fail if the media player has not been initialized yet. This
- // can be the case if setDisplay() on MediaPlayer2.java has been called
- // before setDataSource(). The redundant call to setVideoSurfaceTexture()
- // in prepare/prepare covers for this case.
- mp->setVideoSurfaceTexture(new ANativeWindowWrapper(anw));
-}
-
-static void
-android_media_MediaPlayer2_setVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface)
-{
- setVideoSurface(env, thiz, jsurface, true /* mediaPlayerMustBeAlive */);
-}
-
-static jobject
-android_media_MediaPlayer2_getBufferingParams(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return NULL;
- }
-
- BufferingParams bp;
- BufferingSettings &settings = bp.settings;
- process_media_player_call(
- env, thiz, mp->getBufferingSettings(&settings),
- "java/lang/IllegalStateException", "unexpected error");
- if (env->ExceptionCheck()) {
- return nullptr;
- }
- ALOGV("getBufferingSettings:{%s}", settings.toString().string());
-
- return bp.asJobject(env, gBufferingParamsFields);
-}
-
-static void
-android_media_MediaPlayer2_setBufferingParams(JNIEnv *env, jobject thiz, jobject params)
-{
- if (params == NULL) {
- return;
- }
-
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- BufferingParams bp;
- bp.fillFromJobject(env, gBufferingParamsFields, params);
- ALOGV("setBufferingParams:{%s}", bp.settings.toString().string());
-
- process_media_player_call(
- env, thiz, mp->setBufferingSettings(bp.settings),
- "java/lang/IllegalStateException", "unexpected error");
-}
-
-static void
-android_media_MediaPlayer2_playNextDataSource(JNIEnv *env, jobject thiz, jlong srcId)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- process_media_player_call(env, thiz, mp->playNextDataSource((int64_t)srcId),
- "java/io/IOException", "playNextDataSource failed." );
-}
-
-static void
-android_media_MediaPlayer2_prepare(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- // Handle the case where the display surface was set before the mp was
- // initialized. We try again to make it stick.
- sp<ANativeWindowWrapper> st = getVideoSurfaceTexture(env, thiz);
- mp->setVideoSurfaceTexture(st);
-
- process_media_player_call( env, thiz, mp->prepareAsync(), "java/io/IOException", "Prepare Async failed." );
-}
-
-static void
-android_media_MediaPlayer2_start(JNIEnv *env, jobject thiz)
-{
- ALOGV("start");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->start(), NULL, NULL );
-}
-
-static void
-android_media_MediaPlayer2_pause(JNIEnv *env, jobject thiz)
-{
- ALOGV("pause");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->pause(), NULL, NULL );
-}
-
-static void
-android_media_MediaPlayer2_setPlaybackParams(JNIEnv *env, jobject thiz, jobject params)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- PlaybackParams pbp;
- pbp.fillFromJobject(env, gPlaybackParamsFields, params);
- ALOGV("setPlaybackParams: %d:%f %d:%f %d:%u %d:%u",
- pbp.speedSet, pbp.audioRate.mSpeed,
- pbp.pitchSet, pbp.audioRate.mPitch,
- pbp.audioFallbackModeSet, pbp.audioRate.mFallbackMode,
- pbp.audioStretchModeSet, pbp.audioRate.mStretchMode);
-
- AudioPlaybackRate rate;
- status_t err = mp->getPlaybackSettings(&rate);
- if (err == OK) {
- bool updatedRate = false;
- if (pbp.speedSet) {
- rate.mSpeed = pbp.audioRate.mSpeed;
- updatedRate = true;
- }
- if (pbp.pitchSet) {
- rate.mPitch = pbp.audioRate.mPitch;
- updatedRate = true;
- }
- if (pbp.audioFallbackModeSet) {
- rate.mFallbackMode = pbp.audioRate.mFallbackMode;
- updatedRate = true;
- }
- if (pbp.audioStretchModeSet) {
- rate.mStretchMode = pbp.audioRate.mStretchMode;
- updatedRate = true;
- }
- if (updatedRate) {
- err = mp->setPlaybackSettings(rate);
- }
- }
- process_media_player_call(
- env, thiz, err,
- "java/lang/IllegalStateException", "unexpected error");
-}
-
-static jobject
-android_media_MediaPlayer2_getPlaybackParams(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return NULL;
- }
-
- PlaybackParams pbp;
- AudioPlaybackRate &audioRate = pbp.audioRate;
- process_media_player_call(
- env, thiz, mp->getPlaybackSettings(&audioRate),
- "java/lang/IllegalStateException", "unexpected error");
- if (env->ExceptionCheck()) {
- return nullptr;
- }
- ALOGV("getPlaybackSettings: %f %f %d %d",
- audioRate.mSpeed, audioRate.mPitch, audioRate.mFallbackMode, audioRate.mStretchMode);
-
- pbp.speedSet = true;
- pbp.pitchSet = true;
- pbp.audioFallbackModeSet = true;
- pbp.audioStretchModeSet = true;
-
- return pbp.asJobject(env, gPlaybackParamsFields);
-}
-
-static void
-android_media_MediaPlayer2_setSyncParams(JNIEnv *env, jobject thiz, jobject params)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- SyncParams scp;
- scp.fillFromJobject(env, gSyncParamsFields, params);
- ALOGV("setSyncParams: %d:%d %d:%d %d:%f %d:%f",
- scp.syncSourceSet, scp.sync.mSource,
- scp.audioAdjustModeSet, scp.sync.mAudioAdjustMode,
- scp.toleranceSet, scp.sync.mTolerance,
- scp.frameRateSet, scp.frameRate);
-
- AVSyncSettings avsync;
- float videoFrameRate;
- status_t err = mp->getSyncSettings(&avsync, &videoFrameRate);
- if (err == OK) {
- bool updatedSync = scp.frameRateSet;
- if (scp.syncSourceSet) {
- avsync.mSource = scp.sync.mSource;
- updatedSync = true;
- }
- if (scp.audioAdjustModeSet) {
- avsync.mAudioAdjustMode = scp.sync.mAudioAdjustMode;
- updatedSync = true;
- }
- if (scp.toleranceSet) {
- avsync.mTolerance = scp.sync.mTolerance;
- updatedSync = true;
- }
- if (updatedSync) {
- err = mp->setSyncSettings(avsync, scp.frameRateSet ? scp.frameRate : -1.f);
- }
- }
- process_media_player_call(
- env, thiz, err,
- "java/lang/IllegalStateException", "unexpected error");
-}
-
-static jobject
-android_media_MediaPlayer2_getSyncParams(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return NULL;
- }
-
- SyncParams scp;
- scp.frameRate = -1.f;
- process_media_player_call(
- env, thiz, mp->getSyncSettings(&scp.sync, &scp.frameRate),
- "java/lang/IllegalStateException", "unexpected error");
- if (env->ExceptionCheck()) {
- return nullptr;
- }
-
- ALOGV("getSyncSettings: %d %d %f %f",
- scp.sync.mSource, scp.sync.mAudioAdjustMode, scp.sync.mTolerance, scp.frameRate);
-
- // sanity check params
- if (scp.sync.mSource >= AVSYNC_SOURCE_MAX
- || scp.sync.mAudioAdjustMode >= AVSYNC_AUDIO_ADJUST_MODE_MAX
- || scp.sync.mTolerance < 0.f
- || scp.sync.mTolerance >= AVSYNC_TOLERANCE_MAX) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return NULL;
- }
-
- scp.syncSourceSet = true;
- scp.audioAdjustModeSet = true;
- scp.toleranceSet = true;
- scp.frameRateSet = scp.frameRate >= 0.f;
-
- return scp.asJobject(env, gSyncParamsFields);
-}
-
-static void
-android_media_MediaPlayer2_seekTo(JNIEnv *env, jobject thiz, jlong msec, jint mode)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- ALOGV("seekTo: %lld(msec), mode=%d", (long long)msec, mode);
- process_media_player_call(env, thiz, mp->seekTo((int64_t)msec, (MediaPlayer2SeekMode)mode),
- NULL, NULL);
-}
-
-static jint
-android_media_MediaPlayer2_getState(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- return MEDIAPLAYER2_STATE_IDLE;
- }
- return (jint)mp->getState();
-}
-
-static jobject
-android_media_MediaPlayer2_native_getMetrics(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return 0;
- }
-
- char *buffer = NULL;
- size_t length = 0;
- status_t status = mp->getMetrics(&buffer, &length);
- if (status != OK) {
- ALOGD("getMetrics() failed: %d", status);
- return (jobject) NULL;
- }
-
- jobject mybundle = MediaMetricsJNI::writeAttributesToBundle(env, NULL, buffer, length);
-
- free(buffer);
-
- return mybundle;
-}
-
-static jlong
-android_media_MediaPlayer2_getCurrentPosition(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return 0;
- }
- int64_t msec;
- process_media_player_call( env, thiz, mp->getCurrentPosition(&msec), NULL, NULL );
- ALOGV("getCurrentPosition: %lld (msec)", (long long)msec);
- return (jlong) msec;
-}
-
-static jlong
-android_media_MediaPlayer2_getDuration(JNIEnv *env, jobject thiz, jlong srcId)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return 0;
- }
- int64_t msec;
- process_media_player_call( env, thiz, mp->getDuration(srcId, &msec), NULL, NULL );
- ALOGV("getDuration: %lld (msec)", (long long)msec);
- return (jlong) msec;
-}
-
-static void
-android_media_MediaPlayer2_reset(JNIEnv *env, jobject thiz)
-{
- ALOGV("reset");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->reset(), NULL, NULL );
-}
-
-static jboolean
-android_media_MediaPlayer2_setAudioAttributes(JNIEnv *env, jobject thiz, jobject attributes)
-{
- ALOGV("setAudioAttributes");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return false;
- }
- status_t err = mp->setAudioAttributes(attributes);
- return err == OK;
-}
-
-static jobject
-android_media_MediaPlayer2_getAudioAttributes(JNIEnv *env, jobject thiz)
-{
- ALOGV("getAudioAttributes");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return NULL;
- }
-
- return mp->getAudioAttributes();
-}
-
-static void
-android_media_MediaPlayer2_setLooping(JNIEnv *env, jobject thiz, jboolean looping)
-{
- ALOGV("setLooping: %d", looping);
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->setLooping(looping), NULL, NULL );
-}
-
-static jboolean
-android_media_MediaPlayer2_isLooping(JNIEnv *env, jobject thiz)
-{
- ALOGV("isLooping");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return JNI_FALSE;
- }
- return mp->isLooping() ? JNI_TRUE : JNI_FALSE;
-}
-
-static void
-android_media_MediaPlayer2_setVolume(JNIEnv *env, jobject thiz, jfloat volume)
-{
- ALOGV("setVolume: volume %f", (float) volume);
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->setVolume((float) volume), NULL, NULL );
-}
-
-static jbyteArray
-android_media_MediaPlayer2_invoke(JNIEnv *env, jobject thiz, jbyteArray requestData) {
- sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
- if (media_player == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return NULL;
- }
-
- // Get the byte[] pointer and data length.
- jbyte* pData = env->GetByteArrayElements(requestData, NULL);
- jsize pDataLen = env->GetArrayLength(requestData);
-
- // Deserialize from the byte stream.
- PlayerMessage request;
- PlayerMessage response;
- request.ParseFromArray(pData, pDataLen);
-
- process_media_player_call( env, thiz, media_player->invoke(request, &response),
- "java.lang.RuntimeException", NULL );
- if (env->ExceptionCheck()) {
- return NULL;
- }
-
- int size = response.ByteSize();
- jbyte* temp = new jbyte[size];
- response.SerializeToArray(temp, size);
-
- // return the response as a byte array.
- jbyteArray out = env->NewByteArray(size);
- env->SetByteArrayRegion(out, 0, size, temp);
- delete[] temp;
-
- return out;
-}
-
-// This function gets some field IDs, which in turn causes class initialization.
-// It is called from a static block in MediaPlayer2, which won't run until the
-// first time an instance of this class is used.
-static void
-android_media_MediaPlayer2_native_init(JNIEnv *env)
-{
- jclass clazz;
-
- clazz = env->FindClass("android/media/MediaPlayer2");
- if (clazz == NULL) {
- return;
- }
-
- fields.context = env->GetFieldID(clazz, "mContext", "Landroid/content/Context;");
- if (fields.context == NULL) {
- return;
- }
-
- fields.nativeContext = env->GetFieldID(clazz, "mNativeContext", "J");
- if (fields.nativeContext == NULL) {
- return;
- }
-
- fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
- "(Ljava/lang/Object;JIII[B)V");
- if (fields.post_event == NULL) {
- return;
- }
-
- fields.surface_texture = env->GetFieldID(clazz, "mNativeSurfaceTexture", "J");
- if (fields.surface_texture == NULL) {
- return;
- }
-
- env->DeleteLocalRef(clazz);
-
- clazz = env->FindClass("android/net/ProxyInfo");
- if (clazz == NULL) {
- return;
- }
-
- fields.proxyConfigGetHost =
- env->GetMethodID(clazz, "getHost", "()Ljava/lang/String;");
-
- fields.proxyConfigGetPort =
- env->GetMethodID(clazz, "getPort", "()I");
-
- fields.proxyConfigGetExclusionList =
- env->GetMethodID(clazz, "getExclusionListAsString", "()Ljava/lang/String;");
-
- env->DeleteLocalRef(clazz);
-
- gBufferingParamsFields.init(env);
-
- // Modular DRM
- FIND_CLASS(clazz, "android/media/MediaDrm$MediaDrmStateException");
- if (clazz) {
- GET_METHOD_ID(gStateExceptionFields.init, clazz, "<init>", "(ILjava/lang/String;)V");
- gStateExceptionFields.classId = static_cast<jclass>(env->NewGlobalRef(clazz));
-
- env->DeleteLocalRef(clazz);
- } else {
- ALOGE("JNI android_media_MediaPlayer2_native_init couldn't "
- "get clazz android/media/MediaDrm$MediaDrmStateException");
- }
-
- gPlaybackParamsFields.init(env);
- gSyncParamsFields.init(env);
- gVolumeShaperFields.init(env);
-}
-
-static void
-android_media_MediaPlayer2_native_setup(JNIEnv *env, jobject thiz,
- jint sessionId, jobject weak_this)
-{
- ALOGV("native_setup");
- jobject context = env->GetObjectField(thiz, fields.context);
- sp<MediaPlayer2> mp = MediaPlayer2::Create(sessionId, context);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
- return;
- }
-
- // create new listener and give it to MediaPlayer2
- sp<JNIMediaPlayer2Listener> listener = new JNIMediaPlayer2Listener(env, thiz, weak_this);
- mp->setListener(listener);
-
- // Stow our new C++ MediaPlayer2 in an opaque field in the Java object.
- setMediaPlayer(env, thiz, mp);
-}
-
-static void
-android_media_MediaPlayer2_release(JNIEnv *env, jobject thiz)
-{
- ALOGV("release");
- decVideoSurfaceRef(env, thiz);
- sp<MediaPlayer2> mp = setMediaPlayer(env, thiz, 0);
- if (mp != NULL) {
- // this prevents native callbacks after the object is released
- mp->setListener(0);
- mp->disconnect();
- }
-}
-
-static void
-android_media_MediaPlayer2_native_finalize(JNIEnv *env, jobject thiz)
-{
- ALOGV("native_finalize");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp != NULL) {
- ALOGW("MediaPlayer2 finalized without being released");
- }
- android_media_MediaPlayer2_release(env, thiz);
-}
-
-static void android_media_MediaPlayer2_setAudioSessionId(JNIEnv *env, jobject thiz,
- jint sessionId) {
- ALOGV("setAudioSessionId(): %d", sessionId);
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->setAudioSessionId((audio_session_t) sessionId), NULL,
- NULL);
-}
-
-static jint android_media_MediaPlayer2_getAudioSessionId(JNIEnv *env, jobject thiz) {
- ALOGV("getAudioSessionId()");
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return 0;
- }
-
- return (jint) mp->getAudioSessionId();
-}
-
-static void
-android_media_MediaPlayer2_setAuxEffectSendLevel(JNIEnv *env, jobject thiz, jfloat level)
-{
- ALOGV("setAuxEffectSendLevel: level %f", level);
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->setAuxEffectSendLevel(level), NULL, NULL );
-}
-
-static void android_media_MediaPlayer2_attachAuxEffect(JNIEnv *env, jobject thiz, jint effectId) {
- ALOGV("attachAuxEffect(): %d", effectId);
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
- process_media_player_call( env, thiz, mp->attachAuxEffect(effectId), NULL, NULL );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////
-// Modular DRM begin
-
-// TODO: investigate if these can be shared with their MediaDrm counterparts
-static void throwDrmStateException(JNIEnv *env, const char *msg, status_t err)
-{
- ALOGE("Illegal DRM state exception: %s (%d)", msg, err);
-
- jobject exception = env->NewObject(gStateExceptionFields.classId,
- gStateExceptionFields.init, static_cast<int>(err),
- env->NewStringUTF(msg));
- env->Throw(static_cast<jthrowable>(exception));
-}
-
-// TODO: investigate if these can be shared with their MediaDrm counterparts
-static bool throwDrmExceptionAsNecessary(JNIEnv *env, status_t err, const char *msg = NULL)
-{
- const char *drmMessage = "Unknown DRM Msg";
-
- switch (err) {
- case ERROR_DRM_UNKNOWN:
- drmMessage = "General DRM error";
- break;
- case ERROR_DRM_NO_LICENSE:
- drmMessage = "No license";
- break;
- case ERROR_DRM_LICENSE_EXPIRED:
- drmMessage = "License expired";
- break;
- case ERROR_DRM_SESSION_NOT_OPENED:
- drmMessage = "Session not opened";
- break;
- case ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED:
- drmMessage = "Not initialized";
- break;
- case ERROR_DRM_DECRYPT:
- drmMessage = "Decrypt error";
- break;
- case ERROR_DRM_CANNOT_HANDLE:
- drmMessage = "Unsupported scheme or data format";
- break;
- case ERROR_DRM_TAMPER_DETECTED:
- drmMessage = "Invalid state";
- break;
- default:
- break;
- }
-
- String8 vendorMessage;
- if (err >= ERROR_DRM_VENDOR_MIN && err <= ERROR_DRM_VENDOR_MAX) {
- vendorMessage = String8::format("DRM vendor-defined error: %d", err);
- drmMessage = vendorMessage.string();
- }
-
- if (err == BAD_VALUE) {
- jniThrowException(env, "java/lang/IllegalArgumentException", msg);
- return true;
- } else if (err == ERROR_DRM_NOT_PROVISIONED) {
- jniThrowException(env, "android/media/NotProvisionedException", msg);
- return true;
- } else if (err == ERROR_DRM_RESOURCE_BUSY) {
- jniThrowException(env, "android/media/ResourceBusyException", msg);
- return true;
- } else if (err == ERROR_DRM_DEVICE_REVOKED) {
- jniThrowException(env, "android/media/DeniedByServerException", msg);
- return true;
- } else if (err == DEAD_OBJECT) {
- jniThrowException(env, "android/media/MediaDrmResetException",
- "mediaserver died");
- return true;
- } else if (err != OK) {
- String8 errbuf;
- if (drmMessage != NULL) {
- if (msg == NULL) {
- msg = drmMessage;
- } else {
- errbuf = String8::format("%s: %s", msg, drmMessage);
- msg = errbuf.string();
- }
- }
- throwDrmStateException(env, msg, err);
- return true;
- }
- return false;
-}
-
-static Vector<uint8_t> JByteArrayToVector(JNIEnv *env, jbyteArray const &byteArray)
-{
- Vector<uint8_t> vector;
- size_t length = env->GetArrayLength(byteArray);
- vector.insertAt((size_t)0, length);
- env->GetByteArrayRegion(byteArray, 0, length, (jbyte *)vector.editArray());
- return vector;
-}
-
-static void android_media_MediaPlayer2_prepareDrm(JNIEnv *env, jobject thiz,
- jlong srcId, jbyteArray uuidObj, jbyteArray drmSessionIdObj)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- if (uuidObj == NULL) {
- jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
- return;
- }
-
- Vector<uint8_t> uuid = JByteArrayToVector(env, uuidObj);
-
- if (uuid.size() != 16) {
- jniThrowException(
- env,
- "java/lang/IllegalArgumentException",
- "invalid UUID size, expected 16 bytes");
- return;
- }
-
- Vector<uint8_t> drmSessionId = JByteArrayToVector(env, drmSessionIdObj);
-
- if (drmSessionId.size() == 0) {
- jniThrowException(
- env,
- "java/lang/IllegalArgumentException",
- "empty drmSessionId");
- return;
- }
-
- status_t err = mp->prepareDrm(srcId, uuid.array(), drmSessionId);
- if (err != OK) {
- if (err == INVALID_OPERATION) {
- jniThrowException(
- env,
- "java/lang/IllegalStateException",
- "The player must be in prepared state.");
- } else if (err == ERROR_DRM_CANNOT_HANDLE) {
- jniThrowException(
- env,
- "android/media/UnsupportedSchemeException",
- "Failed to instantiate drm object.");
- } else {
- throwDrmExceptionAsNecessary(env, err, "Failed to prepare DRM scheme");
- }
- }
-}
-
-static void android_media_MediaPlayer2_releaseDrm(JNIEnv *env, jobject thiz, jlong srcId)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL ) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- return;
- }
-
- status_t err = mp->releaseDrm(srcId);
- if (err != OK) {
- if (err == INVALID_OPERATION) {
- jniThrowException(
- env,
- "java/lang/IllegalStateException",
- "Can not release DRM in an active player state.");
- }
- }
-}
-// Modular DRM end
-// ----------------------------------------------------------------------------
-
-/////////////////////////////////////////////////////////////////////////////////////
-// AudioRouting begin
-static jboolean android_media_MediaPlayer2_setPreferredDevice(JNIEnv *env, jobject thiz, jobject device)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- return false;
- }
- return mp->setPreferredDevice(device) == NO_ERROR;
-}
-
-static jobject android_media_MediaPlayer2_getRoutedDevice(JNIEnv *env, jobject thiz)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- return nullptr;
- }
- return mp->getRoutedDevice();
-}
-
-static void android_media_MediaPlayer2_addDeviceCallback(
- JNIEnv* env, jobject thiz, jobject routingDelegate)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- return;
- }
-
- status_t status = mp->addAudioDeviceCallback(routingDelegate);
- if (status != NO_ERROR) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- ALOGE("enable device callback failed: %d", status);
- }
-}
-
-static void android_media_MediaPlayer2_removeDeviceCallback(
- JNIEnv* env, jobject thiz, jobject listener)
-{
- sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
- if (mp == NULL) {
- return;
- }
-
- status_t status = mp->removeAudioDeviceCallback(listener);
- if (status != NO_ERROR) {
- jniThrowException(env, "java/lang/IllegalStateException", NULL);
- ALOGE("enable device callback failed: %d", status);
- }
-}
-
-// AudioRouting end
-// ----------------------------------------------------------------------------
-
-/////////////////////////////////////////////////////////////////////////////////////
-// AudioTrack.StreamEventCallback begin
-static void android_media_MediaPlayer2_native_on_tear_down(JNIEnv *env __unused,
- jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
-{
- JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
- if (callback != NULL) {
- callback(JAudioTrack::EVENT_NEW_IAUDIOTRACK, (void *) userDataPtr, NULL);
- }
-}
-
-static void android_media_MediaPlayer2_native_on_stream_presentation_end(JNIEnv *env __unused,
- jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
-{
- JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
- if (callback != NULL) {
- callback(JAudioTrack::EVENT_STREAM_END, (void *) userDataPtr, NULL);
- }
-}
-
-static void android_media_MediaPlayer2_native_on_stream_data_request(JNIEnv *env __unused,
- jobject thiz __unused, jlong jAudioTrackPtr, jlong callbackPtr, jlong userDataPtr)
-{
- JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
- JAudioTrack* track = (JAudioTrack *) jAudioTrackPtr;
- if (callback != NULL && track != NULL) {
- JAudioTrack::Buffer* buffer = new JAudioTrack::Buffer();
-
- size_t bufferSizeInFrames = track->frameCount();
- audio_format_t format = track->format();
-
- size_t bufferSizeInBytes;
- if (audio_has_proportional_frames(format)) {
- bufferSizeInBytes =
- bufferSizeInFrames * audio_bytes_per_sample(format) * track->channelCount();
- } else {
- // See Javadoc of AudioTrack::getBufferSizeInFrames().
- bufferSizeInBytes = bufferSizeInFrames;
- }
-
- uint8_t* byteBuffer = new uint8_t[bufferSizeInBytes];
- buffer->mSize = bufferSizeInBytes;
- buffer->mData = (void *) byteBuffer;
-
- callback(JAudioTrack::EVENT_MORE_DATA, (void *) userDataPtr, buffer);
-
- if (buffer->mSize > 0 && buffer->mData == byteBuffer) {
- track->write(buffer->mData, buffer->mSize, true /* Blocking */);
- }
-
- delete[] byteBuffer;
- delete buffer;
- }
-}
-
-
-// AudioTrack.StreamEventCallback end
-// ----------------------------------------------------------------------------
-
-static const JNINativeMethod gMethods[] = {
- {
- "nativeHandleDataSourceUrl",
- "(ZJLandroid/media/Media2HTTPService;Ljava/lang/String;[Ljava/lang/String;"
- "[Ljava/lang/String;JJ)V",
- (void *)android_media_MediaPlayer2_handleDataSourceUrl
- },
- {
- "nativeHandleDataSourceFD",
- "(ZJLjava/io/FileDescriptor;JJJJ)V",
- (void *)android_media_MediaPlayer2_handleDataSourceFD
- },
- {
- "nativeHandleDataSourceCallback",
- "(ZJLandroid/media/DataSourceCallback;JJ)V",
- (void *)android_media_MediaPlayer2_handleDataSourceCallback
- },
- {"nativePlayNextDataSource", "(J)V", (void *)android_media_MediaPlayer2_playNextDataSource},
- {"native_setVideoSurface", "(Landroid/view/Surface;)V", (void *)android_media_MediaPlayer2_setVideoSurface},
- {"getBufferingParams", "()Landroid/media/BufferingParams;", (void *)android_media_MediaPlayer2_getBufferingParams},
- {"native_setBufferingParams", "(Landroid/media/BufferingParams;)V", (void *)android_media_MediaPlayer2_setBufferingParams},
- {"native_prepare", "()V", (void *)android_media_MediaPlayer2_prepare},
- {"native_start", "()V", (void *)android_media_MediaPlayer2_start},
- {"native_getState", "()I", (void *)android_media_MediaPlayer2_getState},
- {"native_getMetrics", "()Landroid/os/PersistableBundle;", (void *)android_media_MediaPlayer2_native_getMetrics},
- {"native_setPlaybackParams", "(Landroid/media/PlaybackParams;)V", (void *)android_media_MediaPlayer2_setPlaybackParams},
- {"getPlaybackParams", "()Landroid/media/PlaybackParams;", (void *)android_media_MediaPlayer2_getPlaybackParams},
- {"native_setSyncParams", "(Landroid/media/SyncParams;)V", (void *)android_media_MediaPlayer2_setSyncParams},
- {"getSyncParams", "()Landroid/media/SyncParams;", (void *)android_media_MediaPlayer2_getSyncParams},
- {"native_seekTo", "(JI)V", (void *)android_media_MediaPlayer2_seekTo},
- {"native_pause", "()V", (void *)android_media_MediaPlayer2_pause},
- {"getCurrentPosition", "()J", (void *)android_media_MediaPlayer2_getCurrentPosition},
- {"native_getDuration", "(J)J", (void *)android_media_MediaPlayer2_getDuration},
- {"native_release", "()V", (void *)android_media_MediaPlayer2_release},
- {"native_reset", "()V", (void *)android_media_MediaPlayer2_reset},
- {"native_setAudioAttributes", "(Landroid/media/AudioAttributes;)Z", (void *)android_media_MediaPlayer2_setAudioAttributes},
- {"native_getAudioAttributes", "()Landroid/media/AudioAttributes;", (void *)android_media_MediaPlayer2_getAudioAttributes},
- {"setLooping", "(Z)V", (void *)android_media_MediaPlayer2_setLooping},
- {"isLooping", "()Z", (void *)android_media_MediaPlayer2_isLooping},
- {"native_setVolume", "(F)V", (void *)android_media_MediaPlayer2_setVolume},
- {"native_invoke", "([B)[B", (void *)android_media_MediaPlayer2_invoke},
- {"native_init", "()V", (void *)android_media_MediaPlayer2_native_init},
- {"native_setup", "(ILjava/lang/Object;)V", (void *)android_media_MediaPlayer2_native_setup},
- {"native_finalize", "()V", (void *)android_media_MediaPlayer2_native_finalize},
- {"getAudioSessionId", "()I", (void *)android_media_MediaPlayer2_getAudioSessionId},
- {"native_setAudioSessionId", "(I)V", (void *)android_media_MediaPlayer2_setAudioSessionId},
- {"native_setAuxEffectSendLevel", "(F)V", (void *)android_media_MediaPlayer2_setAuxEffectSendLevel},
- {"native_attachAuxEffect", "(I)V", (void *)android_media_MediaPlayer2_attachAuxEffect},
- // Modular DRM
- { "native_prepareDrm", "(J[B[B)V", (void *)android_media_MediaPlayer2_prepareDrm },
- { "native_releaseDrm", "(J)V", (void *)android_media_MediaPlayer2_releaseDrm },
-
- // AudioRouting
- {"native_setPreferredDevice", "(Landroid/media/AudioDeviceInfo;)Z", (void *)android_media_MediaPlayer2_setPreferredDevice},
- {"getRoutedDevice", "()Landroid/media/AudioDeviceInfo;", (void *)android_media_MediaPlayer2_getRoutedDevice},
- {"native_addDeviceCallback", "(Landroid/media/RoutingDelegate;)V", (void *)android_media_MediaPlayer2_addDeviceCallback},
- {"native_removeDeviceCallback", "(Landroid/media/AudioRouting$OnRoutingChangedListener;)V",
- (void *)android_media_MediaPlayer2_removeDeviceCallback},
-
- // StreamEventCallback for JAudioTrack
- {"native_stream_event_onTearDown", "(JJ)V", (void *)android_media_MediaPlayer2_native_on_tear_down},
- {"native_stream_event_onStreamPresentationEnd", "(JJ)V", (void *)android_media_MediaPlayer2_native_on_stream_presentation_end},
- {"native_stream_event_onStreamDataRequest", "(JJJ)V", (void *)android_media_MediaPlayer2_native_on_stream_data_request},
-};
-
-// This function only registers the native methods
-static int register_android_media_MediaPlayer2(JNIEnv *env)
-{
- return jniRegisterNativeMethods(env, "android/media/MediaPlayer2", gMethods, NELEM(gMethods));
-}
-
-jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
-{
- JNIEnv* env = NULL;
- jint result = -1;
-
- if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
- ALOGE("ERROR: GetEnv failed\n");
- goto bail;
- }
- assert(env != NULL);
-
- if (register_android_media_MediaPlayer2(env) < 0) {
- ALOGE("ERROR: MediaPlayer2 native registration failed\n");
- goto bail;
- }
-
- JavaVMHelper::setJavaVM(vm);
-
- /* success -- return valid version number */
- result = JNI_VERSION_1_4;
-
-bail:
- return result;
-}
-
-// KTHXBYE
diff --git a/media/proto/Android.bp b/media/proto/Android.bp
deleted file mode 100644
index 2dc0d579c0da..000000000000
--- a/media/proto/Android.bp
+++ /dev/null
@@ -1,20 +0,0 @@
-java_library_static {
- name: "mediaplayer2-protos",
- host_supported: true,
- proto: {
- type: "lite",
- },
- srcs: ["mediaplayer2.proto"],
- jarjar_rules: "jarjar-rules.txt",
- sdk_version: "28",
-}
-
-cc_library_static {
- name: "libmediaplayer2-protos",
- host_supported: true,
- proto: {
- export_proto_headers: true,
- type: "lite",
- },
- srcs: ["mediaplayer2.proto"],
-}
diff --git a/media/proto/jarjar-rules.txt b/media/proto/jarjar-rules.txt
deleted file mode 100644
index e73f86dddac1..000000000000
--- a/media/proto/jarjar-rules.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-rule com.google.protobuf.** android.media.protobuf.@1
-
diff --git a/media/proto/mediaplayer2.proto b/media/proto/mediaplayer2.proto
deleted file mode 100644
index 6287d6cd326d..000000000000
--- a/media/proto/mediaplayer2.proto
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2018 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.
- */
-
-syntax = "proto2";
-
-option optimize_for = LITE_RUNTIME;
-
-// C++ namespace: android::media:MediaPlayer2Proto:
-package android.media.MediaPlayer2Proto;
-
-option java_package = "android.media";
-option java_outer_classname = "MediaPlayer2Proto";
-
-message Value {
- // The kind of value.
- oneof kind {
- // Represents a boolean value.
- bool bool_value = 1;
- // Represents an int32 value.
- int32 int32_value = 2;
- // Represents an uint32 value.
- uint32 uint32_value = 3;
- // Represents an int64 value.
- int64 int64_value = 4;
- // Represents an uint64 value.
- uint64 uint64_value = 5;
- // Represents a float value.
- double float_value = 6;
- // Represents a double value.
- double double_value = 7;
- // Represents a string value.
- string string_value = 8;
- // Represents a bytes value.
- bytes bytes_value = 9;
- }
-}
-
-message PlayerMessage {
- repeated Value values = 1;
-}
diff --git a/packages/BackupEncryption/Android.bp b/packages/BackupEncryption/Android.bp
index 9bcd677538eb..342d796de402 100644
--- a/packages/BackupEncryption/Android.bp
+++ b/packages/BackupEncryption/Android.bp
@@ -18,6 +18,7 @@ android_app {
name: "BackupEncryption",
srcs: ["src/**/*.java"],
libs: ["backup-encryption-protos"],
+ static_libs: ["backuplib"],
optimize: { enabled: false },
platform_apis: true,
certificate: "platform",
diff --git a/packages/BackupEncryption/AndroidManifest.xml b/packages/BackupEncryption/AndroidManifest.xml
index a705df5a425b..4d174e3b64d6 100644
--- a/packages/BackupEncryption/AndroidManifest.xml
+++ b/packages/BackupEncryption/AndroidManifest.xml
@@ -20,5 +20,14 @@
package="com.android.server.backup.encryption"
android:sharedUserId="android.uid.system" >
- <application android:allowBackup="false" />
+ <application android:allowBackup="false" >
+ <!-- This service does not need to be exported because it shares uid with the system server
+ which is the only client. -->
+ <service android:name=".BackupEncryptionService"
+ android:exported="false">
+ <intent-filter>
+ <action android:name="android.encryption.BACKUP_ENCRYPTION" />
+ </intent-filter>
+ </service>
+ </application>
</manifest>
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java
new file mode 100644
index 000000000000..84fb0e62dbca
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.encryption.transport.IntermediateEncryptingTransport;
+import com.android.server.backup.encryption.transport.IntermediateEncryptingTransportManager;
+
+/**
+ * This service provides encryption of backup data. For an intent used to bind to this service, it
+ * provides an {@link IntermediateEncryptingTransport} which is an implementation of {@link
+ * IBackupTransport} that encrypts (or decrypts) the data when sending it (or receiving it) from the
+ * real {@link IBackupTransport}.
+ */
+public class BackupEncryptionService extends Service {
+ public static final String TAG = "BackupEncryption";
+ private static IntermediateEncryptingTransportManager sTransportManager = null;
+
+ @Override
+ public void onCreate() {
+ Log.i(TAG, "onCreate:" + this);
+ if (sTransportManager == null) {
+ Log.i(TAG, "Creating IntermediateEncryptingTransportManager");
+ sTransportManager = new IntermediateEncryptingTransportManager(this);
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ Log.i(TAG, "onDestroy:" + this);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ // TODO (b141536117): Check connection with TransportClient.connect and return null on fail.
+ return sTransportManager.get(intent);
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ sTransportManager.cleanup(intent);
+ return false;
+ }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java
new file mode 100644
index 000000000000..3d3fb552bb58
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.chunking;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+import static com.android.internal.util.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunk.ChunkListingMap;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Writes batches of {@link EncryptedChunk} to a diff script, and generates the associated {@link
+ * ChunksMetadataProto.ChunkListing} and {@link ChunksMetadataProto.ChunkOrdering}.
+ */
+public class BackupFileBuilder {
+ private static final String TAG = "BackupFileBuilder";
+
+ private static final int BYTES_PER_KILOBYTE = 1024;
+
+ private final BackupWriter mBackupWriter;
+ private final EncryptedChunkEncoder mEncryptedChunkEncoder;
+ private final ChunkListingMap mOldChunkListing;
+ private final ChunksMetadataProto.ChunkListing mNewChunkListing;
+ private final ChunksMetadataProto.ChunkOrdering mChunkOrdering;
+ private final List<ChunksMetadataProto.Chunk> mKnownChunks = new ArrayList<>();
+ private final List<Integer> mKnownStarts = new ArrayList<>();
+ private final Map<ChunkHash, Long> mChunkStartPositions;
+
+ private long mNewChunksSizeBytes;
+ private boolean mFinished;
+
+ /**
+ * Constructs a new instance which writes raw data to the given {@link OutputStream}, without
+ * generating a diff.
+ *
+ * <p>This class never closes the output stream.
+ */
+ public static BackupFileBuilder createForNonIncremental(OutputStream outputStream) {
+ return new BackupFileBuilder(
+ new RawBackupWriter(outputStream), new ChunksMetadataProto.ChunkListing());
+ }
+
+ /**
+ * Constructs a new instance which writes a diff script to the given {@link OutputStream} using
+ * a {@link SingleStreamDiffScriptWriter}.
+ *
+ * <p>This class never closes the output stream.
+ *
+ * @param oldChunkListing against which the diff will be generated.
+ */
+ public static BackupFileBuilder createForIncremental(
+ OutputStream outputStream, ChunksMetadataProto.ChunkListing oldChunkListing) {
+ return new BackupFileBuilder(
+ DiffScriptBackupWriter.newInstance(outputStream), oldChunkListing);
+ }
+
+ private BackupFileBuilder(
+ BackupWriter backupWriter, ChunksMetadataProto.ChunkListing oldChunkListing) {
+ this.mBackupWriter = backupWriter;
+ // TODO(b/77188289): Use InlineLengthsEncryptedChunkEncoder for key-value backups
+ this.mEncryptedChunkEncoder = new LengthlessEncryptedChunkEncoder();
+ this.mOldChunkListing = ChunkListingMap.fromProto(oldChunkListing);
+
+ mNewChunkListing = new ChunksMetadataProto.ChunkListing();
+ mNewChunkListing.cipherType = ChunksMetadataProto.AES_256_GCM;
+ mNewChunkListing.chunkOrderingType = ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+
+ mChunkOrdering = new ChunksMetadataProto.ChunkOrdering();
+ mChunkStartPositions = new HashMap<>();
+ }
+
+ /**
+ * Writes the given chunks to the output stream, and adds them to the new chunk listing and
+ * chunk ordering.
+ *
+ * <p>Sorts the chunks in lexicographical order before writing.
+ *
+ * @param allChunks The hashes of all the chunks, in the order they appear in the plaintext.
+ * @param newChunks A map from hash to {@link EncryptedChunk} containing the new chunks not
+ * present in the previous backup.
+ */
+ public void writeChunks(List<ChunkHash> allChunks, Map<ChunkHash, EncryptedChunk> newChunks)
+ throws IOException {
+ checkState(!mFinished, "Cannot write chunks after flushing.");
+
+ List<ChunkHash> sortedChunks = new ArrayList<>(allChunks);
+ Collections.sort(sortedChunks);
+ for (ChunkHash chunkHash : sortedChunks) {
+ // As we have already included this chunk in the backup file, don't add it again to
+ // deduplicate identical chunks.
+ if (!mChunkStartPositions.containsKey(chunkHash)) {
+ // getBytesWritten() gives us the start of the chunk.
+ mChunkStartPositions.put(chunkHash, mBackupWriter.getBytesWritten());
+
+ writeChunkToFileAndListing(chunkHash, newChunks);
+ }
+ }
+
+ long totalSizeKb = mBackupWriter.getBytesWritten() / BYTES_PER_KILOBYTE;
+ long newChunksSizeKb = mNewChunksSizeBytes / BYTES_PER_KILOBYTE;
+ Slog.d(
+ TAG,
+ "Total backup size: "
+ + totalSizeKb
+ + " kb, new chunks size: "
+ + newChunksSizeKb
+ + " kb");
+
+ for (ChunkHash chunkHash : allChunks) {
+ mKnownStarts.add(mChunkStartPositions.get(chunkHash).intValue());
+ }
+ }
+
+ /**
+ * Returns a new listing for all of the chunks written so far, setting the given fingerprint
+ * mixer salt (this overrides the {@link ChunksMetadataProto.ChunkListing#fingerprintMixerSalt}
+ * in the old {@link ChunksMetadataProto.ChunkListing} passed into the
+ * {@link #BackupFileBuilder).
+ */
+ public ChunksMetadataProto.ChunkListing getNewChunkListing(
+ @Nullable byte[] fingerprintMixerSalt) {
+ // TODO: b/141537803 Add check to ensure this is called only once per instance
+ mNewChunkListing.fingerprintMixerSalt =
+ fingerprintMixerSalt != null
+ ? Arrays.copyOf(fingerprintMixerSalt, fingerprintMixerSalt.length)
+ : new byte[0];
+ mNewChunkListing.chunks = mKnownChunks.toArray(new ChunksMetadataProto.Chunk[0]);
+ return mNewChunkListing;
+ }
+
+ /** Returns a new ordering for all of the chunks written so far, setting the given checksum. */
+ public ChunksMetadataProto.ChunkOrdering getNewChunkOrdering(byte[] checksum) {
+ // TODO: b/141537803 Add check to ensure this is called only once per instance
+ mChunkOrdering.starts = new int[mKnownStarts.size()];
+ for (int i = 0; i < mKnownStarts.size(); i++) {
+ mChunkOrdering.starts[i] = mKnownStarts.get(i).intValue();
+ }
+ mChunkOrdering.checksum = Arrays.copyOf(checksum, checksum.length);
+ return mChunkOrdering;
+ }
+
+ /**
+ * Finishes the backup file by writing the chunk metadata and metadata position.
+ *
+ * <p>Once this is called, calling {@link #writeChunks(List, Map)} will throw {@link
+ * IllegalStateException}.
+ */
+ public void finish(ChunksMetadataProto.ChunksMetadata metadata) throws IOException {
+ checkNotNull(metadata, "Metadata cannot be null");
+
+ long startOfMetadata = mBackupWriter.getBytesWritten();
+ mBackupWriter.writeBytes(ChunksMetadataProto.ChunksMetadata.toByteArray(metadata));
+ mBackupWriter.writeBytes(toByteArray(startOfMetadata));
+
+ mBackupWriter.flush();
+ mFinished = true;
+ }
+
+ /**
+ * Checks if the given chunk hash references an existing chunk or a new chunk, and adds this
+ * chunk to the backup file and new chunk listing.
+ */
+ private void writeChunkToFileAndListing(
+ ChunkHash chunkHash, Map<ChunkHash, EncryptedChunk> newChunks) throws IOException {
+ checkNotNull(chunkHash, "Hash cannot be null");
+
+ if (mOldChunkListing.hasChunk(chunkHash)) {
+ ChunkListingMap.Entry oldChunk = mOldChunkListing.getChunkEntry(chunkHash);
+ mBackupWriter.writeChunk(oldChunk.getStart(), oldChunk.getLength());
+
+ checkArgument(oldChunk.getLength() >= 0, "Chunk must have zero or positive length");
+ addChunk(chunkHash.getHash(), oldChunk.getLength());
+ } else if (newChunks.containsKey(chunkHash)) {
+ EncryptedChunk newChunk = newChunks.get(chunkHash);
+ mEncryptedChunkEncoder.writeChunkToWriter(mBackupWriter, newChunk);
+ int length = mEncryptedChunkEncoder.getEncodedLengthOfChunk(newChunk);
+ mNewChunksSizeBytes += length;
+
+ checkArgument(length >= 0, "Chunk must have zero or positive length");
+ addChunk(chunkHash.getHash(), length);
+ } else {
+ throw new IllegalArgumentException(
+ "Chunk did not exist in old chunks or new chunks: " + chunkHash);
+ }
+ }
+
+ private void addChunk(byte[] chunkHash, int length) {
+ ChunksMetadataProto.Chunk chunk = new ChunksMetadataProto.Chunk();
+ chunk.hash = Arrays.copyOf(chunkHash, chunkHash.length);
+ chunk.length = length;
+ mKnownChunks.add(chunk);
+ }
+
+ private static byte[] toByteArray(long value) {
+ // Note that this code needs to stay compatible with GWT, which has known
+ // bugs when narrowing byte casts of long values occur.
+ byte[] result = new byte[8];
+ for (int i = 7; i >= 0; i--) {
+ result[i] = (byte) (value & 0xffL);
+ value >>= 8;
+ }
+ return result;
+ }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java
new file mode 100644
index 000000000000..d7f7dc7d0472
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.client;
+
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.util.Map;
+
+/**
+ * Contains methods for communicating with the parts of the backup server relevant to encryption.
+ */
+public interface CryptoBackupServer {
+ /**
+ * Uploads an incremental backup to the server.
+ *
+ * <p>Handles setting up and tearing down the connection.
+ *
+ * @param packageName the package to associate the data with
+ * @param oldDocId the id of the previous backup doc in Drive
+ * @param diffScript containing the actual backup data
+ * @param tertiaryKey the wrapped key used to encrypt this backup
+ * @return the id of the new backup doc in Drive.
+ */
+ String uploadIncrementalBackup(
+ String packageName,
+ String oldDocId,
+ byte[] diffScript,
+ WrappedKeyProto.WrappedKey tertiaryKey);
+
+ /**
+ * Uploads non-incremental backup to the server.
+ *
+ * <p>Handles setting up and tearing down the connection.
+ *
+ * @param packageName the package to associate the data with
+ * @param data the actual backup data
+ * @param tertiaryKey the wrapped key used to encrypt this backup
+ * @return the id of the new backup doc in Drive.
+ */
+ String uploadNonIncrementalBackup(
+ String packageName, byte[] data, WrappedKeyProto.WrappedKey tertiaryKey);
+
+ /**
+ * Sets the alias of the active secondary key. This is the alias used to refer to the key in the
+ * {@link java.security.KeyStore}. It is also used to key storage for tertiary keys on the
+ * backup server. Also has to upload all existing tertiary keys, wrapped with the new key.
+ *
+ * @param keyAlias The ID of the secondary key.
+ * @param tertiaryKeys The tertiary keys, wrapped with the new secondary key.
+ */
+ void setActiveSecondaryKeyAlias(
+ String keyAlias, Map<String, WrappedKeyProto.WrappedKey> tertiaryKeys);
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java
new file mode 100644
index 000000000000..ef13f23e799d
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java
@@ -0,0 +1,243 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.tasks;
+
+import android.annotation.Nullable;
+import android.annotation.TargetApi;
+import android.os.Build.VERSION_CODES;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.BackupFileBuilder;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.ShortBufferException;
+import javax.crypto.spec.GCMParameterSpec;
+
+/**
+ * Task which reads encrypted chunks from a {@link BackupEncrypter}, builds a backup file and
+ * uploads it to the server.
+ */
+@TargetApi(VERSION_CODES.P)
+public class EncryptedBackupTask {
+ private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+ private static final int GCM_NONCE_LENGTH_BYTES = 12;
+ private static final int GCM_TAG_LENGTH_BYTES = 16;
+ private static final int BITS_PER_BYTE = 8;
+
+ private static final String TAG = "EncryptedBackupTask";
+
+ private final CryptoBackupServer mCryptoBackupServer;
+ private final SecureRandom mSecureRandom;
+ private final String mPackageName;
+ private final ByteArrayOutputStream mBackupDataOutput;
+ private final BackupEncrypter mBackupEncrypter;
+ private final AtomicBoolean mCancelled;
+
+ /** Creates a new instance which reads data from the given input stream. */
+ public EncryptedBackupTask(
+ CryptoBackupServer cryptoBackupServer,
+ SecureRandom secureRandom,
+ String packageName,
+ BackupEncrypter backupEncrypter) {
+ mCryptoBackupServer = cryptoBackupServer;
+ mSecureRandom = secureRandom;
+ mPackageName = packageName;
+ mBackupEncrypter = backupEncrypter;
+
+ mBackupDataOutput = new ByteArrayOutputStream();
+ mCancelled = new AtomicBoolean(false);
+ }
+
+ /**
+ * Creates a non-incremental backup file and uploads it to the server.
+ *
+ * @param fingerprintMixerSalt Fingerprint mixer salt used for content-defined chunking during a
+ * full backup. May be {@code null} for a key-value backup.
+ */
+ public ChunksMetadataProto.ChunkListing performNonIncrementalBackup(
+ SecretKey tertiaryKey,
+ WrappedKeyProto.WrappedKey wrappedTertiaryKey,
+ @Nullable byte[] fingerprintMixerSalt)
+ throws IOException, GeneralSecurityException {
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ performBackup(
+ tertiaryKey,
+ fingerprintMixerSalt,
+ BackupFileBuilder.createForNonIncremental(mBackupDataOutput),
+ new HashSet<>());
+
+ throwIfCancelled();
+
+ newChunkListing.documentId =
+ mCryptoBackupServer.uploadNonIncrementalBackup(
+ mPackageName, mBackupDataOutput.toByteArray(), wrappedTertiaryKey);
+
+ return newChunkListing;
+ }
+
+ /** Creates an incremental backup file and uploads it to the server. */
+ public ChunksMetadataProto.ChunkListing performIncrementalBackup(
+ SecretKey tertiaryKey,
+ WrappedKeyProto.WrappedKey wrappedTertiaryKey,
+ ChunksMetadataProto.ChunkListing oldChunkListing)
+ throws IOException, GeneralSecurityException {
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ performBackup(
+ tertiaryKey,
+ oldChunkListing.fingerprintMixerSalt,
+ BackupFileBuilder.createForIncremental(mBackupDataOutput, oldChunkListing),
+ getChunkHashes(oldChunkListing));
+
+ throwIfCancelled();
+
+ String oldDocumentId = oldChunkListing.documentId;
+ Slog.v(TAG, "Old doc id: " + oldDocumentId);
+
+ newChunkListing.documentId =
+ mCryptoBackupServer.uploadIncrementalBackup(
+ mPackageName,
+ oldDocumentId,
+ mBackupDataOutput.toByteArray(),
+ wrappedTertiaryKey);
+ return newChunkListing;
+ }
+
+ /**
+ * Signals to the task that the backup has been cancelled. If the upload has not yet started
+ * then the task will not upload any data to the server or save the new chunk listing.
+ */
+ public void cancel() {
+ mCancelled.getAndSet(true);
+ }
+
+ private void throwIfCancelled() {
+ if (mCancelled.get()) {
+ throw new CancellationException("EncryptedBackupTask was cancelled");
+ }
+ }
+
+ private ChunksMetadataProto.ChunkListing performBackup(
+ SecretKey tertiaryKey,
+ @Nullable byte[] fingerprintMixerSalt,
+ BackupFileBuilder backupFileBuilder,
+ Set<ChunkHash> existingChunkHashes)
+ throws IOException, GeneralSecurityException {
+ BackupEncrypter.Result result =
+ mBackupEncrypter.backup(tertiaryKey, fingerprintMixerSalt, existingChunkHashes);
+ backupFileBuilder.writeChunks(result.getAllChunks(), buildChunkMap(result.getNewChunks()));
+
+ ChunksMetadataProto.ChunkOrdering chunkOrdering =
+ backupFileBuilder.getNewChunkOrdering(result.getDigest());
+ backupFileBuilder.finish(buildMetadata(tertiaryKey, chunkOrdering));
+
+ return backupFileBuilder.getNewChunkListing(fingerprintMixerSalt);
+ }
+
+ /** Returns a set containing the hashes of every chunk in the given listing. */
+ private static Set<ChunkHash> getChunkHashes(ChunksMetadataProto.ChunkListing chunkListing) {
+ Set<ChunkHash> hashes = new HashSet<>();
+ for (ChunksMetadataProto.Chunk chunk : chunkListing.chunks) {
+ hashes.add(new ChunkHash(chunk.hash));
+ }
+ return hashes;
+ }
+
+ /** Returns a map from chunk hash to chunk containing every chunk in the given list. */
+ private static Map<ChunkHash, EncryptedChunk> buildChunkMap(List<EncryptedChunk> chunks) {
+ Map<ChunkHash, EncryptedChunk> chunkMap = new HashMap<>();
+ for (EncryptedChunk chunk : chunks) {
+ chunkMap.put(chunk.key(), chunk);
+ }
+ return chunkMap;
+ }
+
+ private ChunksMetadataProto.ChunksMetadata buildMetadata(
+ SecretKey tertiaryKey, ChunksMetadataProto.ChunkOrdering chunkOrdering)
+ throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
+ InvalidAlgorithmParameterException, NoSuchAlgorithmException,
+ ShortBufferException, NoSuchPaddingException {
+ ChunksMetadataProto.ChunksMetadata metaData = new ChunksMetadataProto.ChunksMetadata();
+ metaData.cipherType = ChunksMetadataProto.AES_256_GCM;
+ metaData.checksumType = ChunksMetadataProto.SHA_256;
+ metaData.chunkOrdering = encryptChunkOrdering(tertiaryKey, chunkOrdering);
+ return metaData;
+ }
+
+ private byte[] encryptChunkOrdering(
+ SecretKey tertiaryKey, ChunksMetadataProto.ChunkOrdering chunkOrdering)
+ throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
+ NoSuchPaddingException, NoSuchAlgorithmException,
+ InvalidAlgorithmParameterException, ShortBufferException {
+ Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+
+ byte[] nonce = generateNonce();
+
+ cipher.init(
+ Cipher.ENCRYPT_MODE,
+ tertiaryKey,
+ new GCMParameterSpec(GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE, nonce));
+
+ byte[] orderingBytes = ChunksMetadataProto.ChunkOrdering.toByteArray(chunkOrdering);
+ // We prepend the nonce to the ordering.
+ byte[] output =
+ Arrays.copyOf(
+ nonce,
+ GCM_NONCE_LENGTH_BYTES + orderingBytes.length + GCM_TAG_LENGTH_BYTES);
+
+ cipher.doFinal(
+ orderingBytes,
+ /*inputOffset=*/ 0,
+ /*inputLen=*/ orderingBytes.length,
+ output,
+ /*outputOffset=*/ GCM_NONCE_LENGTH_BYTES);
+
+ return output;
+ }
+
+ private byte[] generateNonce() {
+ byte[] nonce = new byte[GCM_NONCE_LENGTH_BYTES];
+ mSecureRandom.nextBytes(nonce);
+ return nonce;
+ }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java
new file mode 100644
index 000000000000..d20cd4c07f88
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.tasks;
+
+import static com.android.internal.util.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupDataInput;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkEncryptor;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.kv.KeyValueListingBuilder;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.SecretKey;
+
+/**
+ * Reads key value backup data from an input, converts each pair into a chunk and encrypts the
+ * chunks.
+ *
+ * <p>The caller should pass in the key value listing from the previous backup, if there is one.
+ * This class emits chunks for both existing and new pairs, using the provided listing to
+ * determine the hashes of pairs that already exist. During the backup it computes the new listing,
+ * which the caller should store on disk and pass in at the start of the next backup.
+ *
+ * <p>Also computes the message digest, which is {@code SHA-256(chunk hashes sorted
+ * lexicographically)}.
+ */
+public class KvBackupEncrypter implements BackupEncrypter {
+ private final BackupDataInput mBackupDataInput;
+
+ private KeyValueListingProto.KeyValueListing mOldKeyValueListing;
+ @Nullable private KeyValueListingBuilder mNewKeyValueListing;
+
+ /**
+ * Constructs a new instance which reads data from the given input.
+ *
+ * <p>By default this performs non-incremental backup, call {@link #setOldKeyValueListing} to
+ * perform incremental backup.
+ */
+ public KvBackupEncrypter(BackupDataInput backupDataInput) {
+ mBackupDataInput = backupDataInput;
+ mOldKeyValueListing = KeyValueListingBuilder.emptyListing();
+ }
+
+ /** Sets the old listing to perform incremental backup against. */
+ public void setOldKeyValueListing(KeyValueListingProto.KeyValueListing oldKeyValueListing) {
+ mOldKeyValueListing = oldKeyValueListing;
+ }
+
+ @Override
+ public Result backup(
+ SecretKey secretKey,
+ @Nullable byte[] unusedFingerprintMixerSalt,
+ Set<ChunkHash> unusedExistingChunks)
+ throws IOException, GeneralSecurityException {
+ ChunkHasher chunkHasher = new ChunkHasher(secretKey);
+ ChunkEncryptor chunkEncryptor = new ChunkEncryptor(secretKey, new SecureRandom());
+ mNewKeyValueListing = new KeyValueListingBuilder();
+ List<ChunkHash> allChunks = new ArrayList<>();
+ List<EncryptedChunk> newChunks = new ArrayList<>();
+
+ Map<String, ChunkHash> existingChunksToReuse = buildPairMap(mOldKeyValueListing);
+
+ while (mBackupDataInput.readNextHeader()) {
+ String key = mBackupDataInput.getKey();
+ Optional<byte[]> value = readEntireValue(mBackupDataInput);
+
+ // As this pair exists in the new backup, we don't need to add it from the previous
+ // backup.
+ existingChunksToReuse.remove(key);
+
+ // If the value is not present then this key has been deleted.
+ if (value.isPresent()) {
+ EncryptedChunk newChunk =
+ createEncryptedChunk(chunkHasher, chunkEncryptor, key, value.get());
+ allChunks.add(newChunk.key());
+ newChunks.add(newChunk);
+ mNewKeyValueListing.addPair(key, newChunk.key());
+ }
+ }
+
+ allChunks.addAll(existingChunksToReuse.values());
+
+ mNewKeyValueListing.addAll(existingChunksToReuse);
+
+ return new Result(allChunks, newChunks, createMessageDigest(allChunks));
+ }
+
+ /**
+ * Returns a listing containing the pairs in the new backup.
+ *
+ * <p>You must call {@link #backup} first.
+ */
+ public KeyValueListingProto.KeyValueListing getNewKeyValueListing() {
+ checkState(mNewKeyValueListing != null, "Must call backup() first");
+ return mNewKeyValueListing.build();
+ }
+
+ private static Map<String, ChunkHash> buildPairMap(
+ KeyValueListingProto.KeyValueListing listing) {
+ Map<String, ChunkHash> map = new HashMap<>();
+ for (KeyValueListingProto.KeyValueEntry entry : listing.entries) {
+ map.put(entry.key, new ChunkHash(entry.hash));
+ }
+ return map;
+ }
+
+ private EncryptedChunk createEncryptedChunk(
+ ChunkHasher chunkHasher, ChunkEncryptor chunkEncryptor, String key, byte[] value)
+ throws InvalidKeyException, IllegalBlockSizeException {
+ KeyValuePairProto.KeyValuePair pair = new KeyValuePairProto.KeyValuePair();
+ pair.key = key;
+ pair.value = Arrays.copyOf(value, value.length);
+
+ byte[] plaintext = KeyValuePairProto.KeyValuePair.toByteArray(pair);
+ return chunkEncryptor.encrypt(chunkHasher.computeHash(plaintext), plaintext);
+ }
+
+ private static byte[] createMessageDigest(List<ChunkHash> allChunks)
+ throws NoSuchAlgorithmException {
+ MessageDigest messageDigest =
+ MessageDigest.getInstance(BackupEncrypter.MESSAGE_DIGEST_ALGORITHM);
+ // TODO:b/141531271 Extract sorted chunks code to utility class
+ List<ChunkHash> sortedChunks = new ArrayList<>(allChunks);
+ Collections.sort(sortedChunks);
+ for (ChunkHash hash : sortedChunks) {
+ messageDigest.update(hash.getHash());
+ }
+ return messageDigest.digest();
+ }
+
+ private static Optional<byte[]> readEntireValue(BackupDataInput input) throws IOException {
+ // A negative data size indicates that this key should be deleted.
+ if (input.getDataSize() < 0) {
+ return Optional.empty();
+ }
+
+ byte[] value = new byte[input.getDataSize()];
+ int bytesRead = 0;
+ while (bytesRead < value.length) {
+ bytesRead += input.readEntityData(value, bytesRead, value.length - bytesRead);
+ }
+ return Optional.of(value);
+ }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java
new file mode 100644
index 000000000000..1d0224d49be7
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.transport;
+
+import static com.android.server.backup.encryption.BackupEncryptionService.TAG;
+
+import android.os.RemoteException;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.transport.DelegatingTransport;
+import com.android.server.backup.transport.TransportClient;
+
+/**
+ * This is an implementation of {@link IBackupTransport} that encrypts (or decrypts) the data when
+ * sending it (or receiving it) from the {@link IBackupTransport} returned by {@link
+ * TransportClient.connect(String)}.
+ */
+public class IntermediateEncryptingTransport extends DelegatingTransport {
+ private final TransportClient mTransportClient;
+ private final Object mConnectLock = new Object();
+ private volatile IBackupTransport mRealTransport;
+
+ @VisibleForTesting
+ IntermediateEncryptingTransport(TransportClient transportClient) {
+ mTransportClient = transportClient;
+ }
+
+ @Override
+ protected IBackupTransport getDelegate() throws RemoteException {
+ if (mRealTransport == null) {
+ connect();
+ }
+ return mRealTransport;
+ }
+
+ private void connect() throws RemoteException {
+ Log.i(TAG, "connecting " + mTransportClient);
+ synchronized (mConnectLock) {
+ if (mRealTransport == null) {
+ mRealTransport = mTransportClient.connect("IntermediateEncryptingTransport");
+ if (mRealTransport == null) {
+ throw new RemoteException("Could not connect: " + mTransportClient);
+ }
+ }
+ }
+ }
+
+ @VisibleForTesting
+ TransportClient getClient() {
+ return mTransportClient;
+ }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java
new file mode 100644
index 000000000000..6e6d571aa3c7
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.transport;
+
+import static com.android.server.backup.encryption.BackupEncryptionService.TAG;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.UserHandle;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.transport.TransportClientManager;
+import com.android.server.backup.transport.TransportStats;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Handles creation and cleanup of {@link IntermediateEncryptingTransport} instances.
+ */
+public class IntermediateEncryptingTransportManager {
+ private static final String CALLER = "IntermediateEncryptingTransportManager";
+ private final TransportClientManager mTransportClientManager;
+ private final Object mTransportsLock = new Object();
+ private final Map<ComponentName, IntermediateEncryptingTransport> mTransports = new HashMap<>();
+
+ @VisibleForTesting
+ IntermediateEncryptingTransportManager(TransportClientManager transportClientManager) {
+ mTransportClientManager = transportClientManager;
+ }
+
+ public IntermediateEncryptingTransportManager(Context context) {
+ this(new TransportClientManager(UserHandle.myUserId(), context, new TransportStats()));
+ }
+
+ /**
+ * Extract the {@link ComponentName} corresponding to the real {@link IBackupTransport}, and
+ * provide a {@link IntermediateEncryptingTransport} which is an implementation of {@link
+ * IBackupTransport} that encrypts (or decrypts) the data when sending it (or receiving it) from
+ * the real {@link IBackupTransport}.
+ * @param intent {@link Intent} created with a call to {@link
+ * TransportClientManager.getEncryptingTransportIntent(ComponentName)}.
+ * @return
+ */
+ public IntermediateEncryptingTransport get(Intent intent) {
+ Intent transportIntent = TransportClientManager.getRealTransportIntent(intent);
+ Log.i(TAG, "get: intent:" + intent + " transportIntent:" + transportIntent);
+ synchronized (mTransportsLock) {
+ return mTransports.computeIfAbsent(transportIntent.getComponent(),
+ c -> create(transportIntent));
+ }
+ }
+
+ /**
+ * Create an instance of {@link IntermediateEncryptingTransport}.
+ */
+ private IntermediateEncryptingTransport create(Intent realTransportIntent) {
+ Log.d(TAG, "create: intent:" + realTransportIntent);
+ return new IntermediateEncryptingTransport(mTransportClientManager.getTransportClient(
+ realTransportIntent.getComponent(), realTransportIntent.getExtras(), CALLER));
+ }
+
+ /**
+ * Cleanup the {@link IntermediateEncryptingTransport} which was created by a call to
+ * {@link #get(Intent)} with this {@link Intent}.
+ */
+ public void cleanup(Intent intent) {
+ Intent transportIntent = TransportClientManager.getRealTransportIntent(intent);
+ Log.i(TAG, "cleanup: intent:" + intent + " transportIntent:" + transportIntent);
+
+ IntermediateEncryptingTransport transport;
+ synchronized (mTransportsLock) {
+ transport = mTransports.remove(transportIntent.getComponent());
+ }
+ if (transport != null) {
+ mTransportClientManager.disposeOfTransportClient(transport.getClient(), CALLER);
+ } else {
+ Log.i(TAG, "Could not find IntermediateEncryptingTransport");
+ }
+ }
+}
diff --git a/packages/BackupEncryption/test/robolectric/Android.bp b/packages/BackupEncryption/test/robolectric/Android.bp
index 4e42ce7366f0..2a36dcf0baba 100644
--- a/packages/BackupEncryption/test/robolectric/Android.bp
+++ b/packages/BackupEncryption/test/robolectric/Android.bp
@@ -16,7 +16,7 @@ android_robolectric_test {
name: "BackupEncryptionRoboTests",
srcs: [
"src/**/*.java",
- ":FrameworksServicesRoboShadows",
+// ":FrameworksServicesRoboShadows",
],
java_resource_dirs: ["config"],
libs: [
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java
new file mode 100644
index 000000000000..590938efe148
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java
@@ -0,0 +1,614 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.chunking;
+
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.AES_256_GCM;
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+import static com.android.server.backup.testing.CryptoTestUtils.newChunk;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static junit.framework.Assert.fail;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.testng.Assert.assertThrows;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.testing.DiffScriptProcessor;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.io.Files;
+import com.google.common.primitives.Bytes;
+import com.google.common.primitives.Longs;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class BackupFileBuilderTest {
+ private static final String TEST_DATA_1 =
+ "I'm already there or close to [T7-9/executive level] in terms of big-picture vision";
+ private static final String TEST_DATA_2 =
+ "I was known for Real Games and should have been brought in for advice";
+ private static final String TEST_DATA_3 =
+ "Pride is rooted in the delusional belief held by all humans in an unchanging self";
+
+ private static final byte[] TEST_FINGERPRINT_MIXER_SALT =
+ Arrays.copyOf(new byte[] {22}, ChunkHash.HASH_LENGTH_BYTES);
+
+ private static final ChunkHash TEST_HASH_1 =
+ new ChunkHash(Arrays.copyOf(new byte[] {0}, EncryptedChunk.KEY_LENGTH_BYTES));
+ private static final ChunkHash TEST_HASH_2 =
+ new ChunkHash(Arrays.copyOf(new byte[] {1}, EncryptedChunk.KEY_LENGTH_BYTES));
+ private static final ChunkHash TEST_HASH_3 =
+ new ChunkHash(Arrays.copyOf(new byte[] {2}, EncryptedChunk.KEY_LENGTH_BYTES));
+
+ private static final byte[] TEST_NONCE =
+ Arrays.copyOf(new byte[] {3}, EncryptedChunk.NONCE_LENGTH_BYTES);
+
+ private static final EncryptedChunk TEST_CHUNK_1 =
+ EncryptedChunk.create(TEST_HASH_1, TEST_NONCE, TEST_DATA_1.getBytes(UTF_8));
+ private static final EncryptedChunk TEST_CHUNK_2 =
+ EncryptedChunk.create(TEST_HASH_2, TEST_NONCE, TEST_DATA_2.getBytes(UTF_8));
+ private static final EncryptedChunk TEST_CHUNK_3 =
+ EncryptedChunk.create(TEST_HASH_3, TEST_NONCE, TEST_DATA_3.getBytes(UTF_8));
+
+ private static final byte[] TEST_CHECKSUM = {1, 2, 3, 4, 5, 6};
+
+ @Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+ private File mOldFile;
+ private ChunksMetadataProto.ChunkListing mOldChunkListing;
+ private EncryptedChunkEncoder mEncryptedChunkEncoder;
+
+ @Before
+ public void setUp() {
+ mEncryptedChunkEncoder = new LengthlessEncryptedChunkEncoder();
+ }
+
+ @Test
+ public void writeChunks_nonIncremental_writesCorrectRawData() throws Exception {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ BackupFileBuilder backupFileBuilder = BackupFileBuilder.createForNonIncremental(output);
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+ getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+
+ byte[] actual = output.toByteArray();
+ byte[] expected =
+ Bytes.concat(
+ TEST_CHUNK_1.nonce(),
+ TEST_CHUNK_1.encryptedBytes(),
+ TEST_CHUNK_2.nonce(),
+ TEST_CHUNK_2.encryptedBytes());
+ assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+ }
+
+ @Test
+ public void writeChunks_nonIncrementalWithDuplicates_writesEachChunkOnlyOnce()
+ throws Exception {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ BackupFileBuilder backupFileBuilder = BackupFileBuilder.createForNonIncremental(output);
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_1),
+ getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+
+ byte[] actual = output.toByteArray();
+ byte[] expected =
+ Bytes.concat(
+ TEST_CHUNK_1.nonce(),
+ TEST_CHUNK_1.encryptedBytes(),
+ TEST_CHUNK_2.nonce(),
+ TEST_CHUNK_2.encryptedBytes());
+ assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+ }
+
+ @Test
+ public void writeChunks_incremental_writesParsableDiffScript() throws Exception {
+ // We will insert chunk 2 in between chunks 1 and 3.
+ setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+ ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(diffOutputStream, mOldChunkListing);
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+ getNewChunkMap(TEST_HASH_2));
+ backupFileBuilder.finish(getTestMetadata());
+
+ byte[] actual =
+ stripMetadataAndPositionFromOutput(parseDiffScript(diffOutputStream.toByteArray()));
+ byte[] expected =
+ Bytes.concat(
+ TEST_CHUNK_1.nonce(),
+ TEST_CHUNK_1.encryptedBytes(),
+ TEST_CHUNK_2.nonce(),
+ TEST_CHUNK_2.encryptedBytes(),
+ TEST_CHUNK_3.nonce(),
+ TEST_CHUNK_3.encryptedBytes());
+ assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+ }
+
+ @Test
+ public void writeChunks_incrementalWithDuplicates_writesEachChunkOnlyOnce() throws Exception {
+ // We will insert chunk 2 twice in between chunks 1 and 3.
+ setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+ ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(diffOutputStream, mOldChunkListing);
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_2, TEST_HASH_3),
+ getNewChunkMap(TEST_HASH_2));
+ backupFileBuilder.finish(getTestMetadata());
+
+ byte[] actual =
+ stripMetadataAndPositionFromOutput(parseDiffScript(diffOutputStream.toByteArray()));
+ byte[] expected =
+ Bytes.concat(
+ TEST_CHUNK_1.nonce(),
+ TEST_CHUNK_1.encryptedBytes(),
+ TEST_CHUNK_2.nonce(),
+ TEST_CHUNK_2.encryptedBytes(),
+ TEST_CHUNK_3.nonce(),
+ TEST_CHUNK_3.encryptedBytes());
+ assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+ }
+
+ @Test
+ public void writeChunks_writesChunksInOrderOfHash() throws Exception {
+ setUpOldBackupWithChunks(ImmutableList.of());
+ ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(diffOutputStream, mOldChunkListing);
+
+ // Write chunks out of order.
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_2, TEST_HASH_1),
+ getNewChunkMap(TEST_HASH_2, TEST_HASH_1));
+ backupFileBuilder.finish(getTestMetadata());
+
+ byte[] actual =
+ stripMetadataAndPositionFromOutput(parseDiffScript(diffOutputStream.toByteArray()));
+ byte[] expected =
+ Bytes.concat(
+ TEST_CHUNK_1.nonce(),
+ TEST_CHUNK_1.encryptedBytes(),
+ TEST_CHUNK_2.nonce(),
+ TEST_CHUNK_2.encryptedBytes());
+ assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+ }
+
+ @Test
+ public void writeChunks_alreadyFlushed_throwsException() throws Exception {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+ backupFileBuilder.finish(getTestMetadata());
+
+ assertThrows(
+ IllegalStateException.class,
+ () -> backupFileBuilder.writeChunks(ImmutableList.of(), getNewChunkMap()));
+ }
+
+ @Test
+ public void getNewChunkListing_hasChunksInOrderOfKey() throws Exception {
+ // We will insert chunk 2 in between chunks 1 and 3.
+ setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ // Write chunks out of order.
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_3, TEST_HASH_2),
+ getNewChunkMap(TEST_HASH_2));
+ backupFileBuilder.finish(getTestMetadata());
+
+ ChunksMetadataProto.ChunkListing expected = expectedChunkListing();
+ ChunksMetadataProto.ChunkListing actual =
+ backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+ assertListingsEqual(actual, expected);
+ }
+
+ @Test
+ public void getNewChunkListing_writeChunksInTwoBatches_returnsListingContainingAllChunks()
+ throws Exception {
+ // We will insert chunk 2 in between chunks 1 and 3.
+ setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2), getNewChunkMap(TEST_HASH_2));
+ backupFileBuilder.writeChunks(ImmutableList.of(TEST_HASH_3), getNewChunkMap(TEST_HASH_2));
+ backupFileBuilder.finish(getTestMetadata());
+
+ ChunksMetadataProto.ChunkListing expected = expectedChunkListing();
+ ChunksMetadataProto.ChunkListing actual =
+ backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+ assertListingsEqual(actual, expected);
+ }
+
+ @Test
+ public void getNewChunkListing_writeDuplicateChunks_writesEachChunkOnlyOnce() throws Exception {
+ // We will append [2][3][3][2] onto [1].
+ setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1));
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+ getNewChunkMap(TEST_HASH_3, TEST_HASH_2));
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_3, TEST_HASH_2),
+ getNewChunkMap(TEST_HASH_3, TEST_HASH_2));
+ backupFileBuilder.finish(getTestMetadata());
+
+ ChunksMetadataProto.ChunkListing expected = expectedChunkListing();
+ ChunksMetadataProto.ChunkListing actual =
+ backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+ assertListingsEqual(actual, expected);
+ }
+
+ @Test
+ public void getNewChunkListing_nonIncrementalWithNoSalt_doesNotThrowOnSerialisation() {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+ // Does not throw.
+ ChunksMetadataProto.ChunkListing.toByteArray(newChunkListing);
+ }
+
+ @Test
+ public void getNewChunkListing_incrementalWithNoSalt_doesNotThrowOnSerialisation()
+ throws Exception {
+
+ setUpOldBackupWithChunks(ImmutableList.of());
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+ // Does not throw.
+ ChunksMetadataProto.ChunkListing.toByteArray(newChunkListing);
+ }
+
+ @Test
+ public void getNewChunkListing_nonIncrementalWithNoSalt_hasEmptySalt() {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+ assertThat(newChunkListing.fingerprintMixerSalt).isEmpty();
+ }
+
+ @Test
+ public void getNewChunkListing_incrementalWithNoSalt_hasEmptySalt() throws Exception {
+ setUpOldBackupWithChunks(ImmutableList.of());
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+ assertThat(newChunkListing.fingerprintMixerSalt).isEmpty();
+ }
+
+ @Test
+ public void getNewChunkListing_nonIncrementalWithSalt_hasGivenSalt() {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+
+ assertThat(newChunkListing.fingerprintMixerSalt).isEqualTo(TEST_FINGERPRINT_MIXER_SALT);
+ }
+
+ @Test
+ public void getNewChunkListing_incrementalWithSalt_hasGivenSalt() throws Exception {
+ setUpOldBackupWithChunks(ImmutableList.of());
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+
+ assertThat(newChunkListing.fingerprintMixerSalt).isEqualTo(TEST_FINGERPRINT_MIXER_SALT);
+ }
+
+ @Test
+ public void getNewChunkListing_nonIncremental_hasCorrectCipherTypeAndChunkOrderingType() {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+ assertThat(newChunkListing.cipherType).isEqualTo(ChunksMetadataProto.AES_256_GCM);
+ assertThat(newChunkListing.chunkOrderingType)
+ .isEqualTo(ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED);
+ }
+
+ @Test
+ public void getNewChunkListing_incremental_hasCorrectCipherTypeAndChunkOrderingType()
+ throws Exception {
+ setUpOldBackupWithChunks(ImmutableList.of());
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), mOldChunkListing);
+
+ ChunksMetadataProto.ChunkListing newChunkListing =
+ backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+ assertThat(newChunkListing.cipherType).isEqualTo(ChunksMetadataProto.AES_256_GCM);
+ assertThat(newChunkListing.chunkOrderingType)
+ .isEqualTo(ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED);
+ }
+
+ @Test
+ public void getNewChunkOrdering_chunksHaveCorrectStartPositions() throws Exception {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+
+ // Write out of order by key to check that ordering is maintained.
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_3, TEST_HASH_2),
+ getNewChunkMap(TEST_HASH_1, TEST_HASH_3, TEST_HASH_2));
+ backupFileBuilder.finish(getTestMetadata());
+
+ ChunksMetadataProto.ChunkOrdering actual =
+ backupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM);
+ // The chunks are listed in the order they are written above, but the start positions are
+ // determined by the order in the encrypted blob (which is lexicographical by key).
+ int chunk1Start = 0;
+ int chunk2Start =
+ chunk1Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_1);
+ int chunk3Start =
+ chunk2Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_2);
+
+ int[] expected = {chunk1Start, chunk3Start, chunk2Start};
+ assertThat(actual.starts.length).isEqualTo(expected.length);
+ for (int i = 0; i < actual.starts.length; i++) {
+ assertThat(expected[i]).isEqualTo(actual.starts[i]);
+ }
+ }
+
+ @Test
+ public void getNewChunkOrdering_duplicateChunks_writesDuplicates() throws Exception {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_2),
+ getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+ backupFileBuilder.writeChunks(
+ ImmutableList.of(TEST_HASH_3, TEST_HASH_3), getNewChunkMap(TEST_HASH_3));
+ backupFileBuilder.finish(getTestMetadata());
+
+ ChunksMetadataProto.ChunkOrdering actual =
+ backupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM);
+ int chunk1Start = 0;
+ int chunk2Start =
+ chunk1Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_1);
+ int chunk3Start =
+ chunk2Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_2);
+
+ int[] expected = {chunk1Start, chunk2Start, chunk2Start, chunk3Start, chunk3Start};
+ assertThat(actual.starts.length).isEqualTo(expected.length);
+ for (int i = 0; i < actual.starts.length; i++) {
+ assertThat(expected[i]).isEqualTo(actual.starts[i]);
+ }
+ }
+
+ @Test
+ public void getNewChunkOrdering_returnsOrderingWithChecksum() throws Exception {
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+
+ backupFileBuilder.writeChunks(ImmutableList.of(TEST_HASH_1), getNewChunkMap(TEST_HASH_1));
+ backupFileBuilder.finish(getTestMetadata());
+
+ ChunksMetadataProto.ChunkOrdering actual =
+ backupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM);
+ assertThat(actual.checksum).isEqualTo(TEST_CHECKSUM);
+ }
+
+ @Test
+ public void finish_writesMetadata() throws Exception {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ BackupFileBuilder builder = BackupFileBuilder.createForNonIncremental(output);
+ ChunksMetadataProto.ChunksMetadata expectedMetadata = getTestMetadata();
+
+ builder.finish(expectedMetadata);
+
+ // The output is [metadata]+[long giving size of metadata].
+ byte[] metadataBytes =
+ Arrays.copyOfRange(output.toByteArray(), 0, output.size() - Long.BYTES);
+ ChunksMetadataProto.ChunksMetadata actualMetadata =
+ ChunksMetadataProto.ChunksMetadata.parseFrom(metadataBytes);
+ assertThat(actualMetadata.checksumType).isEqualTo(ChunksMetadataProto.SHA_256);
+ assertThat(actualMetadata.cipherType).isEqualTo(ChunksMetadataProto.AES_256_GCM);
+ }
+
+ @Test
+ public void finish_writesMetadataPosition() throws Exception {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ BackupFileBuilder builder = BackupFileBuilder.createForNonIncremental(output);
+
+ builder.writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+ getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+ builder.writeChunks(ImmutableList.of(TEST_HASH_3), getNewChunkMap(TEST_HASH_3));
+ builder.finish(getTestMetadata());
+
+ long expectedPosition =
+ (long) mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_1)
+ + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_2)
+ + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_3);
+ long actualPosition =
+ Longs.fromByteArray(
+ Arrays.copyOfRange(
+ output.toByteArray(), output.size() - Long.BYTES, output.size()));
+ assertThat(actualPosition).isEqualTo(expectedPosition);
+ }
+
+ @Test
+ public void finish_flushesOutputStream() throws Exception {
+ OutputStream diffOutputStream = mock(OutputStream.class);
+ BackupFileBuilder backupFileBuilder =
+ BackupFileBuilder.createForIncremental(
+ diffOutputStream, new ChunksMetadataProto.ChunkListing());
+
+ backupFileBuilder.writeChunks(ImmutableList.of(TEST_HASH_1), getNewChunkMap(TEST_HASH_1));
+ diffOutputStream.flush();
+
+ verify(diffOutputStream).flush();
+ }
+
+ private void setUpOldBackupWithChunks(List<EncryptedChunk> chunks) throws Exception {
+ mOldFile = mTemporaryFolder.newFile();
+ ChunksMetadataProto.ChunkListing chunkListing = new ChunksMetadataProto.ChunkListing();
+ chunkListing.fingerprintMixerSalt =
+ Arrays.copyOf(TEST_FINGERPRINT_MIXER_SALT, TEST_FINGERPRINT_MIXER_SALT.length);
+ chunkListing.cipherType = AES_256_GCM;
+ chunkListing.chunkOrderingType = CHUNK_ORDERING_TYPE_UNSPECIFIED;
+
+ List<ChunksMetadataProto.Chunk> knownChunks = new ArrayList<>();
+ try (FileOutputStream outputStream = new FileOutputStream(mOldFile)) {
+ for (EncryptedChunk chunk : chunks) {
+ // Chunks are encoded in the format [nonce]+[data].
+ outputStream.write(chunk.nonce());
+ outputStream.write(chunk.encryptedBytes());
+
+ knownChunks.add(createChunkFor(chunk));
+ }
+
+ outputStream.flush();
+ }
+
+ chunkListing.chunks = knownChunks.toArray(new ChunksMetadataProto.Chunk[0]);
+ mOldChunkListing = chunkListing;
+ }
+
+ private byte[] parseDiffScript(byte[] diffScript) throws Exception {
+ File newFile = mTemporaryFolder.newFile();
+ new DiffScriptProcessor(mOldFile, newFile).process(new ByteArrayInputStream(diffScript));
+ return Files.toByteArray(newFile);
+ }
+
+ private void assertListingsEqual(
+ ChunksMetadataProto.ChunkListing result, ChunksMetadataProto.ChunkListing expected) {
+ assertThat(result.chunks.length).isEqualTo(expected.chunks.length);
+ for (int i = 0; i < result.chunks.length; i++) {
+ assertWithMessage("Chunk " + i)
+ .that(result.chunks[i].length)
+ .isEqualTo(expected.chunks[i].length);
+ assertWithMessage("Chunk " + i)
+ .that(result.chunks[i].hash)
+ .isEqualTo(expected.chunks[i].hash);
+ }
+ }
+
+ private static ImmutableMap<ChunkHash, EncryptedChunk> getNewChunkMap(ChunkHash... hashes) {
+ ImmutableMap.Builder<ChunkHash, EncryptedChunk> builder = ImmutableMap.builder();
+ for (ChunkHash hash : hashes) {
+ if (TEST_HASH_1.equals(hash)) {
+ builder.put(TEST_HASH_1, TEST_CHUNK_1);
+ } else if (TEST_HASH_2.equals(hash)) {
+ builder.put(TEST_HASH_2, TEST_CHUNK_2);
+ } else if (TEST_HASH_3.equals(hash)) {
+ builder.put(TEST_HASH_3, TEST_CHUNK_3);
+ } else {
+ fail("Hash was not recognised: " + hash);
+ }
+ }
+ return builder.build();
+ }
+
+ private static ChunksMetadataProto.ChunksMetadata getTestMetadata() {
+ ChunksMetadataProto.ChunksMetadata metadata = new ChunksMetadataProto.ChunksMetadata();
+ metadata.checksumType = ChunksMetadataProto.SHA_256;
+ metadata.cipherType = AES_256_GCM;
+ return metadata;
+ }
+
+ private static byte[] stripMetadataAndPositionFromOutput(byte[] output) {
+ long metadataStart =
+ Longs.fromByteArray(
+ Arrays.copyOfRange(output, output.length - Long.BYTES, output.length));
+ return Arrays.copyOfRange(output, 0, (int) metadataStart);
+ }
+
+ private ChunksMetadataProto.ChunkListing expectedChunkListing() {
+ ChunksMetadataProto.ChunkListing chunkListing = new ChunksMetadataProto.ChunkListing();
+ chunkListing.fingerprintMixerSalt =
+ Arrays.copyOf(TEST_FINGERPRINT_MIXER_SALT, TEST_FINGERPRINT_MIXER_SALT.length);
+ chunkListing.cipherType = AES_256_GCM;
+ chunkListing.chunkOrderingType = CHUNK_ORDERING_TYPE_UNSPECIFIED;
+ chunkListing.chunks = new ChunksMetadataProto.Chunk[3];
+ chunkListing.chunks[0] = createChunkFor(TEST_CHUNK_1);
+ chunkListing.chunks[1] = createChunkFor(TEST_CHUNK_2);
+ chunkListing.chunks[2] = createChunkFor(TEST_CHUNK_3);
+ return chunkListing;
+ }
+
+ private ChunksMetadataProto.Chunk createChunkFor(EncryptedChunk encryptedChunk) {
+ byte[] chunkHash = encryptedChunk.key().getHash();
+ byte[] hashCopy = Arrays.copyOf(chunkHash, chunkHash.length);
+ return newChunk(hashCopy, mEncryptedChunkEncoder.getEncodedLengthOfChunk(encryptedChunk));
+ }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java
new file mode 100644
index 000000000000..f6914efd6d83
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java
@@ -0,0 +1,397 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.tasks;
+
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.AES_256_GCM;
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.SHA_256;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.BackupFileBuilder;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.chunking.EncryptedChunkEncoder;
+import com.android.server.backup.encryption.chunking.LengthlessEncryptedChunkEncoder;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.TertiaryKeyGenerator;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkListing;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkOrdering;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunksMetadata;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto.WrappedKey;
+import com.android.server.backup.encryption.tasks.BackupEncrypter.Result;
+import com.android.server.backup.testing.CryptoTestUtils;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.protobuf.nano.MessageNano;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.io.OutputStream;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.concurrent.CancellationException;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+
+@Config(shadows = {EncryptedBackupTaskTest.ShadowBackupFileBuilder.class})
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class EncryptedBackupTaskTest {
+
+ private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+ private static final int GCM_NONCE_LENGTH_BYTES = 12;
+ private static final int GCM_TAG_LENGTH_BYTES = 16;
+ private static final int BITS_PER_BYTE = 8;
+
+ private static final byte[] TEST_FINGERPRINT_MIXER_SALT =
+ Arrays.copyOf(new byte[] {22}, ChunkHash.HASH_LENGTH_BYTES);
+
+ private static final byte[] TEST_NONCE =
+ Arrays.copyOf(new byte[] {55}, EncryptedChunk.NONCE_LENGTH_BYTES);
+
+ private static final ChunkHash TEST_HASH_1 =
+ new ChunkHash(Arrays.copyOf(new byte[] {1}, ChunkHash.HASH_LENGTH_BYTES));
+ private static final ChunkHash TEST_HASH_2 =
+ new ChunkHash(Arrays.copyOf(new byte[] {2}, ChunkHash.HASH_LENGTH_BYTES));
+ private static final ChunkHash TEST_HASH_3 =
+ new ChunkHash(Arrays.copyOf(new byte[] {3}, ChunkHash.HASH_LENGTH_BYTES));
+
+ private static final EncryptedChunk TEST_CHUNK_1 =
+ EncryptedChunk.create(TEST_HASH_1, TEST_NONCE, new byte[] {1, 2, 3, 4, 5});
+ private static final EncryptedChunk TEST_CHUNK_2 =
+ EncryptedChunk.create(TEST_HASH_2, TEST_NONCE, new byte[] {6, 7, 8, 9, 10});
+ private static final EncryptedChunk TEST_CHUNK_3 =
+ EncryptedChunk.create(TEST_HASH_3, TEST_NONCE, new byte[] {11, 12, 13, 14, 15});
+
+ private static final byte[] TEST_CHECKSUM = Arrays.copyOf(new byte[] {10}, 258 / 8);
+ private static final String TEST_PACKAGE_NAME = "com.example.package";
+ private static final String TEST_OLD_DOCUMENT_ID = "old_doc_1";
+ private static final String TEST_NEW_DOCUMENT_ID = "new_doc_1";
+
+ @Captor private ArgumentCaptor<ChunksMetadata> mMetadataCaptor;
+
+ @Mock private CryptoBackupServer mCryptoBackupServer;
+ @Mock private BackupEncrypter mBackupEncrypter;
+ @Mock private BackupFileBuilder mBackupFileBuilder;
+
+ private ChunkListing mOldChunkListing;
+ private SecretKey mTertiaryKey;
+ private WrappedKey mWrappedTertiaryKey;
+ private EncryptedChunkEncoder mEncryptedChunkEncoder;
+ private EncryptedBackupTask mTask;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+
+ SecureRandom secureRandom = new SecureRandom();
+ mTertiaryKey = new TertiaryKeyGenerator(secureRandom).generate();
+ mWrappedTertiaryKey = new WrappedKey();
+
+ mEncryptedChunkEncoder = new LengthlessEncryptedChunkEncoder();
+
+ ShadowBackupFileBuilder.sInstance = mBackupFileBuilder;
+
+ mTask =
+ new EncryptedBackupTask(
+ mCryptoBackupServer, secureRandom, TEST_PACKAGE_NAME, mBackupEncrypter);
+ }
+
+ @Test
+ public void performNonIncrementalBackup_performsBackup() throws Exception {
+ setUpWithoutExistingBackup();
+
+ // Chunk listing and ordering don't matter for this test.
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+ when(mCryptoBackupServer.uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), any()))
+ .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+ mTask.performNonIncrementalBackup(
+ mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT);
+
+ verify(mBackupFileBuilder)
+ .writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+ ImmutableMap.of(TEST_HASH_1, TEST_CHUNK_1, TEST_HASH_2, TEST_CHUNK_2));
+ verify(mBackupFileBuilder).finish(any());
+ verify(mCryptoBackupServer)
+ .uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), eq(mWrappedTertiaryKey));
+ }
+
+ @Test
+ public void performIncrementalBackup_performsBackup() throws Exception {
+ setUpWithExistingBackup();
+
+ // Chunk listing and ordering don't matter for this test.
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+ when(mCryptoBackupServer.uploadIncrementalBackup(
+ eq(TEST_PACKAGE_NAME), eq(TEST_OLD_DOCUMENT_ID), any(), any()))
+ .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+ mTask.performIncrementalBackup(mTertiaryKey, mWrappedTertiaryKey, mOldChunkListing);
+
+ verify(mBackupFileBuilder)
+ .writeChunks(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+ ImmutableMap.of(TEST_HASH_2, TEST_CHUNK_2));
+ verify(mBackupFileBuilder).finish(any());
+ verify(mCryptoBackupServer)
+ .uploadIncrementalBackup(
+ eq(TEST_PACKAGE_NAME),
+ eq(TEST_OLD_DOCUMENT_ID),
+ any(),
+ eq(mWrappedTertiaryKey));
+ }
+
+ @Test
+ public void performIncrementalBackup_returnsNewChunkListingWithDocId() throws Exception {
+ setUpWithExistingBackup();
+
+ ChunkListing chunkListingWithoutDocId =
+ CryptoTestUtils.newChunkListingWithoutDocId(
+ TEST_FINGERPRINT_MIXER_SALT,
+ AES_256_GCM,
+ CHUNK_ORDERING_TYPE_UNSPECIFIED,
+ createChunkProtoFor(TEST_HASH_1, TEST_CHUNK_1),
+ createChunkProtoFor(TEST_HASH_2, TEST_CHUNK_2));
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(chunkListingWithoutDocId);
+
+ // Chunk ordering doesn't matter for this test.
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+ when(mCryptoBackupServer.uploadIncrementalBackup(
+ eq(TEST_PACKAGE_NAME), eq(TEST_OLD_DOCUMENT_ID), any(), any()))
+ .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+ ChunkListing actualChunkListing =
+ mTask.performIncrementalBackup(mTertiaryKey, mWrappedTertiaryKey, mOldChunkListing);
+
+ ChunkListing expectedChunkListing = CryptoTestUtils.clone(chunkListingWithoutDocId);
+ expectedChunkListing.documentId = TEST_NEW_DOCUMENT_ID;
+ assertChunkListingsAreEqual(actualChunkListing, expectedChunkListing);
+ }
+
+ @Test
+ public void performNonIncrementalBackup_returnsNewChunkListingWithDocId() throws Exception {
+ setUpWithoutExistingBackup();
+
+ ChunkListing chunkListingWithoutDocId =
+ CryptoTestUtils.newChunkListingWithoutDocId(
+ TEST_FINGERPRINT_MIXER_SALT,
+ AES_256_GCM,
+ CHUNK_ORDERING_TYPE_UNSPECIFIED,
+ createChunkProtoFor(TEST_HASH_1, TEST_CHUNK_1),
+ createChunkProtoFor(TEST_HASH_2, TEST_CHUNK_2));
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(chunkListingWithoutDocId);
+
+ // Chunk ordering doesn't matter for this test.
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+ when(mCryptoBackupServer.uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), any()))
+ .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+ ChunkListing actualChunkListing =
+ mTask.performNonIncrementalBackup(
+ mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT);
+
+ ChunkListing expectedChunkListing = CryptoTestUtils.clone(chunkListingWithoutDocId);
+ expectedChunkListing.documentId = TEST_NEW_DOCUMENT_ID;
+ assertChunkListingsAreEqual(actualChunkListing, expectedChunkListing);
+ }
+
+ @Test
+ public void performNonIncrementalBackup_buildsCorrectChunkMetadata() throws Exception {
+ setUpWithoutExistingBackup();
+
+ // Chunk listing doesn't matter for this test.
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+
+ ChunkOrdering expectedOrdering =
+ CryptoTestUtils.newChunkOrdering(new int[10], TEST_CHECKSUM);
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(expectedOrdering);
+
+ when(mCryptoBackupServer.uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), any()))
+ .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+ mTask.performNonIncrementalBackup(
+ mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT);
+
+ verify(mBackupFileBuilder).finish(mMetadataCaptor.capture());
+
+ ChunksMetadata actualMetadata = mMetadataCaptor.getValue();
+ assertThat(actualMetadata.checksumType).isEqualTo(SHA_256);
+ assertThat(actualMetadata.cipherType).isEqualTo(AES_256_GCM);
+
+ ChunkOrdering actualOrdering = decryptChunkOrdering(actualMetadata.chunkOrdering);
+ assertThat(actualOrdering.checksum).isEqualTo(TEST_CHECKSUM);
+ assertThat(actualOrdering.starts).isEqualTo(expectedOrdering.starts);
+ }
+
+ @Test
+ public void cancel_incrementalBackup_doesNotUploadOrSaveChunkListing() throws Exception {
+ setUpWithExistingBackup();
+
+ // Chunk listing and ordering don't matter for this test.
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+ mTask.cancel();
+ assertThrows(
+ CancellationException.class,
+ () ->
+ mTask.performIncrementalBackup(
+ mTertiaryKey, mWrappedTertiaryKey, mOldChunkListing));
+
+ verify(mCryptoBackupServer, never()).uploadIncrementalBackup(any(), any(), any(), any());
+ verify(mCryptoBackupServer, never()).uploadNonIncrementalBackup(any(), any(), any());
+ }
+
+ @Test
+ public void cancel_nonIncrementalBackup_doesNotUploadOrSaveChunkListing() throws Exception {
+ setUpWithoutExistingBackup();
+
+ // Chunk listing and ordering don't matter for this test.
+ when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+ when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+ mTask.cancel();
+ assertThrows(
+ CancellationException.class,
+ () ->
+ mTask.performNonIncrementalBackup(
+ mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT));
+
+ verify(mCryptoBackupServer, never()).uploadIncrementalBackup(any(), any(), any(), any());
+ verify(mCryptoBackupServer, never()).uploadNonIncrementalBackup(any(), any(), any());
+ }
+
+ /** Sets up a backup of [CHUNK 1][CHUNK 2] with no existing data. */
+ private void setUpWithoutExistingBackup() throws Exception {
+ Result result =
+ new Result(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+ ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_2),
+ TEST_CHECKSUM);
+ when(mBackupEncrypter.backup(any(), eq(TEST_FINGERPRINT_MIXER_SALT), eq(ImmutableSet.of())))
+ .thenReturn(result);
+ }
+
+ /**
+ * Sets up a backup of [CHUNK 1][CHUNK 2][CHUNK 3] where the previous backup contained [CHUNK
+ * 1][CHUNK 3].
+ */
+ private void setUpWithExistingBackup() throws Exception {
+ mOldChunkListing =
+ CryptoTestUtils.newChunkListing(
+ TEST_OLD_DOCUMENT_ID,
+ TEST_FINGERPRINT_MIXER_SALT,
+ AES_256_GCM,
+ CHUNK_ORDERING_TYPE_UNSPECIFIED,
+ createChunkProtoFor(TEST_HASH_1, TEST_CHUNK_1),
+ createChunkProtoFor(TEST_HASH_3, TEST_CHUNK_3));
+
+ Result result =
+ new Result(
+ ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+ ImmutableList.of(TEST_CHUNK_2),
+ TEST_CHECKSUM);
+ when(mBackupEncrypter.backup(
+ any(),
+ eq(TEST_FINGERPRINT_MIXER_SALT),
+ eq(ImmutableSet.of(TEST_HASH_1, TEST_HASH_3))))
+ .thenReturn(result);
+ }
+
+ private ChunksMetadataProto.Chunk createChunkProtoFor(
+ ChunkHash chunkHash, EncryptedChunk encryptedChunk) {
+ return CryptoTestUtils.newChunk(
+ chunkHash, mEncryptedChunkEncoder.getEncodedLengthOfChunk(encryptedChunk));
+ }
+
+ private ChunkOrdering decryptChunkOrdering(byte[] encryptedOrdering) throws Exception {
+ Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+ cipher.init(
+ Cipher.DECRYPT_MODE,
+ mTertiaryKey,
+ new GCMParameterSpec(
+ GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE,
+ encryptedOrdering,
+ /*offset=*/ 0,
+ GCM_NONCE_LENGTH_BYTES));
+ byte[] decrypted =
+ cipher.doFinal(
+ encryptedOrdering,
+ GCM_NONCE_LENGTH_BYTES,
+ encryptedOrdering.length - GCM_NONCE_LENGTH_BYTES);
+ return ChunkOrdering.parseFrom(decrypted);
+ }
+
+ // This method is needed because nano protobuf generated classes dont implmenent
+ // .equals
+ private void assertChunkListingsAreEqual(ChunkListing a, ChunkListing b) {
+ byte[] aBytes = MessageNano.toByteArray(a);
+ byte[] bBytes = MessageNano.toByteArray(b);
+
+ assertThat(aBytes).isEqualTo(bBytes);
+ }
+
+ @Implements(BackupFileBuilder.class)
+ public static class ShadowBackupFileBuilder {
+
+ private static BackupFileBuilder sInstance;
+
+ @Implementation
+ public static BackupFileBuilder createForNonIncremental(OutputStream outputStream) {
+ return sInstance;
+ }
+
+ @Implementation
+ public static BackupFileBuilder createForIncremental(
+ OutputStream outputStream, ChunkListing oldChunkListing) {
+ return sInstance;
+ }
+ }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java
new file mode 100644
index 000000000000..ccfbfa4b25e9
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java
@@ -0,0 +1,287 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.app.backup.BackupDataInput;
+import android.platform.test.annotations.Presubmit;
+import android.util.Pair;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.kv.KeyValueListingBuilder;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto.KeyValueListing;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto.KeyValuePair;
+import com.android.server.backup.encryption.tasks.BackupEncrypter.Result;
+import com.android.server.testing.shadows.DataEntity;
+import com.android.server.testing.shadows.ShadowBackupDataInput;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Ordering;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+import java.security.MessageDigest;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+@Config(shadows = {ShadowBackupDataInput.class})
+public class KvBackupEncrypterTest {
+ private static final String KEY_ALGORITHM = "AES";
+ private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+ private static final int GCM_TAG_LENGTH_BYTES = 16;
+
+ private static final byte[] TEST_TERTIARY_KEY = Arrays.copyOf(new byte[0], 256 / Byte.SIZE);
+ private static final String TEST_KEY_1 = "test_key_1";
+ private static final String TEST_KEY_2 = "test_key_2";
+ private static final String TEST_KEY_3 = "test_key_3";
+ private static final byte[] TEST_VALUE_1 = {10, 11, 12};
+ private static final byte[] TEST_VALUE_2 = {13, 14, 15};
+ private static final byte[] TEST_VALUE_2B = {13, 14, 15, 16};
+ private static final byte[] TEST_VALUE_3 = {16, 17, 18};
+
+ private SecretKey mSecretKey;
+ private ChunkHasher mChunkHasher;
+
+ @Before
+ public void setUp() {
+ mSecretKey = new SecretKeySpec(TEST_TERTIARY_KEY, KEY_ALGORITHM);
+ mChunkHasher = new ChunkHasher(mSecretKey);
+
+ ShadowBackupDataInput.reset();
+ }
+
+ private KvBackupEncrypter createEncrypter(KeyValueListing keyValueListing) {
+ KvBackupEncrypter encrypter = new KvBackupEncrypter(new BackupDataInput(null));
+ encrypter.setOldKeyValueListing(keyValueListing);
+ return encrypter;
+ }
+
+ @Test
+ public void backup_noExistingBackup_encryptsAllPairs() throws Exception {
+ ShadowBackupDataInput.addEntity(TEST_KEY_1, TEST_VALUE_1);
+ ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2);
+
+ KeyValueListing emptyKeyValueListing = new KeyValueListingBuilder().build();
+ ImmutableSet<ChunkHash> emptyExistingChunks = ImmutableSet.of();
+ KvBackupEncrypter encrypter = createEncrypter(emptyKeyValueListing);
+
+ Result result =
+ encrypter.backup(
+ mSecretKey, /*unusedFingerprintMixerSalt=*/ null, emptyExistingChunks);
+
+ assertThat(result.getAllChunks()).hasSize(2);
+ EncryptedChunk chunk1 = result.getNewChunks().get(0);
+ EncryptedChunk chunk2 = result.getNewChunks().get(1);
+ assertThat(chunk1.key()).isEqualTo(getChunkHash(TEST_KEY_1, TEST_VALUE_1));
+ KeyValuePair pair1 = decryptChunk(chunk1);
+ assertThat(pair1.key).isEqualTo(TEST_KEY_1);
+ assertThat(pair1.value).isEqualTo(TEST_VALUE_1);
+ assertThat(chunk2.key()).isEqualTo(getChunkHash(TEST_KEY_2, TEST_VALUE_2));
+ KeyValuePair pair2 = decryptChunk(chunk2);
+ assertThat(pair2.key).isEqualTo(TEST_KEY_2);
+ assertThat(pair2.value).isEqualTo(TEST_VALUE_2);
+ }
+
+ @Test
+ public void backup_existingBackup_encryptsNewAndUpdatedPairs() throws Exception {
+ Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+ // Update key 2 and add the new key 3.
+ ShadowBackupDataInput.reset();
+ ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2B);
+ ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+ KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+ BackupEncrypter.Result secondResult =
+ encrypter.backup(
+ mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+ assertThat(secondResult.getAllChunks()).hasSize(3);
+ assertThat(secondResult.getNewChunks()).hasSize(2);
+ EncryptedChunk newChunk2 = secondResult.getNewChunks().get(0);
+ EncryptedChunk newChunk3 = secondResult.getNewChunks().get(1);
+ assertThat(newChunk2.key()).isEqualTo(getChunkHash(TEST_KEY_2, TEST_VALUE_2B));
+ assertThat(decryptChunk(newChunk2).value).isEqualTo(TEST_VALUE_2B);
+ assertThat(newChunk3.key()).isEqualTo(getChunkHash(TEST_KEY_3, TEST_VALUE_3));
+ assertThat(decryptChunk(newChunk3).value).isEqualTo(TEST_VALUE_3);
+ }
+
+ @Test
+ public void backup_allChunksContainsHashesOfAllChunks() throws Exception {
+ Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+ ShadowBackupDataInput.reset();
+ ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+ KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+ BackupEncrypter.Result secondResult =
+ encrypter.backup(
+ mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+ assertThat(secondResult.getAllChunks())
+ .containsExactly(
+ getChunkHash(TEST_KEY_1, TEST_VALUE_1),
+ getChunkHash(TEST_KEY_2, TEST_VALUE_2),
+ getChunkHash(TEST_KEY_3, TEST_VALUE_3));
+ }
+
+ @Test
+ public void backup_negativeSize_deletesKeyFromExistingBackup() throws Exception {
+ Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+ ShadowBackupDataInput.reset();
+ ShadowBackupDataInput.addEntity(new DataEntity(TEST_KEY_2));
+
+ KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+ Result secondResult =
+ encrypter.backup(
+ mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+ assertThat(secondResult.getAllChunks())
+ .containsExactly(getChunkHash(TEST_KEY_1, TEST_VALUE_1));
+ assertThat(secondResult.getNewChunks()).isEmpty();
+ }
+
+ @Test
+ public void backup_returnsMessageDigestOverChunkHashes() throws Exception {
+ Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+ ShadowBackupDataInput.reset();
+ ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+ KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+ Result secondResult =
+ encrypter.backup(
+ mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+ MessageDigest messageDigest =
+ MessageDigest.getInstance(BackupEncrypter.MESSAGE_DIGEST_ALGORITHM);
+ ImmutableList<ChunkHash> sortedHashes =
+ Ordering.natural()
+ .immutableSortedCopy(
+ ImmutableList.of(
+ getChunkHash(TEST_KEY_1, TEST_VALUE_1),
+ getChunkHash(TEST_KEY_2, TEST_VALUE_2),
+ getChunkHash(TEST_KEY_3, TEST_VALUE_3)));
+ messageDigest.update(sortedHashes.get(0).getHash());
+ messageDigest.update(sortedHashes.get(1).getHash());
+ messageDigest.update(sortedHashes.get(2).getHash());
+ assertThat(secondResult.getDigest()).isEqualTo(messageDigest.digest());
+ }
+
+ @Test
+ public void getNewKeyValueListing_noExistingBackup_returnsCorrectListing() throws Exception {
+ KeyValueListing keyValueListing = runInitialBackupOfPairs1And2().first;
+
+ assertThat(keyValueListing.entries.length).isEqualTo(2);
+ assertThat(keyValueListing.entries[0].key).isEqualTo(TEST_KEY_1);
+ assertThat(keyValueListing.entries[0].hash)
+ .isEqualTo(getChunkHash(TEST_KEY_1, TEST_VALUE_1).getHash());
+ assertThat(keyValueListing.entries[1].key).isEqualTo(TEST_KEY_2);
+ assertThat(keyValueListing.entries[1].hash)
+ .isEqualTo(getChunkHash(TEST_KEY_2, TEST_VALUE_2).getHash());
+ }
+
+ @Test
+ public void getNewKeyValueListing_existingBackup_returnsCorrectListing() throws Exception {
+ Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+ ShadowBackupDataInput.reset();
+ ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2B);
+ ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+ KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+ encrypter.backup(mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+ ImmutableMap<String, ChunkHash> keyValueListing =
+ listingToMap(encrypter.getNewKeyValueListing());
+ assertThat(keyValueListing).hasSize(3);
+ assertThat(keyValueListing)
+ .containsEntry(TEST_KEY_1, getChunkHash(TEST_KEY_1, TEST_VALUE_1));
+ assertThat(keyValueListing)
+ .containsEntry(TEST_KEY_2, getChunkHash(TEST_KEY_2, TEST_VALUE_2B));
+ assertThat(keyValueListing)
+ .containsEntry(TEST_KEY_3, getChunkHash(TEST_KEY_3, TEST_VALUE_3));
+ }
+
+ @Test
+ public void getNewKeyValueChunkListing_beforeBackup_throws() throws Exception {
+ KvBackupEncrypter encrypter = createEncrypter(new KeyValueListing());
+ assertThrows(IllegalStateException.class, encrypter::getNewKeyValueListing);
+ }
+
+ private ImmutableMap<String, ChunkHash> listingToMap(KeyValueListing listing) {
+ // We can't use the ImmutableMap collector directly because it isn't supported in Android
+ // guava.
+ return ImmutableMap.copyOf(
+ Arrays.stream(listing.entries)
+ .collect(
+ Collectors.toMap(
+ entry -> entry.key, entry -> new ChunkHash(entry.hash))));
+ }
+
+ private Pair<KeyValueListing, Set<ChunkHash>> runInitialBackupOfPairs1And2() throws Exception {
+ ShadowBackupDataInput.addEntity(TEST_KEY_1, TEST_VALUE_1);
+ ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2);
+
+ KeyValueListing initialKeyValueListing = new KeyValueListingBuilder().build();
+ ImmutableSet<ChunkHash> initialExistingChunks = ImmutableSet.of();
+ KvBackupEncrypter encrypter = createEncrypter(initialKeyValueListing);
+ Result firstResult =
+ encrypter.backup(
+ mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialExistingChunks);
+
+ return Pair.create(
+ encrypter.getNewKeyValueListing(), ImmutableSet.copyOf(firstResult.getAllChunks()));
+ }
+
+ private ChunkHash getChunkHash(String key, byte[] value) throws Exception {
+ KeyValuePair pair = new KeyValuePair();
+ pair.key = key;
+ pair.value = Arrays.copyOf(value, value.length);
+ return mChunkHasher.computeHash(KeyValuePair.toByteArray(pair));
+ }
+
+ private KeyValuePair decryptChunk(EncryptedChunk encryptedChunk) throws Exception {
+ Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+ cipher.init(
+ Cipher.DECRYPT_MODE,
+ mSecretKey,
+ new GCMParameterSpec(GCM_TAG_LENGTH_BYTES * Byte.SIZE, encryptedChunk.nonce()));
+ byte[] decryptedBytes = cipher.doFinal(encryptedChunk.encryptedBytes());
+ return KeyValuePair.parseFrom(decryptedBytes);
+ }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java
new file mode 100644
index 000000000000..faddb6cf129c
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java
@@ -0,0 +1,256 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.testing;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+/**
+ * To be used as part of a fake backup server. Processes a Scotty diff script.
+ *
+ * <p>A Scotty diff script consists of an ASCII line denoting a command, optionally followed by a
+ * range of bytes. Command format is either
+ *
+ * <ul>
+ * <li>A single 64-bit integer, followed by a new line: this denotes that the given number of
+ * bytes are to follow in the stream. These bytes should be written directly to the new file.
+ * <li>Two 64-bit integers, separated by a hyphen, followed by a new line: this says that the
+ * given range of bytes from the original file ought to be copied into the new file.
+ * </ul>
+ */
+public class DiffScriptProcessor {
+
+ private static final int COPY_BUFFER_SIZE = 1024;
+
+ private static final String READ_MODE = "r";
+ private static final Pattern VALID_COMMAND_PATTERN = Pattern.compile("^\\d+(-\\d+)?$");
+
+ private final File mInput;
+ private final File mOutput;
+ private final long mInputLength;
+
+ /**
+ * A new instance, with {@code input} as previous file, and {@code output} as new file.
+ *
+ * @param input Previous file from which ranges of bytes are to be copied. This file should be
+ * immutable.
+ * @param output Output file, to which the new data should be written.
+ * @throws IllegalArgumentException if input does not exist.
+ */
+ public DiffScriptProcessor(File input, File output) {
+ checkArgument(input.exists(), "input file did not exist.");
+ mInput = input;
+ mInputLength = input.length();
+ mOutput = checkNotNull(output);
+ }
+
+ public void process(InputStream diffScript) throws IOException, MalformedDiffScriptException {
+ RandomAccessFile randomAccessInput = new RandomAccessFile(mInput, READ_MODE);
+
+ try (FileOutputStream outputStream = new FileOutputStream(mOutput)) {
+ while (true) {
+ Optional<String> commandString = readCommand(diffScript);
+ if (!commandString.isPresent()) {
+ return;
+ }
+ Command command = Command.parse(commandString.get());
+
+ if (command.mIsRange) {
+ checkFileRange(command.mCount, command.mLimit);
+ copyRange(randomAccessInput, outputStream, command.mCount, command.mLimit);
+ } else {
+ long bytesCopied = copyBytes(diffScript, outputStream, command.mCount);
+ if (bytesCopied < command.mCount) {
+ throw new MalformedDiffScriptException(
+ String.format(
+ Locale.US,
+ "Command to copy %d bytes from diff script, but only %d"
+ + " bytes available",
+ command.mCount,
+ bytesCopied));
+ }
+ if (diffScript.read() != '\n') {
+ throw new MalformedDiffScriptException("Expected new line after bytes.");
+ }
+ }
+ }
+ }
+ }
+
+ private void checkFileRange(long start, long end) throws MalformedDiffScriptException {
+ if (end < start) {
+ throw new MalformedDiffScriptException(
+ String.format(
+ Locale.US,
+ "Command to copy %d-%d bytes from original file, but %2$d < %1$d.",
+ start,
+ end));
+ }
+
+ if (end >= mInputLength) {
+ throw new MalformedDiffScriptException(
+ String.format(
+ Locale.US,
+ "Command to copy %d-%d bytes from original file, but file is only %d"
+ + " bytes long.",
+ start,
+ end,
+ mInputLength));
+ }
+ }
+
+ /**
+ * Reads a command from the input stream.
+ *
+ * @param inputStream The input.
+ * @return Optional of command, or empty if EOF.
+ */
+ private static Optional<String> readCommand(InputStream inputStream) throws IOException {
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+
+ int b;
+ while (!isEndOfCommand(b = inputStream.read())) {
+ byteArrayOutputStream.write(b);
+ }
+
+ byte[] bytes = byteArrayOutputStream.toByteArray();
+ if (bytes.length == 0) {
+ return Optional.empty();
+ } else {
+ return Optional.of(new String(bytes, UTF_8));
+ }
+ }
+
+ /**
+ * If the given output from {@link InputStream#read()} is the end of a command - i.e., a new
+ * line or the EOF.
+ *
+ * @param b The byte or -1.
+ * @return {@code true} if ends the command.
+ */
+ private static boolean isEndOfCommand(int b) {
+ return b == -1 || b == '\n';
+ }
+
+ /**
+ * Copies {@code n} bytes from {@code inputStream} to {@code outputStream}.
+ *
+ * @return The number of bytes copied.
+ * @throws IOException if there was a problem reading or writing.
+ */
+ private static long copyBytes(InputStream inputStream, OutputStream outputStream, long n)
+ throws IOException {
+ byte[] buffer = new byte[COPY_BUFFER_SIZE];
+ long copied = 0;
+ while (n - copied > COPY_BUFFER_SIZE) {
+ long read = copyBlock(inputStream, outputStream, buffer, COPY_BUFFER_SIZE);
+ if (read <= 0) {
+ return copied;
+ }
+ }
+ while (n - copied > 0) {
+ copied += copyBlock(inputStream, outputStream, buffer, (int) (n - copied));
+ }
+ return copied;
+ }
+
+ private static long copyBlock(
+ InputStream inputStream, OutputStream outputStream, byte[] buffer, int size)
+ throws IOException {
+ int read = inputStream.read(buffer, 0, size);
+ outputStream.write(buffer, 0, read);
+ return read;
+ }
+
+ /**
+ * Copies the given range of bytes from the input file to the output stream.
+ *
+ * @param input The input file.
+ * @param output The output stream.
+ * @param start Start position in the input file.
+ * @param end End position in the output file (inclusive).
+ * @throws IOException if there was a problem reading or writing.
+ */
+ private static void copyRange(RandomAccessFile input, OutputStream output, long start, long end)
+ throws IOException {
+ input.seek(start);
+
+ // Inefficient but obviously correct. If tests become slow, optimize.
+ for (; start <= end; start++) {
+ output.write(input.read());
+ }
+ }
+
+ /** Error thrown for a malformed diff script. */
+ public static class MalformedDiffScriptException extends Exception {
+ public MalformedDiffScriptException(String message) {
+ super(message);
+ }
+ }
+
+ /**
+ * A command telling the processor either to insert n bytes, which follow, or copy n-m bytes
+ * from the original file.
+ */
+ private static class Command {
+ private final long mCount;
+ private final long mLimit;
+ private final boolean mIsRange;
+
+ private Command(long count, long limit, boolean isRange) {
+ mCount = count;
+ mLimit = limit;
+ mIsRange = isRange;
+ }
+
+ /**
+ * Attempts to parse the command string into a usable structure.
+ *
+ * @param command The command string, without a new line at the end.
+ * @throws MalformedDiffScriptException if the command is not a valid diff script command.
+ * @return The parsed command.
+ */
+ private static Command parse(String command) throws MalformedDiffScriptException {
+ if (!VALID_COMMAND_PATTERN.matcher(command).matches()) {
+ throw new MalformedDiffScriptException("Bad command: " + command);
+ }
+
+ Scanner commandScanner = new Scanner(command);
+ commandScanner.useDelimiter("-");
+ long n = commandScanner.nextLong();
+ if (!commandScanner.hasNextLong()) {
+ return new Command(n, 0L, /*isRange=*/ false);
+ }
+ long m = commandScanner.nextLong();
+ return new Command(n, m, /*isRange=*/ true);
+ }
+ }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java
index 3f3494d2c22c..b9055cecd502 100644
--- a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java
@@ -16,7 +16,11 @@
package com.android.server.backup.testing;
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+
import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
import java.util.Random;
import javax.crypto.KeyGenerator;
@@ -42,4 +46,72 @@ public class CryptoTestUtils {
random.nextBytes(bytes);
return bytes;
}
+
+ public static ChunksMetadataProto.Chunk newChunk(ChunkHash hash, int length) {
+ return newChunk(hash.getHash(), length);
+ }
+
+ public static ChunksMetadataProto.Chunk newChunk(byte[] hash, int length) {
+ ChunksMetadataProto.Chunk newChunk = new ChunksMetadataProto.Chunk();
+ newChunk.hash = Arrays.copyOf(hash, hash.length);
+ newChunk.length = length;
+ return newChunk;
+ }
+
+ public static ChunksMetadataProto.ChunkListing newChunkListing(
+ String docId,
+ byte[] fingerprintSalt,
+ int cipherType,
+ int orderingType,
+ ChunksMetadataProto.Chunk... chunks) {
+ ChunksMetadataProto.ChunkListing chunkListing =
+ newChunkListingWithoutDocId(fingerprintSalt, cipherType, orderingType, chunks);
+ chunkListing.documentId = docId;
+ return chunkListing;
+ }
+
+ public static ChunksMetadataProto.ChunkListing newChunkListingWithoutDocId(
+ byte[] fingerprintSalt,
+ int cipherType,
+ int orderingType,
+ ChunksMetadataProto.Chunk... chunks) {
+ ChunksMetadataProto.ChunkListing chunkListing = new ChunksMetadataProto.ChunkListing();
+ chunkListing.fingerprintMixerSalt = Arrays.copyOf(fingerprintSalt, fingerprintSalt.length);
+ chunkListing.cipherType = cipherType;
+ chunkListing.chunkOrderingType = orderingType;
+ chunkListing.chunks = chunks;
+ return chunkListing;
+ }
+
+ public static ChunksMetadataProto.ChunkOrdering newChunkOrdering(
+ int[] starts, byte[] checksum) {
+ ChunksMetadataProto.ChunkOrdering chunkOrdering = new ChunksMetadataProto.ChunkOrdering();
+ chunkOrdering.starts = Arrays.copyOf(starts, starts.length);
+ chunkOrdering.checksum = Arrays.copyOf(checksum, checksum.length);
+ return chunkOrdering;
+ }
+
+ public static ChunksMetadataProto.ChunkListing clone(
+ ChunksMetadataProto.ChunkListing original) {
+ ChunksMetadataProto.Chunk[] clonedChunks;
+ if (original.chunks == null) {
+ clonedChunks = null;
+ } else {
+ clonedChunks = new ChunksMetadataProto.Chunk[original.chunks.length];
+ for (int i = 0; i < original.chunks.length; i++) {
+ clonedChunks[i] = clone(original.chunks[i]);
+ }
+ }
+
+ return newChunkListing(
+ original.documentId,
+ original.fingerprintMixerSalt,
+ original.cipherType,
+ original.chunkOrderingType,
+ clonedChunks);
+ }
+
+ public static ChunksMetadataProto.Chunk clone(ChunksMetadataProto.Chunk original) {
+ return newChunk(original.hash, original.length);
+ }
}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java
new file mode 100644
index 000000000000..6d3b5e9f1d7b
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.testing.shadows;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+/**
+ * Represents a key value pair in {@link ShadowBackupDataInput} and {@link ShadowBackupDataOutput}.
+ */
+public class DataEntity {
+ public final String mKey;
+ public final byte[] mValue;
+ public final int mSize;
+
+ /**
+ * Constructs a pair with a string value. The value will be converted to a byte array in {@link
+ * StandardCharsets#UTF_8}.
+ */
+ public DataEntity(String key, String value) {
+ this.mKey = checkNotNull(key);
+ this.mValue = value.getBytes(StandardCharsets.UTF_8);
+ mSize = this.mValue.length;
+ }
+
+ /**
+ * Constructs a new entity with the given key but a negative size. This represents a deleted
+ * pair.
+ */
+ public DataEntity(String key) {
+ this.mKey = checkNotNull(key);
+ mSize = -1;
+ mValue = null;
+ }
+
+ /** Constructs a new entity where the size of the value is the entire array. */
+ public DataEntity(String key, byte[] value) {
+ this(key, value, value.length);
+ }
+
+ /**
+ * Constructs a new entity.
+ *
+ * @param key the key of the pair
+ * @param data the value to associate with the key
+ * @param size the length of the value in bytes
+ */
+ public DataEntity(String key, byte[] data, int size) {
+ this.mKey = checkNotNull(key);
+ this.mSize = size;
+ mValue = new byte[size];
+ for (int i = 0; i < size; i++) {
+ mValue[i] = data[i];
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ DataEntity that = (DataEntity) o;
+
+ if (mSize != that.mSize) {
+ return false;
+ }
+ if (!mKey.equals(that.mKey)) {
+ return false;
+ }
+ return Arrays.equals(mValue, that.mValue);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = mKey.hashCode();
+ result = 31 * result + Arrays.hashCode(mValue);
+ result = 31 * result + mSize;
+ return result;
+ }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java
new file mode 100644
index 000000000000..7ac6ec40508d
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.testing.shadows;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupDataInput;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.io.ByteArrayInputStream;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Shadow for BackupDataInput. */
+@Implements(BackupDataInput.class)
+public class ShadowBackupDataInput {
+ private static final List<DataEntity> ENTITIES = new ArrayList<>();
+ @Nullable private static IOException sReadNextHeaderException;
+
+ @Nullable private ByteArrayInputStream mCurrentEntityInputStream;
+ private int mCurrentEntity = -1;
+
+ /** Resets the shadow, clearing any entities or exception. */
+ public static void reset() {
+ ENTITIES.clear();
+ sReadNextHeaderException = null;
+ }
+
+ /** Sets the exception which the input will throw for any call to {@link #readNextHeader}. */
+ public static void setReadNextHeaderException(@Nullable IOException readNextHeaderException) {
+ ShadowBackupDataInput.sReadNextHeaderException = readNextHeaderException;
+ }
+
+ /** Adds the given entity to the input. */
+ public static void addEntity(DataEntity e) {
+ ENTITIES.add(e);
+ }
+
+ /** Adds an entity to the input with the given key and value. */
+ public static void addEntity(String key, byte[] value) {
+ ENTITIES.add(new DataEntity(key, value, value.length));
+ }
+
+ public void __constructor__(FileDescriptor fd) {}
+
+ @Implementation
+ public boolean readNextHeader() throws IOException {
+ if (sReadNextHeaderException != null) {
+ throw sReadNextHeaderException;
+ }
+
+ mCurrentEntity++;
+
+ if (mCurrentEntity >= ENTITIES.size()) {
+ return false;
+ }
+
+ byte[] value = ENTITIES.get(mCurrentEntity).mValue;
+ if (value == null) {
+ mCurrentEntityInputStream = new ByteArrayInputStream(new byte[0]);
+ } else {
+ mCurrentEntityInputStream = new ByteArrayInputStream(value);
+ }
+ return true;
+ }
+
+ @Implementation
+ public String getKey() {
+ return ENTITIES.get(mCurrentEntity).mKey;
+ }
+
+ @Implementation
+ public int getDataSize() {
+ return ENTITIES.get(mCurrentEntity).mSize;
+ }
+
+ @Implementation
+ public void skipEntityData() {
+ // Do nothing.
+ }
+
+ @Implementation
+ public int readEntityData(byte[] data, int offset, int size) {
+ checkState(mCurrentEntityInputStream != null, "Must call readNextHeader() first");
+ return mCurrentEntityInputStream.read(data, offset, size);
+ }
+}
diff --git a/packages/BackupEncryption/test/unittest/Android.bp b/packages/BackupEncryption/test/unittest/Android.bp
new file mode 100644
index 000000000000..d7c510b57518
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/Android.bp
@@ -0,0 +1,22 @@
+android_test {
+ name: "BackupEncryptionUnitTests",
+ srcs: ["src/**/*.java"],
+ static_libs: [
+ "androidx.test.runner",
+ "androidx.test.rules",
+ "mockito-target-minus-junit4",
+ "platform-test-annotations",
+ "truth-prebuilt",
+ "testables",
+ "testng",
+ ],
+ libs: [
+ "android.test.mock",
+ "android.test.base",
+ "android.test.runner",
+ "BackupEncryption",
+ ],
+ test_suites: ["device-tests"],
+ instrumentation_for: "BackupEncryption",
+ certificate: "platform",
+} \ No newline at end of file
diff --git a/packages/BackupEncryption/test/unittest/AndroidManifest.xml b/packages/BackupEncryption/test/unittest/AndroidManifest.xml
new file mode 100644
index 000000000000..39ac8aa32ebc
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.server.backup.encryption.unittests"
+ android:sharedUserId="android.uid.system" >
+ <application android:testOnly="true">
+ <uses-library android:name="android.test.runner" />
+ </application>
+ <instrumentation
+ android:name="androidx.test.runner.AndroidJUnitRunner"
+ android:targetPackage="com.android.server.backup.encryption"
+ android:label="Backup Encryption Unit Tests" />
+</manifest> \ No newline at end of file
diff --git a/packages/BackupEncryption/test/unittest/AndroidTest.xml b/packages/BackupEncryption/test/unittest/AndroidTest.xml
new file mode 100644
index 000000000000..c9c812a78194
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/AndroidTest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+<configuration description="Runs Backup Encryption Unit Tests.">
+ <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+ <option name="cleanup-apks" value="true" />
+ <option name="install-arg" value="-t" />
+ <option name="test-file-name" value="BackupEncryptionUnitTests.apk" />
+ </target_preparer>
+
+ <option name="test-tag" value="BackupEncryptionUnitTests" />
+ <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+ <option name="package" value="com.android.server.backup.encryption.unittests" />
+ <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+ </test>
+</configuration>
diff --git a/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java
new file mode 100644
index 000000000000..0d43a190cd07
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.transport;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotSame;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.content.ComponentName;
+import android.content.Intent;
+import android.os.Bundle;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.backup.transport.TransportClient;
+import com.android.server.backup.transport.TransportClientManager;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class IntermediateEncryptingTransportManagerTest {
+ @Mock private TransportClient mTransportClient;
+ @Mock private TransportClientManager mTransportClientManager;
+
+ private final ComponentName mTransportComponent = new ComponentName("pkg", "class");
+ private final Bundle mExtras = new Bundle();
+ private Intent mEncryptingTransportIntent;
+ private IntermediateEncryptingTransportManager mIntermediateEncryptingTransportManager;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ mExtras.putInt("test", 1);
+ mEncryptingTransportIntent =
+ TransportClientManager.getEncryptingTransportIntent(mTransportComponent)
+ .putExtras(mExtras);
+ mIntermediateEncryptingTransportManager =
+ new IntermediateEncryptingTransportManager(mTransportClientManager);
+ }
+
+ @Test
+ public void testGet_createsClientWithRealTransportComponentAndExtras() {
+ when(mTransportClientManager.getTransportClient(any(), any(), any()))
+ .thenReturn(mTransportClient);
+
+ IntermediateEncryptingTransport intermediateEncryptingTransport =
+ mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+
+ assertEquals(mTransportClient, intermediateEncryptingTransport.getClient());
+ verify(mTransportClientManager, times(1))
+ .getTransportClient(eq(mTransportComponent), argThat(mExtras::kindofEquals), any());
+ verifyNoMoreInteractions(mTransportClientManager);
+ }
+
+ @Test
+ public void testGet_callTwice_returnsSameTransport() {
+ IntermediateEncryptingTransport transport1 =
+ mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+ IntermediateEncryptingTransport transport2 =
+ mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+
+ assertEquals(transport1, transport2);
+ }
+
+ @Test
+ public void testCleanup_disposesTransportClient() {
+ when(mTransportClientManager.getTransportClient(any(), any(), any()))
+ .thenReturn(mTransportClient);
+
+ IntermediateEncryptingTransport transport =
+ mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+ mIntermediateEncryptingTransportManager.cleanup(mEncryptingTransportIntent);
+
+ verify(mTransportClientManager, times(1)).getTransportClient(any(), any(), any());
+ verify(mTransportClientManager, times(1))
+ .disposeOfTransportClient(eq(mTransportClient), any());
+ verifyNoMoreInteractions(mTransportClientManager);
+ }
+
+ @Test
+ public void testCleanup_removesCachedTransport() {
+ when(mTransportClientManager.getTransportClient(any(), any(), any()))
+ .thenReturn(mTransportClient);
+
+ IntermediateEncryptingTransport transport1 =
+ mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+ mIntermediateEncryptingTransportManager.cleanup(mEncryptingTransportIntent);
+ IntermediateEncryptingTransport transport2 =
+ mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+
+ assertNotSame(transport1, transport2);
+ }
+}
diff --git a/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java
new file mode 100644
index 000000000000..cc4b0ab1bb36
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.backup.encryption.transport;
+
+import static junit.framework.Assert.assertEquals;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.transport.TransportClient;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class IntermediateEncryptingTransportTest {
+ @Mock private IBackupTransport mRealTransport;
+ @Mock private TransportClient mTransportClient;
+
+ private IntermediateEncryptingTransport mIntermediateEncryptingTransport;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ mIntermediateEncryptingTransport = new IntermediateEncryptingTransport(mTransportClient);
+ }
+
+ @Test
+ public void testGetDelegate_callsConnect() throws Exception {
+ when(mTransportClient.connect(anyString())).thenReturn(mRealTransport);
+
+ IBackupTransport ret = mIntermediateEncryptingTransport.getDelegate();
+
+ assertEquals(mRealTransport, ret);
+ verify(mTransportClient, times(1)).connect(anyString());
+ verifyNoMoreInteractions(mTransportClient);
+ }
+
+ @Test
+ public void testGetDelegate_callTwice_callsConnectOnce() throws Exception {
+ when(mTransportClient.connect(anyString())).thenReturn(mRealTransport);
+
+ IBackupTransport ret1 = mIntermediateEncryptingTransport.getDelegate();
+ IBackupTransport ret2 = mIntermediateEncryptingTransport.getDelegate();
+
+ assertEquals(mRealTransport, ret1);
+ assertEquals(mRealTransport, ret2);
+ verify(mTransportClient, times(1)).connect(anyString());
+ verifyNoMoreInteractions(mTransportClient);
+ }
+}
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 365923ea8643..046ffc3c36bb 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -2242,9 +2242,6 @@ class SettingsProtoDumpUtil {
dumpSetting(s, p,
Settings.Secure.PACKAGE_VERIFIER_USER_CONSENT,
SecureSettingsProto.PackageVerifier.USER_CONSENT);
- dumpSetting(s, p,
- Settings.Secure.PACKAGE_VERIFIER_STATE,
- SecureSettingsProto.PackageVerifier.STATE);
p.end(packageVerifierToken);
final long parentalControlToken = p.start(SecureSettingsProto.PARENTAL_CONTROL);
diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
index 6ea3db366f66..3a7de188f962 100644
--- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
@@ -17,8 +17,7 @@
package android.provider;
import static com.google.android.collect.Sets.newHashSet;
-
-import static junit.framework.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.reflect.Modifier.isFinal;
import static java.lang.reflect.Modifier.isPublic;
@@ -655,7 +654,6 @@ public class SettingsBackupTest {
Settings.Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED,
Settings.Secure.ODI_CAPTIONS_ENABLED,
- Settings.Secure.PACKAGE_VERIFIER_STATE,
Settings.Secure.PACKAGE_VERIFIER_USER_CONSENT,
Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
Settings.Secure.PAYMENT_SERVICE_SEARCH_URI,
@@ -754,12 +752,11 @@ public class SettingsBackupTest {
Set<String> settings, Set<String> settingsToBackup, Set<String> blacklist) {
Set<String> settingsNotBackedUp = difference(settings, settingsToBackup);
Set<String> settingsNotBackedUpOrBlacklisted = difference(settingsNotBackedUp, blacklist);
- assertTrue(
- "Settings not backed up or blacklisted",
- settingsNotBackedUpOrBlacklisted.isEmpty());
+ assertWithMessage("Settings not backed up or blacklisted")
+ .that(settingsNotBackedUpOrBlacklisted).isEmpty();
- assertTrue(
- "blacklisted settings backed up", intersect(settingsToBackup, blacklist).isEmpty());
+ assertWithMessage("blacklisted settings backed up")
+ .that(intersect(settingsToBackup, blacklist)).isEmpty();
}
private static Set<String> getCandidateSettings(
diff --git a/packages/SystemUI/res/layout/navigation_bar.xml b/packages/SystemUI/res/layout/navigation_bar.xml
index 8ba4c9c05ba6..ba6b6956f187 100644
--- a/packages/SystemUI/res/layout/navigation_bar.xml
+++ b/packages/SystemUI/res/layout/navigation_bar.xml
@@ -24,6 +24,21 @@
android:layout_width="match_parent"
android:background="@drawable/system_bar_background">
+ <com.android.systemui.CornerHandleView
+ android:id="@+id/assist_hint_left"
+ android:layout_width="36dp"
+ android:layout_height="36dp"
+ android:layout_gravity="left|bottom"
+ android:rotation="270"
+ android:visibility="gone"/>
+ <com.android.systemui.CornerHandleView
+ android:id="@+id/assist_hint_right"
+ android:layout_width="36dp"
+ android:layout_height="36dp"
+ android:layout_gravity="right|bottom"
+ android:rotation="180"
+ android:visibility="gone"/>
+
<com.android.systemui.statusbar.phone.NavigationBarInflaterView
android:id="@+id/navigation_inflater"
android:layout_width="match_parent"
diff --git a/packages/SystemUI/res/layout/rounded_corners.xml b/packages/SystemUI/res/layout/rounded_corners.xml
index b409c8f2ba5a..1849068d91b8 100644
--- a/packages/SystemUI/res/layout/rounded_corners.xml
+++ b/packages/SystemUI/res/layout/rounded_corners.xml
@@ -18,18 +18,6 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
- <com.android.systemui.CornerHandleView
- android:id="@+id/assist_hint_left"
- android:layout_width="36dp"
- android:layout_height="36dp"
- android:layout_gravity="left|top"
- android:visibility="gone"/>
- <com.android.systemui.CornerHandleView
- android:id="@+id/assist_hint_right"
- android:layout_width="36dp"
- android:layout_height="36dp"
- android:layout_gravity="right|bottom"
- android:visibility="gone"/>
<ImageView
android:id="@+id/left"
android:layout_width="12dp"
diff --git a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
index f38b4f259c88..3e068b0a0964 100644
--- a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
+++ b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
@@ -25,9 +25,6 @@ import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_M
import static com.android.systemui.tuner.TunablePadding.FLAG_END;
import static com.android.systemui.tuner.TunablePadding.FLAG_START;
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
import android.annotation.Dimension;
import android.app.ActivityManager;
import android.app.Fragment;
@@ -52,7 +49,6 @@ import android.os.SystemProperties;
import android.provider.Settings.Secure;
import android.util.DisplayMetrics;
import android.util.Log;
-import android.util.MathUtils;
import android.view.DisplayCutout;
import android.view.DisplayInfo;
import android.view.Gravity;
@@ -64,9 +60,6 @@ import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
-import android.view.animation.AccelerateInterpolator;
-import android.view.animation.Interpolator;
-import android.view.animation.PathInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
@@ -78,10 +71,7 @@ import com.android.systemui.fragments.FragmentHostManager;
import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
import com.android.systemui.plugins.qs.QS;
import com.android.systemui.qs.SecureSetting;
-import com.android.systemui.shared.system.QuickStepContract;
import com.android.systemui.statusbar.phone.CollapsedStatusBarFragment;
-import com.android.systemui.statusbar.phone.NavigationBarTransitions;
-import com.android.systemui.statusbar.phone.NavigationModeController;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.tuner.TunablePadding;
import com.android.systemui.tuner.TunerService;
@@ -95,8 +85,7 @@ import java.util.List;
* An overlay that draws screen decorations in software (e.g for rounded corners or display cutout)
* for antialiasing and emulation purposes.
*/
-public class ScreenDecorations extends SystemUI implements Tunable,
- NavigationBarTransitions.DarkIntensityListener {
+public class ScreenDecorations extends SystemUI implements Tunable {
private static final boolean DEBUG = false;
private static final String TAG = "ScreenDecorations";
@@ -120,15 +109,11 @@ public class ScreenDecorations extends SystemUI implements Tunable,
private float mDensity;
private WindowManager mWindowManager;
private int mRotation;
- private boolean mAssistHintVisible;
private DisplayCutoutView mCutoutTop;
private DisplayCutoutView mCutoutBottom;
private SecureSetting mColorInversionSetting;
private boolean mPendingRotationChange;
private Handler mHandler;
- private boolean mAssistHintBlocked = false;
- private boolean mIsReceivingNavBarColor = false;
- private boolean mInGesturalMode;
/**
* Converts a set of {@link Rect}s into a {@link Region}
@@ -153,160 +138,6 @@ public class ScreenDecorations extends SystemUI implements Tunable,
mHandler.post(this::startOnScreenDecorationsThread);
setupStatusBarPaddingIfNeeded();
putComponent(ScreenDecorations.class, this);
- mInGesturalMode = QuickStepContract.isGesturalMode(
- Dependency.get(NavigationModeController.class)
- .addListener(this::handleNavigationModeChange));
- }
-
- @VisibleForTesting
- void handleNavigationModeChange(int navigationMode) {
- if (!mHandler.getLooper().isCurrentThread()) {
- mHandler.post(() -> handleNavigationModeChange(navigationMode));
- return;
- }
- boolean inGesturalMode = QuickStepContract.isGesturalMode(navigationMode);
- if (mInGesturalMode != inGesturalMode) {
- mInGesturalMode = inGesturalMode;
-
- if (mInGesturalMode && mOverlay == null) {
- setupDecorations();
- if (mOverlay != null) {
- updateLayoutParams();
- }
- }
- }
- }
-
- /**
- * Returns an animator that animates the given view from start to end over durationMs. Start and
- * end represent total animation progress: 0 is the start, 1 is the end, 1.1 would be an
- * overshoot.
- */
- Animator getHandleAnimator(View view, float start, float end, boolean isLeft, long durationMs,
- Interpolator interpolator) {
- // Note that lerp does allow overshoot, in cases where start and end are outside of [0,1].
- float scaleStart = MathUtils.lerp(2f, 1f, start);
- float scaleEnd = MathUtils.lerp(2f, 1f, end);
- Animator scaleX = ObjectAnimator.ofFloat(view, View.SCALE_X, scaleStart, scaleEnd);
- Animator scaleY = ObjectAnimator.ofFloat(view, View.SCALE_Y, scaleStart, scaleEnd);
- float translationStart = MathUtils.lerp(0.2f, 0f, start);
- float translationEnd = MathUtils.lerp(0.2f, 0f, end);
- int xDirection = isLeft ? -1 : 1;
- Animator translateX = ObjectAnimator.ofFloat(view, View.TRANSLATION_X,
- xDirection * translationStart * view.getWidth(),
- xDirection * translationEnd * view.getWidth());
- Animator translateY = ObjectAnimator.ofFloat(view, View.TRANSLATION_Y,
- translationStart * view.getHeight(), translationEnd * view.getHeight());
-
- AnimatorSet set = new AnimatorSet();
- set.play(scaleX).with(scaleY);
- set.play(scaleX).with(translateX);
- set.play(scaleX).with(translateY);
- set.setDuration(durationMs);
- set.setInterpolator(interpolator);
- return set;
- }
-
- private void fade(View view, boolean fadeIn, boolean isLeft) {
- if (fadeIn) {
- view.animate().cancel();
- view.setAlpha(1f);
- view.setVisibility(View.VISIBLE);
-
- // A piecewise spring-like interpolation.
- // End value in one animator call must match the start value in the next, otherwise
- // there will be a discontinuity.
- AnimatorSet anim = new AnimatorSet();
- Animator first = getHandleAnimator(view, 0, 1.1f, isLeft, 750,
- new PathInterpolator(0, 0.45f, .67f, 1f));
- Interpolator secondInterpolator = new PathInterpolator(0.33f, 0, 0.67f, 1f);
- Animator second = getHandleAnimator(view, 1.1f, 0.97f, isLeft, 400,
- secondInterpolator);
- Animator third = getHandleAnimator(view, 0.97f, 1.02f, isLeft, 400,
- secondInterpolator);
- Animator fourth = getHandleAnimator(view, 1.02f, 1f, isLeft, 400,
- secondInterpolator);
- anim.play(first).before(second);
- anim.play(second).before(third);
- anim.play(third).before(fourth);
- anim.start();
- } else {
- view.animate().cancel();
- view.animate()
- .setInterpolator(new AccelerateInterpolator(1.5f))
- .setDuration(250)
- .alpha(0f);
- }
-
- }
-
- /**
- * Controls the visibility of the assist gesture handles.
- *
- * @param visible whether the handles should be shown
- */
- public void setAssistHintVisible(boolean visible) {
- if (!mHandler.getLooper().isCurrentThread()) {
- mHandler.post(() -> setAssistHintVisible(visible));
- return;
- }
-
- if (mAssistHintBlocked && visible) {
- if (VERBOSE) {
- Log.v(TAG, "Assist hint blocked, cannot make it visible");
- }
- return;
- }
-
- if (mOverlay == null || mBottomOverlay == null) {
- return;
- }
-
- if (mAssistHintVisible != visible) {
- mAssistHintVisible = visible;
-
- CornerHandleView assistHintTopLeft = mOverlay.findViewById(R.id.assist_hint_left);
- CornerHandleView assistHintTopRight = mOverlay.findViewById(R.id.assist_hint_right);
- CornerHandleView assistHintBottomLeft = mBottomOverlay.findViewById(
- R.id.assist_hint_left);
- CornerHandleView assistHintBottomRight = mBottomOverlay.findViewById(
- R.id.assist_hint_right);
-
- switch (mRotation) {
- case RotationUtils.ROTATION_NONE:
- fade(assistHintBottomLeft, mAssistHintVisible, /* isLeft = */ true);
- fade(assistHintBottomRight, mAssistHintVisible, /* isLeft = */ false);
- break;
- case RotationUtils.ROTATION_LANDSCAPE:
- fade(assistHintTopRight, mAssistHintVisible, /* isLeft = */ true);
- fade(assistHintBottomRight, mAssistHintVisible, /* isLeft = */ false);
- break;
- case RotationUtils.ROTATION_SEASCAPE:
- fade(assistHintTopLeft, mAssistHintVisible, /* isLeft = */ false);
- fade(assistHintBottomLeft, mAssistHintVisible, /* isLeft = */ true);
- break;
- case RotationUtils.ROTATION_UPSIDE_DOWN:
- fade(assistHintTopLeft, mAssistHintVisible, /* isLeft = */ false);
- fade(assistHintTopRight, mAssistHintVisible, /* isLeft = */ true);
- break;
- }
- }
- updateWindowVisibilities();
- }
-
- /**
- * Prevents the assist hint from becoming visible even if `mAssistHintVisible` is true.
- */
- public void setAssistHintBlocked(boolean blocked) {
- if (!mHandler.getLooper().isCurrentThread()) {
- mHandler.post(() -> setAssistHintBlocked(blocked));
- return;
- }
-
- mAssistHintBlocked = blocked;
- if (mAssistHintVisible && mAssistHintBlocked) {
- hideAssistHandles();
- }
}
@VisibleForTesting
@@ -316,15 +147,11 @@ public class ScreenDecorations extends SystemUI implements Tunable,
return thread.getThreadHandler();
}
- private boolean shouldHostHandles() {
- return mInGesturalMode;
- }
-
private void startOnScreenDecorationsThread() {
mRotation = RotationUtils.getExactRotation(mContext);
mWindowManager = mContext.getSystemService(WindowManager.class);
updateRoundedCornerRadii();
- if (hasRoundedCorners() || shouldDrawCutout() || shouldHostHandles()) {
+ if (hasRoundedCorners() || shouldDrawCutout()) {
setupDecorations();
}
@@ -501,26 +328,10 @@ public class ScreenDecorations extends SystemUI implements Tunable,
if (mOverlay != null) {
updateLayoutParams();
updateViews();
- if (mAssistHintVisible) {
- // If assist handles are visible, hide them without animation and then make them
- // show once again (with corrected rotation).
- hideAssistHandles();
- setAssistHintVisible(true);
- }
}
}
}
- private void hideAssistHandles() {
- if (mOverlay != null && mBottomOverlay != null) {
- mOverlay.findViewById(R.id.assist_hint_left).setVisibility(View.GONE);
- mOverlay.findViewById(R.id.assist_hint_right).setVisibility(View.GONE);
- mBottomOverlay.findViewById(R.id.assist_hint_left).setVisibility(View.GONE);
- mBottomOverlay.findViewById(R.id.assist_hint_right).setVisibility(View.GONE);
- mAssistHintVisible = false;
- }
- }
-
private void updateRoundedCornerRadii() {
final int newRoundedDefault = mContext.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.rounded_corner_radius);
@@ -569,52 +380,12 @@ public class ScreenDecorations extends SystemUI implements Tunable,
updateView(bottomRight, Gravity.TOP | Gravity.LEFT, 0);
}
- updateAssistantHandleViews();
mCutoutTop.setRotation(mRotation);
mCutoutBottom.setRotation(mRotation);
updateWindowVisibilities();
}
- private void updateAssistantHandleViews() {
- View assistHintTopLeft = mOverlay.findViewById(R.id.assist_hint_left);
- View assistHintTopRight = mOverlay.findViewById(R.id.assist_hint_right);
- View assistHintBottomLeft = mBottomOverlay.findViewById(R.id.assist_hint_left);
- View assistHintBottomRight = mBottomOverlay.findViewById(R.id.assist_hint_right);
-
- final int assistHintVisibility = mAssistHintVisible ? View.VISIBLE : View.INVISIBLE;
-
- if (mRotation == RotationUtils.ROTATION_NONE) {
- assistHintTopLeft.setVisibility(View.GONE);
- assistHintTopRight.setVisibility(View.GONE);
- assistHintBottomLeft.setVisibility(assistHintVisibility);
- assistHintBottomRight.setVisibility(assistHintVisibility);
- updateView(assistHintBottomLeft, Gravity.BOTTOM | Gravity.LEFT, 270);
- updateView(assistHintBottomRight, Gravity.BOTTOM | Gravity.RIGHT, 180);
- } else if (mRotation == RotationUtils.ROTATION_LANDSCAPE) {
- assistHintTopLeft.setVisibility(View.GONE);
- assistHintTopRight.setVisibility(assistHintVisibility);
- assistHintBottomLeft.setVisibility(View.GONE);
- assistHintBottomRight.setVisibility(assistHintVisibility);
- updateView(assistHintTopRight, Gravity.BOTTOM | Gravity.LEFT, 270);
- updateView(assistHintBottomRight, Gravity.BOTTOM | Gravity.RIGHT, 180);
- } else if (mRotation == RotationUtils.ROTATION_UPSIDE_DOWN) {
- assistHintTopLeft.setVisibility(assistHintVisibility);
- assistHintTopRight.setVisibility(assistHintVisibility);
- assistHintBottomLeft.setVisibility(View.GONE);
- assistHintBottomRight.setVisibility(View.GONE);
- updateView(assistHintTopLeft, Gravity.BOTTOM | Gravity.LEFT, 270);
- updateView(assistHintTopRight, Gravity.BOTTOM | Gravity.RIGHT, 180);
- } else if (mRotation == RotationUtils.ROTATION_SEASCAPE) {
- assistHintTopLeft.setVisibility(assistHintVisibility);
- assistHintTopRight.setVisibility(View.GONE);
- assistHintBottomLeft.setVisibility(assistHintVisibility);
- assistHintBottomRight.setVisibility(View.GONE);
- updateView(assistHintTopLeft, Gravity.BOTTOM | Gravity.RIGHT, 180);
- updateView(assistHintBottomLeft, Gravity.BOTTOM | Gravity.LEFT, 270);
- }
- }
-
private void updateView(View v, int gravity, int rotation) {
((FrameLayout.LayoutParams) v.getLayoutParams()).gravity = gravity;
v.setRotation(rotation);
@@ -629,10 +400,7 @@ public class ScreenDecorations extends SystemUI implements Tunable,
boolean visibleForCutout = shouldDrawCutout()
&& overlay.findViewById(R.id.display_cutout).getVisibility() == View.VISIBLE;
boolean visibleForRoundedCorners = hasRoundedCorners();
- boolean visibleForHandles = overlay.findViewById(R.id.assist_hint_left).getVisibility()
- == View.VISIBLE || overlay.findViewById(R.id.assist_hint_right).getVisibility()
- == View.VISIBLE;
- overlay.setVisibility(visibleForCutout || visibleForRoundedCorners || visibleForHandles
+ overlay.setVisibility(visibleForCutout || visibleForRoundedCorners
? View.VISIBLE : View.GONE);
}
@@ -766,31 +534,6 @@ public class ScreenDecorations extends SystemUI implements Tunable,
view.setLayoutParams(params);
}
- @Override
- public void onDarkIntensity(float darkIntensity) {
- if (!mHandler.getLooper().isCurrentThread()) {
- mHandler.post(() -> onDarkIntensity(darkIntensity));
- return;
- }
- if (mOverlay != null) {
- CornerHandleView assistHintTopLeft = mOverlay.findViewById(R.id.assist_hint_left);
- CornerHandleView assistHintTopRight = mOverlay.findViewById(R.id.assist_hint_right);
-
- assistHintTopLeft.updateDarkness(darkIntensity);
- assistHintTopRight.updateDarkness(darkIntensity);
- }
-
- if (mBottomOverlay != null) {
- CornerHandleView assistHintBottomLeft = mBottomOverlay.findViewById(
- R.id.assist_hint_left);
- CornerHandleView assistHintBottomRight = mBottomOverlay.findViewById(
- R.id.assist_hint_right);
-
- assistHintBottomLeft.updateDarkness(darkIntensity);
- assistHintBottomRight.updateDarkness(darkIntensity);
- }
- }
-
@VisibleForTesting
static class TunablePaddingTagListener implements FragmentListener {
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java
index 9bdfa03408aa..4516996345b9 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java
@@ -32,7 +32,6 @@ import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.systemui.DumpController;
import com.android.systemui.Dumpable;
-import com.android.systemui.ScreenDecorations;
import com.android.systemui.shared.system.QuickStepContract;
import com.android.systemui.statusbar.phone.NavigationModeController;
@@ -71,7 +70,7 @@ public final class AssistHandleBehaviorController implements AssistHandleCallbac
private final Handler mHandler;
private final Runnable mHideHandles = this::hideHandles;
private final Runnable mShowAndGo = this::showAndGoInternal;
- private final Provider<ScreenDecorations> mScreenDecorations;
+ private final Provider<AssistHandleViewController> mAssistHandleViewController;
private final PhenotypeHelper mPhenotypeHelper;
private final Map<AssistHandleBehavior, BehaviorController> mBehaviorMap;
@@ -90,7 +89,7 @@ public final class AssistHandleBehaviorController implements AssistHandleCallbac
Context context,
AssistUtils assistUtils,
@Named(ASSIST_HANDLE_THREAD_NAME) Handler handler,
- Provider<ScreenDecorations> screenDecorations,
+ Provider<AssistHandleViewController> assistHandleViewController,
PhenotypeHelper phenotypeHelper,
Map<AssistHandleBehavior, BehaviorController> behaviorMap,
NavigationModeController navigationModeController,
@@ -98,7 +97,7 @@ public final class AssistHandleBehaviorController implements AssistHandleCallbac
mContext = context;
mAssistUtils = assistUtils;
mHandler = handler;
- mScreenDecorations = screenDecorations;
+ mAssistHandleViewController = assistHandleViewController;
mPhenotypeHelper = phenotypeHelper;
mBehaviorMap = behaviorMap;
@@ -193,7 +192,7 @@ public final class AssistHandleBehaviorController implements AssistHandleCallbac
try {
setBehavior(AssistHandleBehavior.valueOf(behavior));
} catch (IllegalArgumentException | NullPointerException e) {
- Log.e(TAG, "Invalid behavior: " + behavior, e);
+ Log.e(TAG, "Invalid behavior: " + behavior);
}
}
@@ -229,12 +228,13 @@ public final class AssistHandleBehaviorController implements AssistHandleCallbac
}
if (handlesUnblocked(ignoreThreshold)) {
- ScreenDecorations screenDecorations = mScreenDecorations.get();
- if (screenDecorations == null) {
- Log.w(TAG, "Couldn't show handles, ScreenDecorations unavailable");
+ mHandlesShowing = true;
+ AssistHandleViewController assistHandleViewController =
+ mAssistHandleViewController.get();
+ if (assistHandleViewController == null) {
+ Log.w(TAG, "Couldn't show handles, AssistHandleViewController unavailable");
} else {
- mHandlesShowing = true;
- screenDecorations.setAssistHintVisible(true);
+ assistHandleViewController.setAssistHintVisible(true);
}
}
}
@@ -244,13 +244,14 @@ public final class AssistHandleBehaviorController implements AssistHandleCallbac
return;
}
- ScreenDecorations screenDecorations = mScreenDecorations.get();
- if (screenDecorations == null) {
- Log.w(TAG, "Couldn't hide handles, ScreenDecorations unavailable");
+ mHandlesShowing = false;
+ mHandlesLastHiddenAt = SystemClock.elapsedRealtime();
+ AssistHandleViewController assistHandleViewController =
+ mAssistHandleViewController.get();
+ if (assistHandleViewController == null) {
+ Log.w(TAG, "Couldn't show handles, AssistHandleViewController unavailable");
} else {
- mHandlesShowing = false;
- mHandlesLastHiddenAt = SystemClock.elapsedRealtime();
- screenDecorations.setAssistHintVisible(false);
+ assistHandleViewController.setAssistHintVisible(false);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java
new file mode 100644
index 000000000000..f9ffb804f9f3
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.assist;
+
+import android.animation.Animator;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
+import android.os.Handler;
+import android.util.Log;
+import android.util.MathUtils;
+import android.view.View;
+import android.view.animation.AccelerateInterpolator;
+import android.view.animation.Interpolator;
+import android.view.animation.PathInterpolator;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.systemui.CornerHandleView;
+import com.android.systemui.R;
+import com.android.systemui.statusbar.phone.NavigationBarTransitions;
+
+/**
+ * A class for managing Assistant handle show, hide and animation.
+ */
+public class AssistHandleViewController implements NavigationBarTransitions.DarkIntensityListener {
+
+ private static final boolean DEBUG = false;
+ private static final String TAG = "AssistHandleViewController";
+
+ private Handler mHandler;
+ private CornerHandleView mAssistHintLeft;
+ private CornerHandleView mAssistHintRight;
+
+ @VisibleForTesting
+ boolean mAssistHintVisible;
+ @VisibleForTesting
+ boolean mAssistHintBlocked = false;
+
+ public AssistHandleViewController(Handler handler, View navBar) {
+ mHandler = handler;
+ mAssistHintLeft = navBar.findViewById(R.id.assist_hint_left);
+ mAssistHintRight = navBar.findViewById(R.id.assist_hint_right);
+ }
+
+ @Override
+ public void onDarkIntensity(float darkIntensity) {
+ mAssistHintLeft.updateDarkness(darkIntensity);
+ mAssistHintRight.updateDarkness(darkIntensity);
+ }
+
+ /**
+ * Controls the visibility of the assist gesture handles.
+ *
+ * @param visible whether the handles should be shown
+ */
+ public void setAssistHintVisible(boolean visible) {
+ if (!mHandler.getLooper().isCurrentThread()) {
+ mHandler.post(() -> setAssistHintVisible(visible));
+ return;
+ }
+
+ if (mAssistHintBlocked && visible) {
+ if (DEBUG) {
+ Log.v(TAG, "Assist hint blocked, cannot make it visible");
+ }
+ return;
+ }
+
+ if (mAssistHintVisible != visible) {
+ mAssistHintVisible = visible;
+ fade(mAssistHintLeft, mAssistHintVisible, /* isLeft = */ true);
+ fade(mAssistHintRight, mAssistHintVisible, /* isLeft = */ false);
+ }
+ }
+
+ /**
+ * Prevents the assist hint from becoming visible even if `mAssistHintVisible` is true.
+ */
+ public void setAssistHintBlocked(boolean blocked) {
+ if (!mHandler.getLooper().isCurrentThread()) {
+ mHandler.post(() -> setAssistHintBlocked(blocked));
+ return;
+ }
+
+ mAssistHintBlocked = blocked;
+ if (mAssistHintVisible && mAssistHintBlocked) {
+ hideAssistHandles();
+ }
+ }
+
+ private void hideAssistHandles() {
+ mAssistHintLeft.setVisibility(View.GONE);
+ mAssistHintRight.setVisibility(View.GONE);
+ mAssistHintVisible = false;
+ }
+
+ /**
+ * Returns an animator that animates the given view from start to end over durationMs. Start and
+ * end represent total animation progress: 0 is the start, 1 is the end, 1.1 would be an
+ * overshoot.
+ */
+ Animator getHandleAnimator(View view, float start, float end, boolean isLeft, long durationMs,
+ Interpolator interpolator) {
+ // Note that lerp does allow overshoot, in cases where start and end are outside of [0,1].
+ float scaleStart = MathUtils.lerp(2f, 1f, start);
+ float scaleEnd = MathUtils.lerp(2f, 1f, end);
+ Animator scaleX = ObjectAnimator.ofFloat(view, View.SCALE_X, scaleStart, scaleEnd);
+ Animator scaleY = ObjectAnimator.ofFloat(view, View.SCALE_Y, scaleStart, scaleEnd);
+ float translationStart = MathUtils.lerp(0.2f, 0f, start);
+ float translationEnd = MathUtils.lerp(0.2f, 0f, end);
+ int xDirection = isLeft ? -1 : 1;
+ Animator translateX = ObjectAnimator.ofFloat(view, View.TRANSLATION_X,
+ xDirection * translationStart * view.getWidth(),
+ xDirection * translationEnd * view.getWidth());
+ Animator translateY = ObjectAnimator.ofFloat(view, View.TRANSLATION_Y,
+ translationStart * view.getHeight(), translationEnd * view.getHeight());
+
+ AnimatorSet set = new AnimatorSet();
+ set.play(scaleX).with(scaleY);
+ set.play(scaleX).with(translateX);
+ set.play(scaleX).with(translateY);
+ set.setDuration(durationMs);
+ set.setInterpolator(interpolator);
+ return set;
+ }
+
+ private void fade(View view, boolean fadeIn, boolean isLeft) {
+ if (fadeIn) {
+ view.animate().cancel();
+ view.setAlpha(1f);
+ view.setVisibility(View.VISIBLE);
+
+ // A piecewise spring-like interpolation.
+ // End value in one animator call must match the start value in the next, otherwise
+ // there will be a discontinuity.
+ AnimatorSet anim = new AnimatorSet();
+ Animator first = getHandleAnimator(view, 0, 1.1f, isLeft, 750,
+ new PathInterpolator(0, 0.45f, .67f, 1f));
+ Interpolator secondInterpolator = new PathInterpolator(0.33f, 0, 0.67f, 1f);
+ Animator second = getHandleAnimator(view, 1.1f, 0.97f, isLeft, 400,
+ secondInterpolator);
+ Animator third = getHandleAnimator(view, 0.97f, 1.02f, isLeft, 400,
+ secondInterpolator);
+ Animator fourth = getHandleAnimator(view, 1.02f, 1f, isLeft, 400,
+ secondInterpolator);
+ anim.play(first).before(second);
+ anim.play(second).before(third);
+ anim.play(third).before(fourth);
+ anim.start();
+ } else {
+ view.animate().cancel();
+ view.animate()
+ .setInterpolator(new AccelerateInterpolator(1.5f))
+ .setDuration(250)
+ .alpha(0f);
+ }
+
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java b/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java
index 2a82d215e44a..739eade35ca6 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java
@@ -24,8 +24,7 @@ import android.os.SystemClock;
import androidx.slice.Clock;
import com.android.internal.app.AssistUtils;
-import com.android.systemui.ScreenDecorations;
-import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.statusbar.NavigationBarController;
import java.util.EnumMap;
import java.util.Map;
@@ -69,8 +68,9 @@ public abstract class AssistModule {
}
@Provides
- static ScreenDecorations provideScreenDecorations(Context context) {
- return SysUiServiceProvider.getComponent(context, ScreenDecorations.class);
+ static AssistHandleViewController provideAssistHandleViewController(
+ NavigationBarController navigationBarController) {
+ return navigationBarController.getAssistHandlerViewController();
}
@Provides
diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java b/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
index b346a6eb2b3c..bf81e1d3b7f1 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
@@ -38,9 +38,9 @@ import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.systemui.Dependency;
import com.android.systemui.R;
-import com.android.systemui.ScreenDecorations;
-import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.assist.AssistHandleViewController;
import com.android.systemui.assist.AssistManager;
+import com.android.systemui.statusbar.NavigationBarController;
import java.util.Locale;
@@ -163,9 +163,11 @@ public class DefaultUiController implements AssistManager.UiController {
}
private void updateAssistHandleVisibility() {
- ScreenDecorations decorations = SysUiServiceProvider.getComponent(mRoot.getContext(),
- ScreenDecorations.class);
- decorations.setAssistHintBlocked(mInvocationInProgress);
+ AssistHandleViewController controller = Dependency.get(NavigationBarController.class)
+ .getAssistHandlerViewController();
+ if (controller != null) {
+ controller.setAssistHintBlocked(mInvocationInProgress);
+ }
}
private void attach() {
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
index dfd83a552bf3..a2014004fe6c 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
@@ -148,7 +148,11 @@ public class DozeSensors {
mProximitySensor = new ProximitySensor(context, sensorManager);
mProximitySensor.register(
- proximityEvent -> mProxCallback.accept(!proximityEvent.getNear()));
+ proximityEvent -> {
+ if (proximityEvent != null) {
+ mProxCallback.accept(!proximityEvent.getNear());
+ }
+ });
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java b/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java
index 55ae61de5bc6..b9f3a7fcc63b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java
@@ -18,11 +18,16 @@ package com.android.systemui.qs;
import static com.android.systemui.Dependency.BG_HANDLER;
import static com.android.systemui.Dependency.BG_HANDLER_NAME;
+import static com.android.systemui.Dependency.MAIN_LOOPER;
+import static com.android.systemui.Dependency.MAIN_LOOPER_NAME;
import static com.android.systemui.util.InjectionInflationController.VIEW_CONTEXT;
+import android.annotation.MainThread;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
import android.provider.Settings;
import android.telephony.SubscriptionManager;
import android.util.AttributeSet;
@@ -39,6 +44,8 @@ import com.android.systemui.R;
import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.statusbar.policy.NetworkController;
+import java.util.function.Consumer;
+
import javax.inject.Inject;
import javax.inject.Named;
@@ -46,7 +53,6 @@ import javax.inject.Named;
* Displays Carrier name and network status in QS
*/
public class QSCarrierGroup extends LinearLayout implements
- CarrierTextController.CarrierTextCallback,
NetworkController.SignalCallback, View.OnClickListener {
private static final String TAG = "QSCarrierGroup";
@@ -56,12 +62,14 @@ public class QSCarrierGroup extends LinearLayout implements
private static final int SIM_SLOTS = 3;
private final NetworkController mNetworkController;
private final Handler mBgHandler;
+ private final H mMainHandler;
private View[] mCarrierDividers = new View[SIM_SLOTS - 1];
private QSCarrier[] mCarrierGroups = new QSCarrier[SIM_SLOTS];
private TextView mNoSimTextView;
private final CellSignalState[] mInfos = new CellSignalState[SIM_SLOTS];
private CarrierTextController mCarrierTextController;
+ private CarrierTextController.CarrierTextCallback mCallback;
private ActivityStarter mActivityStarter;
private boolean mListening;
@@ -69,11 +77,19 @@ public class QSCarrierGroup extends LinearLayout implements
@Inject
public QSCarrierGroup(@Named(VIEW_CONTEXT) Context context, AttributeSet attrs,
NetworkController networkController, ActivityStarter activityStarter,
- @Named(BG_HANDLER_NAME) Handler handler) {
+ @Named(BG_HANDLER_NAME) Handler handler,
+ @Named(MAIN_LOOPER_NAME) Looper looper) {
super(context, attrs);
mNetworkController = networkController;
mActivityStarter = activityStarter;
mBgHandler = handler;
+ mMainHandler = new H(looper, this::handleUpdateCarrierInfo, this::handleUpdateState);
+ mCallback = new Callback(mMainHandler);
+ }
+
+ @VisibleForTesting
+ protected CarrierTextController.CarrierTextCallback getCallback() {
+ return mCallback;
}
@VisibleForTesting
@@ -81,7 +97,8 @@ public class QSCarrierGroup extends LinearLayout implements
this(context, attrs,
Dependency.get(NetworkController.class),
Dependency.get(ActivityStarter.class),
- Dependency.get(BG_HANDLER));
+ Dependency.get(BG_HANDLER),
+ Dependency.get(MAIN_LOOPER));
}
@Override
@@ -136,14 +153,20 @@ public class QSCarrierGroup extends LinearLayout implements
if (mNetworkController.hasVoiceCallingFeature()) {
mNetworkController.addCallback(this);
}
- mCarrierTextController.setListening(this);
+ mCarrierTextController.setListening(mCallback);
} else {
mNetworkController.removeCallback(this);
mCarrierTextController.setListening(null);
}
}
+ @MainThread
private void handleUpdateState() {
+ if (!mMainHandler.getLooper().isCurrentThread()) {
+ mMainHandler.obtainMessage(H.MSG_UPDATE_STATE).sendToTarget();
+ return;
+ }
+
for (int i = 0; i < SIM_SLOTS; i++) {
mCarrierGroups[i].updateState(mInfos[i]);
}
@@ -163,8 +186,13 @@ public class QSCarrierGroup extends LinearLayout implements
return SubscriptionManager.getSlotIndex(subscriptionId);
}
- @Override
- public void updateCarrierInfo(CarrierTextController.CarrierTextCallbackInfo info) {
+ @MainThread
+ private void handleUpdateCarrierInfo(CarrierTextController.CarrierTextCallbackInfo info) {
+ if (!mMainHandler.getLooper().isCurrentThread()) {
+ mMainHandler.obtainMessage(H.MSG_UPDATE_CARRIER_INFO, info).sendToTarget();
+ return;
+ }
+
mNoSimTextView.setVisibility(View.GONE);
if (!info.airplaneMode && info.anySimReady) {
boolean[] slotSeen = new boolean[SIM_SLOTS];
@@ -207,7 +235,7 @@ public class QSCarrierGroup extends LinearLayout implements
mNoSimTextView.setText(info.carrierText);
mNoSimTextView.setVisibility(View.VISIBLE);
}
- handleUpdateState();
+ handleUpdateState(); // handleUpdateCarrierInfo is always called from main thread.
}
@Override
@@ -230,7 +258,7 @@ public class QSCarrierGroup extends LinearLayout implements
mInfos[slotIndex].contentDescription = statusIcon.contentDescription;
mInfos[slotIndex].typeContentDescription = typeContentDescription;
mInfos[slotIndex].roaming = roaming;
- handleUpdateState();
+ mMainHandler.obtainMessage(H.MSG_UPDATE_STATE).sendToTarget();
}
@Override
@@ -240,7 +268,7 @@ public class QSCarrierGroup extends LinearLayout implements
mInfos[i].visible = false;
}
}
- handleUpdateState();
+ mMainHandler.obtainMessage(H.MSG_UPDATE_STATE).sendToTarget();
}
static final class CellSignalState {
@@ -250,4 +278,47 @@ public class QSCarrierGroup extends LinearLayout implements
String typeContentDescription;
boolean roaming;
}
+
+ private static class H extends Handler {
+ private Consumer<CarrierTextController.CarrierTextCallbackInfo> mUpdateCarrierInfo;
+ private Runnable mUpdateState;
+ static final int MSG_UPDATE_CARRIER_INFO = 0;
+ static final int MSG_UPDATE_STATE = 1;
+
+ H(Looper looper,
+ Consumer<CarrierTextController.CarrierTextCallbackInfo> updateCarrierInfo,
+ Runnable updateState) {
+ super(looper);
+ mUpdateCarrierInfo = updateCarrierInfo;
+ mUpdateState = updateState;
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_UPDATE_CARRIER_INFO:
+ mUpdateCarrierInfo.accept(
+ (CarrierTextController.CarrierTextCallbackInfo) msg.obj);
+ break;
+ case MSG_UPDATE_STATE:
+ mUpdateState.run();
+ break;
+ default:
+ super.handleMessage(msg);
+ }
+ }
+ }
+
+ private static class Callback implements CarrierTextController.CarrierTextCallback {
+ private H mMainHandler;
+
+ Callback(H handler) {
+ mMainHandler = handler;
+ }
+
+ @Override
+ public void updateCarrierInfo(CarrierTextController.CarrierTextCallbackInfo info) {
+ mMainHandler.obtainMessage(H.MSG_UPDATE_CARRIER_INFO, info).sendToTarget();
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
index 7bcbd3683130..09f80455a1b0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
@@ -37,6 +37,7 @@ import androidx.annotation.Nullable;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.statusbar.RegisterStatusBarResult;
import com.android.systemui.Dependency;
+import com.android.systemui.assist.AssistHandleViewController;
import com.android.systemui.plugins.DarkIconDispatcher;
import com.android.systemui.statusbar.CommandQueue.Callbacks;
import com.android.systemui.statusbar.phone.AutoHideController;
@@ -233,4 +234,9 @@ public class NavigationBarController implements Callbacks {
public NavigationBarFragment getDefaultNavigationBarFragment() {
return mNavigationBars.get(DEFAULT_DISPLAY);
}
+
+ /** @return {@link AssistHandleViewController} (only on the default display). */
+ public AssistHandleViewController getAssistHandlerViewController() {
+ return getDefaultNavigationBarFragment().getAssistHandlerViewController();
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index b6b149dd049a..90301c59dc68 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -22,6 +22,7 @@ import android.annotation.Nullable;
import android.app.Notification;
import android.content.Context;
import android.service.notification.NotificationListenerService;
+import android.service.notification.NotificationListenerService.Ranking;
import android.service.notification.StatusBarNotification;
import android.util.ArrayMap;
import android.util.Log;
@@ -390,7 +391,7 @@ public class NotificationEntryManager implements
}
mNotificationData.updateRanking(rankingMap);
- NotificationListenerService.Ranking ranking = new NotificationListenerService.Ranking();
+ Ranking ranking = new Ranking();
rankingMap.getRanking(key, ranking);
NotificationEntry entry = new NotificationEntry(notification, ranking);
@@ -513,10 +514,11 @@ public class NotificationEntryManager implements
if (rankingMap == null) {
return;
}
- NotificationListenerService.Ranking ranking = new NotificationListenerService.Ranking();
for (NotificationEntry pendingNotification : mPendingNotifications.values()) {
- rankingMap.getRanking(pendingNotification.key, ranking);
- pendingNotification.setRanking(ranking);
+ Ranking ranking = new Ranking();
+ if (rankingMap.getRanking(pendingNotification.key(), ranking)) {
+ pendingNotification.setRanking(ranking);
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
index 2b8c86b8c549..b87140dddec3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
@@ -86,8 +86,8 @@ import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.util.LatencyTracker;
import com.android.systemui.Dependency;
import com.android.systemui.R;
-import com.android.systemui.ScreenDecorations;
import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.assist.AssistHandleViewController;
import com.android.systemui.assist.AssistManager;
import com.android.systemui.fragments.FragmentHostManager;
import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
@@ -174,7 +174,10 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
public int mDisplayId;
private boolean mIsOnDefaultDisplay;
public boolean mHomeBlockedThisTouch;
- private ScreenDecorations mScreenDecorations;
+
+ /** Only for default display */
+ @Nullable
+ private AssistHandleViewController mAssistHandlerViewController;
private Handler mHandler = Dependency.get(Dependency.MAIN_HANDLER);
@@ -357,17 +360,22 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
mDisabledFlags2 |= StatusBarManager.DISABLE2_ROTATE_SUGGESTIONS;
}
setDisabled2Flags(mDisabledFlags2);
-
- mScreenDecorations = SysUiServiceProvider.getComponent(getContext(),
- ScreenDecorations.class);
- getBarTransitions().addDarkIntensityListener(mScreenDecorations);
+ if (mIsOnDefaultDisplay) {
+ mAssistHandlerViewController =
+ new AssistHandleViewController(mHandler, mNavigationBarView);
+ getBarTransitions().addDarkIntensityListener(mAssistHandlerViewController);
+ }
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mNavigationBarView != null) {
- mNavigationBarView.getBarTransitions().removeDarkIntensityListener(mScreenDecorations);
+ if (mIsOnDefaultDisplay) {
+ mNavigationBarView.getBarTransitions()
+ .removeDarkIntensityListener(mAssistHandlerViewController);
+ mAssistHandlerViewController = null;
+ }
mNavigationBarView.getBarTransitions().destroy();
mNavigationBarView.getLightTransitionsController().destroy(getContext());
}
@@ -1019,6 +1027,11 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
delay + StackStateAnimator.ANIMATION_DURATION_GO_TO_FULL_SHADE);
}
+ @Nullable
+ public AssistHandleViewController getAssistHandlerViewController() {
+ return mAssistHandlerViewController;
+ }
+
/**
* Performs transitions on navigation bar.
*
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
index 3b5e12c4ef96..64ab060e14a2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
@@ -45,7 +45,6 @@ import android.testing.TestableLooper.RunWithLooper;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
-import android.view.WindowManagerPolicyConstants;
import androidx.test.filters.SmallTest;
@@ -53,7 +52,6 @@ import com.android.systemui.R.dimen;
import com.android.systemui.ScreenDecorations.TunablePaddingTagListener;
import com.android.systemui.fragments.FragmentHostManager;
import com.android.systemui.fragments.FragmentService;
-import com.android.systemui.statusbar.phone.NavigationModeController;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.phone.StatusBarWindowView;
import com.android.systemui.tuner.TunablePadding;
@@ -80,7 +78,6 @@ public class ScreenDecorationsTest extends SysuiTestCase {
private TunerService mTunerService;
private StatusBarWindowView mView;
private TunablePaddingService mTunablePaddingService;
- private NavigationModeController mNavigationModeController;
@Before
public void setup() {
@@ -90,8 +87,6 @@ public class ScreenDecorationsTest extends SysuiTestCase {
mTunablePaddingService = mDependency.injectMockDependency(TunablePaddingService.class);
mTunerService = mDependency.injectMockDependency(TunerService.class);
mFragmentService = mDependency.injectMockDependency(FragmentService.class);
- mNavigationModeController = mDependency.injectMockDependency(
- NavigationModeController.class);
mStatusBar = mock(StatusBar.class);
mWindowManager = mock(WindowManager.class);
@@ -213,54 +208,6 @@ public class ScreenDecorationsTest extends SysuiTestCase {
}
@Test
- public void testAssistHandles() {
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.dimen.rounded_corner_radius, 0);
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.dimen.rounded_corner_radius_top, 0);
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
- mContext.getOrCreateTestableResources()
- .addOverride(dimen.rounded_corner_content_padding, 0);
- when(mNavigationModeController.addListener(any())).thenReturn(
- WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL);
-
- mScreenDecorations.start();
-
- // Add 2 windows for rounded corners (top and bottom).
- verify(mWindowManager, times(2)).addView(any(), any());
- }
-
- @Test
- public void testDelayedAssistHandles() {
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.dimen.rounded_corner_radius, 0);
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.dimen.rounded_corner_radius_top, 0);
- mContext.getOrCreateTestableResources().addOverride(
- com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
- mContext.getOrCreateTestableResources()
- .addOverride(dimen.rounded_corner_content_padding, 0);
- when(mNavigationModeController.addListener(any())).thenReturn(
- WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON);
-
- mScreenDecorations.start();
-
- // No handles and no corners
- verify(mWindowManager, never()).addView(any(), any());
-
- mScreenDecorations.handleNavigationModeChange(
- WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL);
-
- // Add 2 windows for rounded corners (top and bottom).
- verify(mWindowManager, times(2)).addView(any(), any());
- }
-
- @Test
public void hasRoundedCornerOverlayFlagSet() {
assertThat(mScreenDecorations.getWindowLayoutParams().privateFlags
& PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java
index 9c920f52d56a..fbb8e0c171cd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java
@@ -38,7 +38,6 @@ import androidx.test.filters.SmallTest;
import com.android.internal.app.AssistUtils;
import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
import com.android.systemui.DumpController;
-import com.android.systemui.ScreenDecorations;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.recents.OverviewProxyService;
@@ -64,7 +63,6 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
private AssistHandleBehaviorController mAssistHandleBehaviorController;
- @Mock private ScreenDecorations mMockScreenDecorations;
@Mock private AssistUtils mMockAssistUtils;
@Mock private Handler mMockHandler;
@Mock private PhenotypeHelper mMockPhenotypeHelper;
@@ -74,6 +72,7 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
@Mock private AssistHandleBehaviorController.BehaviorController mMockTestBehavior;
@Mock private NavigationModeController mMockNavigationModeController;
@Mock private DumpController mMockDumpController;
+ @Mock private AssistHandleViewController mMockAssistHandleViewController;
@Before
public void setup() {
@@ -97,7 +96,7 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
mContext,
mMockAssistUtils,
mMockHandler,
- () -> mMockScreenDecorations,
+ () -> mMockAssistHandleViewController,
mMockPhenotypeHelper,
behaviorMap,
mMockNavigationModeController,
@@ -114,14 +113,14 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.showAndStay();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.hide();
// Assert
- verify(mMockScreenDecorations).setAssistHintVisible(false);
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -129,13 +128,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.hide();
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -143,14 +142,14 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndStay();
// Assert
- verify(mMockScreenDecorations).setAssistHintVisible(true);
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -158,13 +157,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.showAndStay();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndStay();
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -172,13 +171,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(null);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndStay();
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -186,15 +185,15 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGo();
// Assert
- InOrder inOrder = inOrder(mMockScreenDecorations);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(true);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
+ InOrder inOrder = inOrder(mMockAssistHandleViewController);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
inOrder.verifyNoMoreInteractions();
}
@@ -203,14 +202,14 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.showAndStay();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGo();
// Assert
- verify(mMockScreenDecorations).setAssistHintVisible(false);
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -221,13 +220,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
eq(SystemUiDeviceConfigFlags.ASSIST_HANDLES_SHOWN_FREQUENCY_THRESHOLD_MS),
anyLong())).thenReturn(10000L);
mAssistHandleBehaviorController.showAndGo();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGo();
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -235,13 +234,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(null);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGo();
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -249,15 +248,15 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
// Assert
- InOrder inOrder = inOrder(mMockScreenDecorations);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(true);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
+ InOrder inOrder = inOrder(mMockAssistHandleViewController);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
inOrder.verifyNoMoreInteractions();
}
@@ -266,14 +265,14 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.showAndStay();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
// Assert
- verify(mMockScreenDecorations).setAssistHintVisible(false);
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -281,16 +280,16 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
mAssistHandleBehaviorController.showAndStay();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGoDelayed(1000, true);
// Assert
- InOrder inOrder = inOrder(mMockScreenDecorations);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(true);
- inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
+ InOrder inOrder = inOrder(mMockAssistHandleViewController);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+ inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
inOrder.verifyNoMoreInteractions();
}
@@ -302,13 +301,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
eq(SystemUiDeviceConfigFlags.ASSIST_HANDLES_SHOWN_FREQUENCY_THRESHOLD_MS),
anyLong())).thenReturn(10000L);
mAssistHandleBehaviorController.showAndGo();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
@@ -316,13 +315,13 @@ public class AssistHandleBehaviorControllerTest extends SysuiTestCase {
// Arrange
when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(null);
mAssistHandleBehaviorController.hide();
- reset(mMockScreenDecorations);
+ reset(mMockAssistHandleViewController);
// Act
mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
// Assert
- verifyNoMoreInteractions(mMockScreenDecorations);
+ verifyNoMoreInteractions(mMockAssistHandleViewController);
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java
new file mode 100644
index 000000000000..6e21ae218621
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.assist;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper.RunWithLooper;
+import android.view.View;
+import android.view.ViewPropertyAnimator;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.CornerHandleView;
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@RunWithLooper
+public class AssistHandleViewControllerTest extends SysuiTestCase {
+
+ private AssistHandleViewController mAssistHandleViewController;
+
+ @Mock private Handler mMockHandler;
+ @Mock private Looper mMockLooper;
+ @Mock private View mMockBarView;
+ @Mock private CornerHandleView mMockAssistHint;
+ @Mock private ViewPropertyAnimator mMockAnimator;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ when(mMockBarView.findViewById(anyInt())).thenReturn(mMockAssistHint);
+ when(mMockAssistHint.animate()).thenReturn(mMockAnimator);
+ when(mMockAnimator.setInterpolator(any())).thenReturn(mMockAnimator);
+ when(mMockAnimator.setDuration(anyLong())).thenReturn(mMockAnimator);
+ doNothing().when(mMockAnimator).cancel();
+ when(mMockHandler.getLooper()).thenReturn(mMockLooper);
+ when(mMockLooper.isCurrentThread()).thenReturn(true);
+
+ mAssistHandleViewController = new AssistHandleViewController(mMockHandler, mMockBarView);
+ }
+
+ @Test
+ public void testSetVisibleWithoutBlocked() {
+ // Act
+ mAssistHandleViewController.setAssistHintVisible(true);
+
+ // Assert
+ assertTrue(mAssistHandleViewController.mAssistHintVisible);
+ }
+
+ @Test
+ public void testSetInvisibleWithoutBlocked() {
+ // Arrange
+ mAssistHandleViewController.setAssistHintVisible(true);
+
+ // Act
+ mAssistHandleViewController.setAssistHintVisible(false);
+
+ // Assert
+ assertFalse(mAssistHandleViewController.mAssistHintVisible);
+ }
+
+ @Test
+ public void testSetVisibleWithBlocked() {
+ // Act
+ mAssistHandleViewController.setAssistHintBlocked(true);
+ mAssistHandleViewController.setAssistHintVisible(true);
+
+ // Assert
+ assertFalse(mAssistHandleViewController.mAssistHintVisible);
+ assertTrue(mAssistHandleViewController.mAssistHintBlocked);
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java
index f29392b2c5d6..a2a20a9538fc 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java
@@ -20,6 +20,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import android.os.Handler;
import android.telephony.SubscriptionManager;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -28,6 +29,7 @@ import android.view.LayoutInflater;
import androidx.test.filters.SmallTest;
import com.android.keyguard.CarrierTextController;
+import com.android.systemui.Dependency;
import com.android.systemui.R;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.utils.leaks.LeakCheckedTest;
@@ -45,13 +47,20 @@ import org.mockito.stubbing.Answer;
public class QSCarrierGroupTest extends LeakCheckedTest {
private QSCarrierGroup mCarrierGroup;
+ private CarrierTextController.CarrierTextCallback mCallback;
+ private TestableLooper mTestableLooper;
@Before
public void setup() throws Exception {
injectLeakCheckedDependencies(ALL_SUPPORTED_CLASSES);
- TestableLooper.get(this).runWithLooper(
+ mTestableLooper = TestableLooper.get(this);
+ mDependency.injectTestDependency(
+ Dependency.BG_HANDLER, new Handler(mTestableLooper.getLooper()));
+ mDependency.injectTestDependency(Dependency.MAIN_LOOPER, mTestableLooper.getLooper());
+ mTestableLooper.runWithLooper(
() -> mCarrierGroup = (QSCarrierGroup) LayoutInflater.from(mContext).inflate(
R.layout.qs_carrier_group, null));
+ mCallback = mCarrierGroup.getCallback();
}
@Test // throws no Exception
@@ -72,7 +81,7 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{""},
false,
new int[]{0});
- spiedCarrierGroup.updateCarrierInfo(c1);
+ mCallback.updateCarrierInfo(c1);
// listOfCarriers length 1, subscriptionIds length 1, anySims true
CarrierTextController.CarrierTextCallbackInfo
@@ -81,7 +90,7 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{""},
true,
new int[]{0});
- spiedCarrierGroup.updateCarrierInfo(c2);
+ mCallback.updateCarrierInfo(c2);
// listOfCarriers length 2, subscriptionIds length 2, anySims false
CarrierTextController.CarrierTextCallbackInfo
@@ -90,7 +99,7 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{"", ""},
false,
new int[]{0, 1});
- spiedCarrierGroup.updateCarrierInfo(c3);
+ mCallback.updateCarrierInfo(c3);
// listOfCarriers length 2, subscriptionIds length 2, anySims true
CarrierTextController.CarrierTextCallbackInfo
@@ -99,7 +108,9 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{"", ""},
true,
new int[]{0, 1});
- spiedCarrierGroup.updateCarrierInfo(c4);
+ mCallback.updateCarrierInfo(c4);
+
+ mTestableLooper.processAllMessages();
}
@Test // throws no Exception
@@ -120,7 +131,7 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{"", ""},
false,
new int[]{0});
- spiedCarrierGroup.updateCarrierInfo(c1);
+ mCallback.updateCarrierInfo(c1);
// listOfCarriers length 2, subscriptionIds length 1, anySims true
CarrierTextController.CarrierTextCallbackInfo
@@ -129,7 +140,7 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{"", ""},
true,
new int[]{0});
- spiedCarrierGroup.updateCarrierInfo(c2);
+ mCallback.updateCarrierInfo(c2);
// listOfCarriers length 1, subscriptionIds length 2, anySims false
CarrierTextController.CarrierTextCallbackInfo
@@ -138,7 +149,7 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{""},
false,
new int[]{0, 1});
- spiedCarrierGroup.updateCarrierInfo(c3);
+ mCallback.updateCarrierInfo(c3);
// listOfCarriers length 1, subscriptionIds length 2, anySims true
CarrierTextController.CarrierTextCallbackInfo
@@ -147,7 +158,8 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{""},
true,
new int[]{0, 1});
- spiedCarrierGroup.updateCarrierInfo(c4);
+ mCallback.updateCarrierInfo(c4);
+ mTestableLooper.processAllMessages();
}
@Test // throws no Exception
@@ -161,7 +173,8 @@ public class QSCarrierGroupTest extends LeakCheckedTest {
new CharSequence[]{"", ""},
true,
new int[]{0, 1});
- spiedCarrierGroup.updateCarrierInfo(c4);
+ mCallback.updateCarrierInfo(c4);
+ mTestableLooper.processAllMessages();
}
@Test // throws no Exception
diff --git a/services/backup/backuplib/java/com/android/server/backup/TransportManager.java b/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
index 30ce4cf2fd3f..de48f4b13d7b 100644
--- a/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
+++ b/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
@@ -93,7 +93,8 @@ public class TransportManager {
mTransportWhitelist = Preconditions.checkNotNull(whitelist);
mCurrentTransportName = selectedTransport;
mTransportStats = new TransportStats();
- mTransportClientManager = new TransportClientManager(mUserId, context, mTransportStats);
+ mTransportClientManager = TransportClientManager.createEncryptingClientManager(mUserId,
+ context, mTransportStats);
}
@VisibleForTesting
diff --git a/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java
index a4e9b1091bed..72b1ee741d95 100644
--- a/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java
+++ b/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java
@@ -19,18 +19,21 @@ package com.android.server.backup.transport;
import static com.android.server.backup.TransportManager.SERVICE_ACTION_TRANSPORT_HOST;
import static com.android.server.backup.transport.TransportUtils.formatMessage;
+import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
+import com.android.internal.backup.IBackupTransport;
import com.android.server.backup.TransportManager;
import com.android.server.backup.transport.TransportUtils.Priority;
import java.io.PrintWriter;
import java.util.Map;
import java.util.WeakHashMap;
+import java.util.function.Function;
/**
* Manages the creation and disposal of {@link TransportClient}s. The only class that should use
@@ -38,6 +41,12 @@ import java.util.WeakHashMap;
*/
public class TransportClientManager {
private static final String TAG = "TransportClientManager";
+ private static final String SERVICE_ACTION_ENCRYPTING_TRANSPORT =
+ "android.encryption.BACKUP_ENCRYPTION";
+ private static final ComponentName ENCRYPTING_TRANSPORT = new ComponentName(
+ "com.android.server.backup.encryption",
+ "com.android.server.backup.encryption.BackupEncryptionService");
+ private static final String ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY = "transport";
private final @UserIdInt int mUserId;
private final Context mContext;
@@ -45,12 +54,64 @@ public class TransportClientManager {
private final Object mTransportClientsLock = new Object();
private int mTransportClientsCreated = 0;
private Map<TransportClient, String> mTransportClientsCallerMap = new WeakHashMap<>();
+ private final Function<ComponentName, Intent> mIntentFunction;
+
+ /**
+ * Return an {@link Intent} which resolves to an intermediate {@link IBackupTransport} that
+ * encrypts (or decrypts) the data when sending it (or receiving it) from the {@link
+ * IBackupTransport} for the given {@link ComponentName}.
+ */
+ public static Intent getEncryptingTransportIntent(ComponentName tranportComponent) {
+ return new Intent(SERVICE_ACTION_ENCRYPTING_TRANSPORT)
+ .setComponent(ENCRYPTING_TRANSPORT)
+ .putExtra(ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY, tranportComponent);
+ }
+
+ /**
+ * Return an {@link Intent} which resolves to the {@link IBackupTransport} for the {@link
+ * ComponentName}.
+ */
+ private static Intent getRealTransportIntent(ComponentName transportComponent) {
+ return new Intent(SERVICE_ACTION_TRANSPORT_HOST).setComponent(transportComponent);
+ }
+
+ /**
+ * Given a {@link Intent} originally created by {@link
+ * #getEncryptingTransportIntent(ComponentName)}, returns the {@link Intent} which resolves to
+ * the {@link IBackupTransport} for that {@link ComponentName}.
+ */
+ public static Intent getRealTransportIntent(Intent encryptingTransportIntent) {
+ ComponentName transportComponent = encryptingTransportIntent.getParcelableExtra(
+ ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY);
+ Intent intent = getRealTransportIntent(transportComponent)
+ .putExtras(encryptingTransportIntent.getExtras());
+ intent.removeExtra(ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY);
+ return intent;
+ }
+
+ /**
+ * Create a {@link TransportClientManager} such that {@link #getTransportClient(ComponentName,
+ * Bundle, String)} returns a {@link TransportClient} which connects to an intermediate {@link
+ * IBackupTransport} that encrypts (or decrypts) the data when sending it (or receiving it) from
+ * the {@link IBackupTransport} for the given {@link ComponentName}.
+ */
+ public static TransportClientManager createEncryptingClientManager(@UserIdInt int userId,
+ Context context, TransportStats transportStats) {
+ return new TransportClientManager(userId, context, transportStats,
+ TransportClientManager::getEncryptingTransportIntent);
+ }
public TransportClientManager(@UserIdInt int userId, Context context,
TransportStats transportStats) {
+ this(userId, context, transportStats, TransportClientManager::getRealTransportIntent);
+ }
+
+ private TransportClientManager(@UserIdInt int userId, Context context,
+ TransportStats transportStats, Function<ComponentName, Intent> intentFunction) {
mUserId = userId;
mContext = context;
mTransportStats = transportStats;
+ mIntentFunction = intentFunction;
}
/**
@@ -64,10 +125,7 @@ public class TransportClientManager {
* @return A {@link TransportClient}.
*/
public TransportClient getTransportClient(ComponentName transportComponent, String caller) {
- Intent bindIntent =
- new Intent(SERVICE_ACTION_TRANSPORT_HOST).setComponent(transportComponent);
-
- return getTransportClient(transportComponent, caller, bindIntent);
+ return getTransportClient(transportComponent, null, caller);
}
/**
@@ -82,11 +140,11 @@ public class TransportClientManager {
* @return A {@link TransportClient}.
*/
public TransportClient getTransportClient(
- ComponentName transportComponent, Bundle extras, String caller) {
- Intent bindIntent =
- new Intent(SERVICE_ACTION_TRANSPORT_HOST).setComponent(transportComponent);
- bindIntent.putExtras(extras);
-
+ ComponentName transportComponent, @Nullable Bundle extras, String caller) {
+ Intent bindIntent = mIntentFunction.apply(transportComponent);
+ if (extras != null) {
+ bindIntent.putExtras(extras);
+ }
return getTransportClient(transportComponent, caller, bindIntent);
}
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 8367e89058cf..f70d511759f0 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -196,6 +196,9 @@ class StorageManagerService extends IStorageManager.Stub
private static final String ZRAM_ENABLED_PROPERTY =
"persist.sys.zram_enabled";
+ private static final boolean IS_FUSE_ENABLED =
+ SystemProperties.getBoolean("persist.sys.fuse", false);
+
private static final boolean ENABLE_ISOLATED_STORAGE = StorageManager.hasIsolatedStorage();
/**
@@ -346,6 +349,9 @@ class StorageManagerService extends IStorageManager.Stub
@GuardedBy("mLock")
private String mMoveTargetUuid;
+ @Nullable
+ private volatile String mMediaStoreAuthorityPackageName = null;
+
private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
/** Holding lock for AppFuse business */
@@ -1661,6 +1667,15 @@ class StorageManagerService extends IStorageManager.Stub
ServiceManager.getService("package"));
mIAppOpsService = IAppOpsService.Stub.asInterface(
ServiceManager.getService(Context.APP_OPS_SERVICE));
+
+ ProviderInfo provider = mPmInternal.resolveContentProvider(
+ MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE
+ | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+ UserHandle.getUserId(UserHandle.USER_SYSTEM));
+ if (provider != null) {
+ mMediaStoreAuthorityPackageName = provider.packageName;
+ }
+
try {
mIAppOpsService.startWatchingMode(OP_REQUEST_INSTALL_PACKAGES, null, mAppOpsCallback);
mIAppOpsService.startWatchingMode(OP_LEGACY_STORAGE, null, mAppOpsCallback);
@@ -3672,6 +3687,11 @@ class StorageManagerService extends IStorageManager.Stub
return Zygote.MOUNT_EXTERNAL_NONE;
}
+ if (IS_FUSE_ENABLED && packageName.equals(mMediaStoreAuthorityPackageName)) {
+ // Determine if caller requires pass_through mount
+ return Zygote.MOUNT_EXTERNAL_PASS_THROUGH;
+ }
+
// Determine if caller is holding runtime permission
final boolean hasRead = StorageManager.checkPermissionAndCheckOp(mContext, false, 0,
uid, packageName, READ_EXTERNAL_STORAGE, OP_READ_EXTERNAL_STORAGE);
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index caa4f63d387d..c412ebdc9033 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -284,11 +284,12 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
case MSG_UPDATE_DEFAULT_SUB: {
int newDefaultPhoneId = msg.arg1;
- int newDefaultSubId = (Integer)(msg.obj);
+ int newDefaultSubId = msg.arg2;
if (VDBG) {
log("MSG_UPDATE_DEFAULT_SUB:current mDefaultSubId=" + mDefaultSubId
- + " current mDefaultPhoneId=" + mDefaultPhoneId + " newDefaultSubId= "
- + newDefaultSubId + " newDefaultPhoneId=" + newDefaultPhoneId);
+ + " current mDefaultPhoneId=" + mDefaultPhoneId
+ + " newDefaultSubId=" + newDefaultSubId
+ + " newDefaultPhoneId=" + newDefaultPhoneId);
}
//Due to possible risk condition,(notify call back using the new
@@ -305,7 +306,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mDefaultSubId = newDefaultSubId;
mDefaultPhoneId = newDefaultPhoneId;
mLocalLog.log("Default subscription updated: mDefaultPhoneId="
- + mDefaultPhoneId + ", mDefaultSubId" + mDefaultSubId);
+ + mDefaultPhoneId + ", mDefaultSubId=" + mDefaultSubId);
}
}
}
@@ -335,22 +336,25 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
if (DBG) log("onReceive: userHandle=" + userHandle);
mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHED, userHandle, 0));
- } else if (action.equals(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED)) {
- Integer newDefaultSubIdObj = new Integer(intent.getIntExtra(
- PhoneConstants.SUBSCRIPTION_KEY,
- SubscriptionManager.getDefaultSubscriptionId()));
- int newDefaultPhoneId = intent.getIntExtra(PhoneConstants.PHONE_KEY,
- SubscriptionManager.getPhoneId(mDefaultSubId));
+ } else if (action.equals(SubscriptionManager.ACTION_DEFAULT_SUBSCRIPTION_CHANGED)) {
+ int newDefaultSubId = intent.getIntExtra(
+ SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
+ SubscriptionManager.getDefaultSubscriptionId());
+ int newDefaultPhoneId = intent.getIntExtra(
+ PhoneConstants.PHONE_KEY,
+ SubscriptionManager.getPhoneId(newDefaultSubId));
if (DBG) {
log("onReceive:current mDefaultSubId=" + mDefaultSubId
- + " current mDefaultPhoneId=" + mDefaultPhoneId + " newDefaultSubId= "
- + newDefaultSubIdObj + " newDefaultPhoneId=" + newDefaultPhoneId);
+ + " current mDefaultPhoneId=" + mDefaultPhoneId
+ + " newDefaultSubId=" + newDefaultSubId
+ + " newDefaultPhoneId=" + newDefaultPhoneId);
}
- if(validatePhoneId(newDefaultPhoneId) && (!newDefaultSubIdObj.equals(mDefaultSubId)
- || (newDefaultPhoneId != mDefaultPhoneId))) {
+ if (validatePhoneId(newDefaultPhoneId)
+ && (newDefaultSubId != mDefaultSubId
+ || newDefaultPhoneId != mDefaultPhoneId)) {
mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_DEFAULT_SUB,
- newDefaultPhoneId, 0, newDefaultSubIdObj));
+ newDefaultPhoneId, newDefaultSubId));
}
}
}
@@ -449,7 +453,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_USER_SWITCHED);
filter.addAction(Intent.ACTION_USER_REMOVED);
- filter.addAction(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
+ filter.addAction(SubscriptionManager.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
log("systemRunning register for intents");
mContext.registerReceiver(mBroadcastReceiver, filter);
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index c07f67b902ac..d7a68a1015a8 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -15267,7 +15267,7 @@ public class ActivityManagerService extends IActivityManager.Stub
mBatteryStatsService.removeUid(uid);
if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
- intent.getData().getSchemeSpecificPart());
+ intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
} else {
mAppOpsService.uidRemoved(uid);
}
diff --git a/services/core/java/com/android/server/display/DisplayModeDirector.java b/services/core/java/com/android/server/display/DisplayModeDirector.java
index 1fc0db3ff7cb..d24bd1aad1b1 100644
--- a/services/core/java/com/android/server/display/DisplayModeDirector.java
+++ b/services/core/java/com/android/server/display/DisplayModeDirector.java
@@ -49,8 +49,9 @@ import android.view.DisplayInfo;
import com.android.internal.os.BackgroundThread;
import com.android.internal.R;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterFactory;
import com.android.server.display.whitebalance.DisplayWhiteBalanceFactory;
-import com.android.server.display.whitebalance.AmbientFilter;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -970,7 +971,7 @@ public class DisplayModeDirector {
if (lightSensor != null) {
final Resources res = mContext.getResources();
- mAmbientFilter = DisplayWhiteBalanceFactory.createBrightnessFilter(res);
+ mAmbientFilter = AmbientFilterFactory.createBrightnessFilter(TAG, res);
mLightSensor = lightSensor;
onScreenOn(isDefaultDisplayOn());
diff --git a/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java b/services/core/java/com/android/server/display/utils/AmbientFilter.java
index 35808974b9e4..1a8412180c27 100644
--- a/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java
+++ b/services/core/java/com/android/server/display/utils/AmbientFilter.java
@@ -14,13 +14,10 @@
* limitations under the License.
*/
-package com.android.server.display.whitebalance;
+package com.android.server.display.utils;
import android.util.Slog;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.display.utils.RollingBuffer;
-
import java.io.PrintWriter;
import java.util.Arrays;
diff --git a/services/core/java/com/android/server/display/utils/AmbientFilterFactory.java b/services/core/java/com/android/server/display/utils/AmbientFilterFactory.java
new file mode 100644
index 000000000000..dfa1ddc67528
--- /dev/null
+++ b/services/core/java/com/android/server/display/utils/AmbientFilterFactory.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.display.utils;
+
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.util.TypedValue;
+
+public class AmbientFilterFactory {
+ /**
+ * Creates a temporal filter which functions as a weighted moving average buffer for recent
+ * sensor values.
+ * @param tag
+ * The tag used for dumping and logging.
+ * @param horizon
+ * How long ambient value changes are kept and taken into consideration.
+ * @param intercept
+ * Recent changes are prioritised by integrating their duration over y = x + intercept
+ * (the higher it is, the less prioritised recent changes are).
+ *
+ * @return
+ * An AmbientFiler.
+ *
+ * @throws IllegalArgumentException
+ * - Horizon is not positive.
+ * - Intercept not configured.
+ */
+ public static AmbientFilter createAmbientFilter(String tag, int horizon, float intercept) {
+ if (!Float.isNaN(intercept)) {
+ return new AmbientFilter.WeightedMovingAverageAmbientFilter(tag, horizon, intercept);
+ }
+ throw new IllegalArgumentException("missing configurations: "
+ + "expected config_displayWhiteBalanceBrightnessFilterIntercept");
+ }
+
+ /**
+ * Helper to create a default BrightnessFilter which has configuration in the resource file.
+ * @param tag
+ * The tag used for dumping and logging.
+ * @param resources
+ * The resources used to configure the various components.
+ *
+ * @return
+ * An AmbientFilter.
+ */
+ public static AmbientFilter createBrightnessFilter(String tag, Resources resources) {
+ final int horizon = resources.getInteger(
+ com.android.internal.R.integer.config_displayWhiteBalanceBrightnessFilterHorizon);
+ final float intercept = getFloat(resources,
+ com.android.internal.R.dimen.config_displayWhiteBalanceBrightnessFilterIntercept);
+
+ return createAmbientFilter(tag, horizon, intercept);
+ }
+
+ /**
+ * Helper to creates a default ColorTemperatureFilter which has configuration in the resource
+ * file.
+ * @param tag
+ * The tag used for dumping and logging.
+ * @param resources
+ * The resources used to configure the various components.
+ *
+ * @return
+ * An AmbientFilter.
+ */
+ public static AmbientFilter createColorTemperatureFilter(String tag, Resources resources) {
+ final int horizon = resources.getInteger(
+ com.android.internal.R.integer
+ .config_displayWhiteBalanceColorTemperatureFilterHorizon);
+ final float intercept = getFloat(resources,
+ com.android.internal.R.dimen
+ .config_displayWhiteBalanceColorTemperatureFilterIntercept);
+
+ return createAmbientFilter(tag, horizon, intercept);
+ }
+
+ // Instantiation is disabled.
+ private AmbientFilterFactory() { }
+
+ private static float getFloat(Resources resources, int id) {
+ TypedValue value = new TypedValue();
+
+ resources.getValue(id, value, true /* resolveRefs */);
+ if (value.type != TypedValue.TYPE_FLOAT) {
+ return Float.NaN;
+ }
+
+ return value.getFloat();
+ }
+}
+
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
index 7b1f4c3222f3..e8a577938b4c 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
@@ -24,6 +24,7 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
import com.android.server.LocalServices;
import com.android.server.display.color.ColorDisplayService.ColorDisplayServiceInternal;
+import com.android.server.display.utils.AmbientFilter;
import com.android.server.display.utils.History;
import java.io.PrintWriter;
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
index bf0a1d16219d..a72b1ed8f3ec 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
@@ -23,6 +23,8 @@ import android.os.Handler;
import android.util.TypedValue;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterFactory;
/**
* The DisplayWhiteBalanceFactory creates and configures an DisplayWhiteBalanceController.
@@ -58,10 +60,12 @@ public class DisplayWhiteBalanceFactory {
SensorManager sensorManager, Resources resources) {
final AmbientSensor.AmbientBrightnessSensor brightnessSensor =
createBrightnessSensor(handler, sensorManager, resources);
- final AmbientFilter brightnessFilter = createBrightnessFilter(resources);
+ final AmbientFilter brightnessFilter =
+ AmbientFilterFactory.createBrightnessFilter(BRIGHTNESS_FILTER_TAG, resources);
final AmbientSensor.AmbientColorTemperatureSensor colorTemperatureSensor =
createColorTemperatureSensor(handler, sensorManager, resources);
- final AmbientFilter colorTemperatureFilter = createColorTemperatureFilter(resources);
+ final AmbientFilter colorTemperatureFilter = AmbientFilterFactory
+ .createColorTemperatureFilter(COLOR_TEMPERATURE_FILTER_TAG, resources);
final DisplayWhiteBalanceThrottler throttler = createThrottler(resources);
final float[] displayWhiteBalanceLowLightAmbientBrightnesses = getFloatArray(resources,
com.android.internal.R.array
@@ -112,23 +116,6 @@ public class DisplayWhiteBalanceFactory {
}
/**
- * Creates a BrightnessFilter which functions as a weighted moving average buffer for recent
- * brightness values.
- */
- public static AmbientFilter createBrightnessFilter(Resources resources) {
- final int horizon = resources.getInteger(
- com.android.internal.R.integer.config_displayWhiteBalanceBrightnessFilterHorizon);
- final float intercept = getFloat(resources,
- com.android.internal.R.dimen.config_displayWhiteBalanceBrightnessFilterIntercept);
- if (!Float.isNaN(intercept)) {
- return new AmbientFilter.WeightedMovingAverageAmbientFilter(
- BRIGHTNESS_FILTER_TAG, horizon, intercept);
- }
- throw new IllegalArgumentException("missing configurations: "
- + "expected config_displayWhiteBalanceBrightnessFilterIntercept");
- }
-
- /**
* Creates an ambient color sensor instance to redirect sensor data to callbacks.
*/
@VisibleForTesting
@@ -143,21 +130,6 @@ public class DisplayWhiteBalanceFactory {
return new AmbientSensor.AmbientColorTemperatureSensor(handler, sensorManager, name, rate);
}
- private static AmbientFilter createColorTemperatureFilter(Resources resources) {
- final int horizon = resources.getInteger(
- com.android.internal.R.integer
- .config_displayWhiteBalanceColorTemperatureFilterHorizon);
- final float intercept = getFloat(resources,
- com.android.internal.R.dimen
- .config_displayWhiteBalanceColorTemperatureFilterIntercept);
- if (!Float.isNaN(intercept)) {
- return new AmbientFilter.WeightedMovingAverageAmbientFilter(
- COLOR_TEMPERATURE_FILTER_TAG, horizon, intercept);
- }
- throw new IllegalArgumentException("missing configurations: "
- + "expected config_displayWhiteBalanceColorTemperatureFilterIntercept");
- }
-
private static DisplayWhiteBalanceThrottler createThrottler(Resources resources) {
final int increaseDebounce = resources.getInteger(
com.android.internal.R.integer.config_displayWhiteBalanceDecreaseDebounce);
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 123e65e5b9ac..4d76374d5f14 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -17746,8 +17746,14 @@ public class PackageManagerService extends IPackageManager.Stub
}
}
if (removedAppId >= 0) {
+ // If a system app's updates are uninstalled the UID is not actually removed. Some
+ // services need to know the package name affected.
+ if (extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
+ extras.putString(Intent.EXTRA_PACKAGE_NAME, removedPackage);
+ }
+
packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
- removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
+ null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
null, null, broadcastUsers, instantUserIds);
}
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index fe529a152364..3f32f3dde3ae 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -496,6 +496,10 @@ class PackageManagerShellCommand extends ShellCommand {
getErrPrintWriter().println("Error: no package specified");
return 1;
}
+ userId = translateUserId(userId, true /*allowAll*/, "runPath");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
return displayPackageFilePath(pkg, userId);
}
@@ -718,6 +722,10 @@ class PackageManagerShellCommand extends ShellCommand {
final String filter = getNextArg();
+ userId = translateUserId(userId, true /*allowAll*/, "runListPackages");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
@SuppressWarnings("unchecked")
final ParceledListSlice<PackageInfo> slice =
mInterface.getInstalledPackages(getFlags, userId);
@@ -1285,7 +1293,7 @@ class PackageManagerShellCommand extends ShellCommand {
private int runInstallExisting() throws RemoteException {
final PrintWriter pw = getOutPrintWriter();
- int userId = UserHandle.USER_SYSTEM;
+ int userId = UserHandle.USER_CURRENT;
int installFlags = PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS;
String opt;
boolean waitTillComplete = false;
@@ -1320,6 +1328,10 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println("Error: package name not specified");
return 1;
}
+ userId = translateUserId(userId, true /*allowAll*/, "runInstallExisting");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
int installReason = PackageManager.INSTALL_REASON_UNKNOWN;
try {
@@ -1945,6 +1957,10 @@ class PackageManagerShellCommand extends ShellCommand {
getErrPrintWriter().println("Error: no package or component specified");
return 1;
}
+ userId = translateUserId(userId, true /*allowAll*/, "runSetEnabledSetting");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
ComponentName cn = ComponentName.unflattenFromString(pkg);
if (cn == null) {
mInterface.setApplicationEnabledSetting(pkg, state, 0, userId,
@@ -1974,6 +1990,10 @@ class PackageManagerShellCommand extends ShellCommand {
getErrPrintWriter().println("Error: no package or component specified");
return 1;
}
+ userId = translateUserId(userId, true /*allowAll*/, "runSetHiddenSetting");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
mInterface.setApplicationHiddenSettingAsUser(pkg, state, userId);
getOutPrintWriter().println("Package " + pkg + " new hidden state: "
+ mInterface.getApplicationHiddenSettingAsUser(pkg, userId));
@@ -2043,6 +2063,10 @@ class PackageManagerShellCommand extends ShellCommand {
info = null;
}
try {
+ userId = translateUserId(userId, true /*allowAll*/, "runSuspend");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
mInterface.setPackagesSuspendedAsUser(new String[]{packageName}, suspendedState,
appExtras, launcherExtras, info, callingPackage, userId);
pw.println("Package " + packageName + " new suspended state: "
@@ -2074,7 +2098,7 @@ class PackageManagerShellCommand extends ShellCommand {
getErrPrintWriter().println("Error: no permission specified");
return 1;
}
-
+ userId = translateUserId(userId, true /*allowAll*/, "runGrantRevokePermission");
if (grant) {
mPermissionManager.grantRuntimePermission(pkg, perm, userId);
} else {
@@ -2262,6 +2286,10 @@ class PackageManagerShellCommand extends ShellCommand {
return 1;
}
+ userId = translateUserId(userId, true /*allowAll*/, "runSetAppLink");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
final PackageInfo info = mInterface.getPackageInfo(pkg, 0, userId);
if (info == null) {
getErrPrintWriter().println("Error: package " + pkg + " not found.");
@@ -2302,6 +2330,10 @@ class PackageManagerShellCommand extends ShellCommand {
return 1;
}
+ userId = translateUserId(userId, true /*allowAll*/, "runGetAppLink");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
final PackageInfo info = mInterface.getPackageInfo(pkg, 0, userId);
if (info == null) {
getErrPrintWriter().println("Error: package " + pkg + " not found.");
@@ -2666,8 +2698,7 @@ class PackageManagerShellCommand extends ShellCommand {
}
pkgName = componentName.getPackageName();
}
-
-
+ userId = translateUserId(userId, true /*allowAll*/, "runInstallCreate");
final CompletableFuture<Boolean> future = new CompletableFuture<>();
final RemoteCallback callback = new RemoteCallback(res -> future.complete(res != null));
try {
@@ -2763,8 +2794,10 @@ class PackageManagerShellCommand extends ShellCommand {
}
}
- userId = translateUserId(userId, false /*allowAll*/, "runSetHarmfulAppWarning");
-
+ userId = translateUserId(userId, true /*allowAll*/, "runSetHarmfulAppWarning");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
final String packageName = getNextArgRequired();
final String warning = getNextArg();
@@ -2786,8 +2819,10 @@ class PackageManagerShellCommand extends ShellCommand {
}
}
- userId = translateUserId(userId, false /*allowAll*/, "runGetHarmfulAppWarning");
-
+ userId = translateUserId(userId, true /*allowAll*/, "runGetHarmfulAppWarning");
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
final String packageName = getNextArgRequired();
final CharSequence warning = mInterface.getHarmfulAppWarning(packageName, userId);
if (!TextUtils.isEmpty(warning)) {
@@ -2824,7 +2859,7 @@ class PackageManagerShellCommand extends ShellCommand {
private int doCreateSession(SessionParams params, String installerPackageName, int userId)
throws RemoteException {
- userId = translateUserId(userId, true /*allowAll*/, "runInstallCreate");
+ userId = translateUserId(userId, true /*allowAll*/, "doCreateSession");
if (userId == UserHandle.USER_ALL) {
userId = UserHandle.USER_SYSTEM;
params.installFlags |= PackageManager.INSTALL_ALL_USERS;
@@ -3115,13 +3150,13 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println(" dump PACKAGE");
pw.println(" Print various system state associated with the given PACKAGE.");
pw.println("");
- pw.println(" list features");
- pw.println(" Prints all features of the system.");
- pw.println("");
pw.println(" has-feature FEATURE_NAME [version]");
pw.println(" Prints true and returns exit status 0 when system has a FEATURE_NAME,");
pw.println(" otherwise prints false and returns exit status 1");
pw.println("");
+ pw.println(" list features");
+ pw.println(" Prints all features of the system.");
+ pw.println("");
pw.println(" list instrumentation [-f] [TARGET-PACKAGE]");
pw.println(" Prints all test packages; optionally only those targeting TARGET-PACKAGE");
pw.println(" Options:");
@@ -3161,11 +3196,14 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println(" -u: list only the permissions users will see");
pw.println("");
pw.println(" list staged-sessions [--only-ready] [--only-sessionid] [--only-parent]");
- pw.println(" Displays list of all staged sessions on device.");
+ pw.println(" Prints all staged sessions.");
pw.println(" --only-ready: show only staged sessions that are ready");
pw.println(" --only-sessionid: show only sessionId of each session");
pw.println(" --only-parent: hide all children sessions");
pw.println("");
+ pw.println(" list users");
+ pw.println(" Prints all users.");
+ pw.println("");
pw.println(" resolve-activity [--brief] [--components] [--query-flags FLAGS]");
pw.println(" [--user USER_ID] INTENT");
pw.println(" Prints the activity that resolves to the given INTENT.");
@@ -3186,7 +3224,7 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println(" [-p INHERIT_PACKAGE] [--install-location 0/1/2]");
pw.println(" [--install-reason 0/1/2/3/4] [--originating-uri URI]");
pw.println(" [--referrer URI] [--abi ABI_NAME] [--force-sdk]");
- pw.println(" [--preload] [--instantapp] [--full] [--dont-kill]");
+ pw.println(" [--preload] [--instant] [--full] [--dont-kill]");
pw.println(" [--enable-rollback]");
pw.println(" [--force-uuid internal|UUID] [--pkg PACKAGE] [-S BYTES]");
pw.println(" [--apex] [--wait TIMEOUT]");
@@ -3209,7 +3247,7 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println(" --referrer: set URI that instigated the install of the app");
pw.println(" --pkg: specify expected package name of app being installed");
pw.println(" --abi: override the default ABI of the platform");
- pw.println(" --instantapp: cause the app to be installed as an ephemeral install app");
+ pw.println(" --instant: cause the app to be installed as an ephemeral install app");
pw.println(" --full: cause the app to be installed as a non-ephemeral full app");
pw.println(" --install-location: force the install location:");
pw.println(" 0=auto, 1=internal only, 2=prefer external");
@@ -3222,11 +3260,20 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println(" for pre-reboot verification to complete. If TIMEOUT is not");
pw.println(" specified it will wait for " + DEFAULT_WAIT_MS + " milliseconds.");
pw.println("");
+ pw.println(" install-existing [--user USER_ID|all|current]");
+ pw.println(" [--instant] [--full] [--wait] [--restrict-permissions] PACKAGE");
+ pw.println(" Installs an existing application for a new user. Options are:");
+ pw.println(" --user: install for the given user.");
+ pw.println(" --instant: install as an instant app");
+ pw.println(" --full: install as a full app");
+ pw.println(" --wait: wait until the package is installed");
+ pw.println(" --restrict-permissions: don't whitelist restricted permissions");
+ pw.println("");
pw.println(" install-create [-lrtsfdg] [-i PACKAGE] [--user USER_ID|all|current]");
pw.println(" [-p INHERIT_PACKAGE] [--install-location 0/1/2]");
pw.println(" [--install-reason 0/1/2/3/4] [--originating-uri URI]");
pw.println(" [--referrer URI] [--abi ABI_NAME] [--force-sdk]");
- pw.println(" [--preload] [--instantapp] [--full] [--dont-kill]");
+ pw.println(" [--preload] [--instant] [--full] [--dont-kill]");
pw.println(" [--force-uuid internal|UUID] [--pkg PACKAGE] [--apex] [-S BYTES]");
pw.println(" [--multi-package] [--staged]");
pw.println(" Like \"install\", but starts an install session. Use \"install-write\"");
diff --git a/services/core/java/com/android/server/protolog/ProtoLogImpl.java b/services/core/java/com/android/server/protolog/ProtoLogImpl.java
index 239a4259438b..20bab55f39b1 100644
--- a/services/core/java/com/android/server/protolog/ProtoLogImpl.java
+++ b/services/core/java/com/android/server/protolog/ProtoLogImpl.java
@@ -110,6 +110,12 @@ public class ProtoLogImpl {
getSingleInstance().log(LogLevel.WTF, group, messageHash, paramsMask, messageString, args);
}
+ /** Returns true iff logging is enabled for the given {@code IProtoLogGroup}. */
+ public static boolean isEnabled(IProtoLogGroup group) {
+ return group.isLogToProto()
+ || (group.isLogToProto() && getSingleInstance().isProtoEnabled());
+ }
+
private static final int BUFFER_CAPACITY = 1024 * 1024;
private static final String LOG_FILENAME = "/data/misc/wmtrace/wm_log.pb";
private static final String VIEWER_CONFIG_FILENAME = "/system/etc/protolog.conf.json.gz";
@@ -222,48 +228,50 @@ public class ProtoLogImpl {
os.write(MESSAGE_HASH, messageHash);
os.write(ELAPSED_REALTIME_NANOS, SystemClock.elapsedRealtimeNanos());
- int argIndex = 0;
- ArrayList<Long> longParams = new ArrayList<>();
- ArrayList<Double> doubleParams = new ArrayList<>();
- ArrayList<Boolean> booleanParams = new ArrayList<>();
- for (Object o : args) {
- int type = LogDataType.bitmaskToLogDataType(paramsMask, argIndex);
- try {
- switch (type) {
- case LogDataType.STRING:
- os.write(STR_PARAMS, o.toString());
- break;
- case LogDataType.LONG:
- longParams.add(((Number) o).longValue());
- break;
- case LogDataType.DOUBLE:
- doubleParams.add(((Number) o).doubleValue());
- break;
- case LogDataType.BOOLEAN:
- booleanParams.add((boolean) o);
- break;
+ if (args != null) {
+ int argIndex = 0;
+ ArrayList<Long> longParams = new ArrayList<>();
+ ArrayList<Double> doubleParams = new ArrayList<>();
+ ArrayList<Boolean> booleanParams = new ArrayList<>();
+ for (Object o : args) {
+ int type = LogDataType.bitmaskToLogDataType(paramsMask, argIndex);
+ try {
+ switch (type) {
+ case LogDataType.STRING:
+ os.write(STR_PARAMS, o.toString());
+ break;
+ case LogDataType.LONG:
+ longParams.add(((Number) o).longValue());
+ break;
+ case LogDataType.DOUBLE:
+ doubleParams.add(((Number) o).doubleValue());
+ break;
+ case LogDataType.BOOLEAN:
+ booleanParams.add((boolean) o);
+ break;
+ }
+ } catch (ClassCastException ex) {
+ // Should not happen unless there is an error in the ProtoLogTool.
+ os.write(STR_PARAMS, "(INVALID PARAMS_MASK) " + o.toString());
+ Slog.e(TAG, "Invalid ProtoLog paramsMask", ex);
}
- } catch (ClassCastException ex) {
- // Should not happen unless there is an error in the ProtoLogTool.
- os.write(STR_PARAMS, "(INVALID PARAMS_MASK) " + o.toString());
- Slog.e(TAG, "Invalid ProtoLog paramsMask", ex);
+ argIndex++;
}
- argIndex++;
- }
- if (longParams.size() > 0) {
- os.writePackedSInt64(SINT64_PARAMS,
- longParams.stream().mapToLong(i -> i).toArray());
- }
- if (doubleParams.size() > 0) {
- os.writePackedDouble(DOUBLE_PARAMS,
- doubleParams.stream().mapToDouble(i -> i).toArray());
- }
- if (booleanParams.size() > 0) {
- boolean[] arr = new boolean[booleanParams.size()];
- for (int i = 0; i < booleanParams.size(); i++) {
- arr[i] = booleanParams.get(i);
+ if (longParams.size() > 0) {
+ os.writePackedSInt64(SINT64_PARAMS,
+ longParams.stream().mapToLong(i -> i).toArray());
+ }
+ if (doubleParams.size() > 0) {
+ os.writePackedDouble(DOUBLE_PARAMS,
+ doubleParams.stream().mapToDouble(i -> i).toArray());
+ }
+ if (booleanParams.size() > 0) {
+ boolean[] arr = new boolean[booleanParams.size()];
+ for (int i = 0; i < booleanParams.size(); i++) {
+ arr[i] = booleanParams.get(i);
+ }
+ os.writePackedBool(BOOLEAN_PARAMS, arr);
}
- os.writePackedBool(BOOLEAN_PARAMS, arr);
}
os.end(token);
mBuffer.add(os);
diff --git a/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java b/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java
index d49b9589cb15..2b25b8921540 100644
--- a/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java
+++ b/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java
@@ -15,6 +15,7 @@
*/
package com.android.server.stats;
+import android.annotation.Nullable;
import android.os.FileUtils;
import android.util.Slog;
@@ -22,61 +23,53 @@ import com.android.internal.annotations.VisibleForTesting;
import java.io.File;
import java.io.IOException;
-import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class ProcfsMemoryUtil {
private static final String TAG = "ProcfsMemoryUtil";
- /** Path to procfs status file: /proc/pid/status. */
- private static final String STATUS_FILE_FMT = "/proc/%d/status";
-
- private static final Pattern RSS_HIGH_WATER_MARK_IN_KILOBYTES =
- Pattern.compile("VmHWM:\\s*(\\d+)\\s*kB");
- private static final Pattern RSS_IN_KILOBYTES =
- Pattern.compile("VmRSS:\\s*(\\d+)\\s*kB");
- private static final Pattern ANON_RSS_IN_KILOBYTES =
- Pattern.compile("RssAnon:\\s*(\\d+)\\s*kB");
- private static final Pattern SWAP_IN_KILOBYTES =
- Pattern.compile("VmSwap:\\s*(\\d+)\\s*kB");
+ private static final Pattern STATUS_MEMORY_STATS =
+ Pattern.compile(String.join(
+ ".*",
+ "Uid:\\s*(\\d+)\\s*",
+ "VmHWM:\\s*(\\d+)\\s*kB",
+ "VmRSS:\\s*(\\d+)\\s*kB",
+ "RssAnon:\\s*(\\d+)\\s*kB",
+ "VmSwap:\\s*(\\d+)\\s*kB"), Pattern.DOTALL);
private ProcfsMemoryUtil() {}
/**
- * Reads RSS high-water mark of a process from procfs. Returns value of the VmHWM field in
- * /proc/PID/status in kilobytes or 0 if not available.
- */
- static int readRssHighWaterMarkFromProcfs(int pid) {
- final String statusPath = String.format(Locale.US, STATUS_FILE_FMT, pid);
- return parseVmHWMFromStatus(readFile(statusPath));
- }
-
- /**
- * Parses RSS high-water mark out from the contents of the /proc/pid/status file in procfs. The
- * returned value is in kilobytes.
- */
- @VisibleForTesting
- static int parseVmHWMFromStatus(String contents) {
- return tryParseInt(contents, RSS_HIGH_WATER_MARK_IN_KILOBYTES);
- }
-
- /**
- * Reads memory stat of a process from procfs. Returns values of the VmRss, AnonRSS, VmSwap
- * fields in /proc/pid/status in kilobytes or 0 if not available.
+ * Reads memory stats of a process from procfs. Returns values of the VmHWM, VmRss, AnonRSS,
+ * VmSwap fields in /proc/pid/status in kilobytes or null if not available.
*/
+ @Nullable
static MemorySnapshot readMemorySnapshotFromProcfs(int pid) {
- final String statusPath = String.format(Locale.US, STATUS_FILE_FMT, pid);
- return parseMemorySnapshotFromStatus(readFile(statusPath));
+ return parseMemorySnapshotFromStatus(readFile("/proc/" + pid + "/status"));
}
@VisibleForTesting
+ @Nullable
static MemorySnapshot parseMemorySnapshotFromStatus(String contents) {
- final MemorySnapshot snapshot = new MemorySnapshot();
- snapshot.rssInKilobytes = tryParseInt(contents, RSS_IN_KILOBYTES);
- snapshot.anonRssInKilobytes = tryParseInt(contents, ANON_RSS_IN_KILOBYTES);
- snapshot.swapInKilobytes = tryParseInt(contents, SWAP_IN_KILOBYTES);
- return snapshot;
+ if (contents.isEmpty()) {
+ return null;
+ }
+ try {
+ final Matcher matcher = STATUS_MEMORY_STATS.matcher(contents);
+ if (matcher.find()) {
+ final MemorySnapshot snapshot = new MemorySnapshot();
+ snapshot.uid = Integer.parseInt(matcher.group(1));
+ snapshot.rssHighWaterMarkInKilobytes = Integer.parseInt(matcher.group(2));
+ snapshot.rssInKilobytes = Integer.parseInt(matcher.group(3));
+ snapshot.anonRssInKilobytes = Integer.parseInt(matcher.group(4));
+ snapshot.swapInKilobytes = Integer.parseInt(matcher.group(5));
+ return snapshot;
+ }
+ } catch (NumberFormatException e) {
+ Slog.e(TAG, "Failed to parse value", e);
+ }
+ return null;
}
private static String readFile(String path) {
@@ -88,26 +81,11 @@ final class ProcfsMemoryUtil {
}
}
- private static int tryParseInt(String contents, Pattern pattern) {
- if (contents.isEmpty()) {
- return 0;
- }
- final Matcher matcher = pattern.matcher(contents);
- try {
- return matcher.find() ? Integer.parseInt(matcher.group(1)) : 0;
- } catch (NumberFormatException e) {
- Slog.e(TAG, "Failed to parse value", e);
- return 0;
- }
- }
-
static final class MemorySnapshot {
+ public int uid;
+ public int rssHighWaterMarkInKilobytes;
public int rssInKilobytes;
public int anonRssInKilobytes;
public int swapInKilobytes;
-
- boolean isEmpty() {
- return (anonRssInKilobytes + swapInKilobytes) == 0;
- }
}
}
diff --git a/services/core/java/com/android/server/stats/StatsCompanionService.java b/services/core/java/com/android/server/stats/StatsCompanionService.java
index e1a48ed3b550..67830a930caf 100644
--- a/services/core/java/com/android/server/stats/StatsCompanionService.java
+++ b/services/core/java/com/android/server/stats/StatsCompanionService.java
@@ -30,7 +30,6 @@ import static com.android.server.am.MemoryStatUtil.readMemoryStatFromProcfs;
import static com.android.server.stats.IonMemoryUtil.readProcessSystemIonHeapSizesFromDebugfs;
import static com.android.server.stats.IonMemoryUtil.readSystemIonHeapSizeFromDebugfs;
import static com.android.server.stats.ProcfsMemoryUtil.readMemorySnapshotFromProcfs;
-import static com.android.server.stats.ProcfsMemoryUtil.readRssHighWaterMarkFromProcfs;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -245,6 +244,13 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
"zygote",
"zygote64",
};
+ /**
+ * Lowest available uid for apps.
+ *
+ * <p>Used to quickly discard memory snapshots of the zygote forks from native process
+ * measurements.
+ */
+ private static final int MIN_APP_UID = 10_000;
private static final int CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES = 8;
@@ -1197,20 +1203,18 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
private void pullNativeProcessMemoryState(
int tagId, long elapsedNanos, long wallClockNanos,
List<StatsLogEventWrapper> pulledData) {
- final List<String> processNames = Arrays.asList(MEMORY_INTERESTING_NATIVE_PROCESSES);
int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
- for (int i = 0; i < pids.length; i++) {
- int pid = pids[i];
+ for (int pid : pids) {
+ String processName = readCmdlineFromProcfs(pid);
MemoryStat memoryStat = readMemoryStatFromProcfs(pid);
if (memoryStat == null) {
continue;
}
int uid = getUidForPid(pid);
- String processName = readCmdlineFromProcfs(pid);
- // Sometimes we get here processName that is not included in the whitelist. It comes
+ // Sometimes we get here a process that is not included in the whitelist. It comes
// from forking the zygote for an app. We can ignore that sample because this process
// is collected by ProcessMemoryState.
- if (!processNames.contains(processName)) {
+ if (isAppUid(uid)) {
continue;
}
StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
@@ -1238,34 +1242,37 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
LocalServices.getService(
ActivityManagerInternal.class).getMemoryStateForProcesses();
for (ProcessMemoryState managedProcess : managedProcessList) {
- final int rssHighWaterMarkInKilobytes =
- readRssHighWaterMarkFromProcfs(managedProcess.pid);
- if (rssHighWaterMarkInKilobytes == 0) {
+ final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
+ if (snapshot == null) {
continue;
}
StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
e.writeInt(managedProcess.uid);
e.writeString(managedProcess.processName);
// RSS high-water mark in bytes.
- e.writeLong((long) rssHighWaterMarkInKilobytes * 1024L);
- e.writeInt(rssHighWaterMarkInKilobytes);
+ e.writeLong((long) snapshot.rssHighWaterMarkInKilobytes * 1024L);
+ e.writeInt(snapshot.rssHighWaterMarkInKilobytes);
pulledData.add(e);
}
int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
- for (int i = 0; i < pids.length; i++) {
- final int pid = pids[i];
- final int uid = getUidForPid(pid);
+ for (int pid : pids) {
final String processName = readCmdlineFromProcfs(pid);
- final int rssHighWaterMarkInKilobytes = readRssHighWaterMarkFromProcfs(pid);
- if (rssHighWaterMarkInKilobytes == 0) {
+ final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(pid);
+ if (snapshot == null) {
+ continue;
+ }
+ // Sometimes we get here a process that is not included in the whitelist. It comes
+ // from forking the zygote for an app. We can ignore that sample because this process
+ // is collected by ProcessMemoryState.
+ if (isAppUid(snapshot.uid)) {
continue;
}
StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
- e.writeInt(uid);
+ e.writeInt(snapshot.uid);
e.writeString(processName);
// RSS high-water mark in bytes.
- e.writeLong((long) rssHighWaterMarkInKilobytes * 1024L);
- e.writeInt(rssHighWaterMarkInKilobytes);
+ e.writeLong((long) snapshot.rssHighWaterMarkInKilobytes * 1024L);
+ e.writeInt(snapshot.rssHighWaterMarkInKilobytes);
pulledData.add(e);
}
// Invoke rss_hwm_reset binary to reset RSS HWM counters for all processes.
@@ -1279,15 +1286,15 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
LocalServices.getService(
ActivityManagerInternal.class).getMemoryStateForProcesses();
for (ProcessMemoryState managedProcess : managedProcessList) {
+ final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
+ if (snapshot == null) {
+ continue;
+ }
StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
e.writeInt(managedProcess.uid);
e.writeString(managedProcess.processName);
e.writeInt(managedProcess.pid);
e.writeInt(managedProcess.oomScore);
- final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
- if (snapshot.isEmpty()) {
- continue;
- }
e.writeInt(snapshot.rssInKilobytes);
e.writeInt(snapshot.anonRssInKilobytes);
e.writeInt(snapshot.swapInKilobytes);
@@ -1296,15 +1303,22 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
}
int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
for (int pid : pids) {
- StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
- e.writeInt(getUidForPid(pid));
- e.writeString(readCmdlineFromProcfs(pid));
- e.writeInt(pid);
- e.writeInt(-1001); // Placeholder for native processes, OOM_SCORE_ADJ_MIN - 1.
+ final String processName = readCmdlineFromProcfs(pid);
final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(pid);
- if (snapshot.isEmpty()) {
+ if (snapshot == null) {
continue;
}
+ // Sometimes we get here a process that is not included in the whitelist. It comes
+ // from forking the zygote for an app. We can ignore that sample because this process
+ // is collected by ProcessMemoryState.
+ if (isAppUid(snapshot.uid)) {
+ continue;
+ }
+ StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+ e.writeInt(snapshot.uid);
+ e.writeString(processName);
+ e.writeInt(pid);
+ e.writeInt(-1001); // Placeholder for native processes, OOM_SCORE_ADJ_MIN - 1.
e.writeInt(snapshot.rssInKilobytes);
e.writeInt(snapshot.anonRssInKilobytes);
e.writeInt(snapshot.swapInKilobytes);
@@ -1313,6 +1327,10 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
}
}
+ private static boolean isAppUid(int uid) {
+ return uid >= MIN_APP_UID;
+ }
+
private void pullSystemIonHeapSize(
int tagId, long elapsedNanos, long wallClockNanos,
List<StatsLogEventWrapper> pulledData) {
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 63ff2ea8069c..6462744703a3 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -564,6 +564,10 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
// Last systemUiVisibility we dispatched to windows.
private int mLastDispatchedSystemUiVisibility = 0;
+ private final ArrayList<TaskStack> mTmpAlwaysOnTopStacks = new ArrayList<>();
+ private final ArrayList<TaskStack> mTmpNormalStacks = new ArrayList<>();
+ private final ArrayList<TaskStack> mTmpHomeStacks = new ArrayList<>();
+
/** Corner radius that windows should have in order to match the display. */
private final float mWindowCornerRadius;
@@ -4266,54 +4270,56 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
void assignStackOrdering(SurfaceControl.Transaction t) {
-
- final int HOME_STACK_STATE = 0;
- final int NORMAL_STACK_STATE = 1;
- final int ALWAYS_ON_TOP_STATE = 2;
+ if (getParent() == null) {
+ return;
+ }
+ mTmpAlwaysOnTopStacks.clear();
+ mTmpHomeStacks.clear();
+ mTmpNormalStacks.clear();
+ for (int i = 0; i < mChildren.size(); ++i) {
+ final TaskStack s = mChildren.get(i);
+ if (s.isAlwaysOnTop()) {
+ mTmpAlwaysOnTopStacks.add(s);
+ } else if (s.isActivityTypeHome()) {
+ mTmpHomeStacks.add(s);
+ } else {
+ mTmpNormalStacks.add(s);
+ }
+ }
int layer = 0;
- int layerForAnimationLayer = 0;
- int layerForBoostedAnimationLayer = 0;
- int layerForHomeAnimationLayer = 0;
-
- for (int state = 0; state <= ALWAYS_ON_TOP_STATE; state++) {
- for (int i = 0; i < mChildren.size(); i++) {
- final TaskStack s = mChildren.get(i);
- if (state == HOME_STACK_STATE && !s.isActivityTypeHome()) {
- continue;
- } else if (state == NORMAL_STACK_STATE && (s.isActivityTypeHome()
- || s.isAlwaysOnTop())) {
- continue;
- } else if (state == ALWAYS_ON_TOP_STATE && !s.isAlwaysOnTop()) {
- continue;
- }
- s.assignLayer(t, layer++);
- if (s.inSplitScreenWindowingMode() && mSplitScreenDividerAnchor != null) {
- t.setLayer(mSplitScreenDividerAnchor, layer++);
- }
- if ((s.isTaskAnimating() || s.isAppAnimating())
- && state != ALWAYS_ON_TOP_STATE) {
- // Ensure the animation layer ends up above the
- // highest animating stack and no higher.
- layerForAnimationLayer = layer++;
- }
- if (state != ALWAYS_ON_TOP_STATE) {
- layerForBoostedAnimationLayer = layer++;
- }
+ // Place home stacks to the bottom.
+ for (int i = 0; i < mTmpHomeStacks.size(); i++) {
+ mTmpHomeStacks.get(i).assignLayer(t, layer++);
+ }
+ // The home animation layer is between the home stacks and the normal stacks.
+ final int layerForHomeAnimationLayer = layer++;
+ int layerForSplitScreenDividerAnchor = layer++;
+ int layerForAnimationLayer = layer++;
+ for (int i = 0; i < mTmpNormalStacks.size(); i++) {
+ final TaskStack s = mTmpNormalStacks.get(i);
+ s.assignLayer(t, layer++);
+ if (s.inSplitScreenWindowingMode()) {
+ // The split screen divider anchor is located above the split screen window.
+ layerForSplitScreenDividerAnchor = layer++;
}
- if (state == HOME_STACK_STATE) {
- layerForHomeAnimationLayer = layer++;
+ if (s.isTaskAnimating() || s.isAppAnimating()) {
+ // The animation layer is located above the highest animating stack and no
+ // higher.
+ layerForAnimationLayer = layer++;
}
}
- if (mAppAnimationLayer != null) {
- t.setLayer(mAppAnimationLayer, layerForAnimationLayer);
- }
- if (mBoostedAppAnimationLayer != null) {
- t.setLayer(mBoostedAppAnimationLayer, layerForBoostedAnimationLayer);
- }
- if (mHomeAppAnimationLayer != null) {
- t.setLayer(mHomeAppAnimationLayer, layerForHomeAnimationLayer);
+ // The boosted animation layer is between the normal stacks and the always on top
+ // stacks.
+ final int layerForBoostedAnimationLayer = layer++;
+ for (int i = 0; i < mTmpAlwaysOnTopStacks.size(); i++) {
+ mTmpAlwaysOnTopStacks.get(i).assignLayer(t, layer++);
}
+
+ t.setLayer(mHomeAppAnimationLayer, layerForHomeAnimationLayer);
+ t.setLayer(mAppAnimationLayer, layerForAnimationLayer);
+ t.setLayer(mSplitScreenDividerAnchor, layerForSplitScreenDividerAnchor);
+ t.setLayer(mBoostedAppAnimationLayer, layerForBoostedAnimationLayer);
}
@Override
@@ -4335,27 +4341,28 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
@Override
void onParentChanged() {
- super.onParentChanged();
if (getParent() != null) {
- mAppAnimationLayer = makeChildSurface(null)
- .setName("animationLayer")
- .build();
- mBoostedAppAnimationLayer = makeChildSurface(null)
- .setName("boostedAnimationLayer")
- .build();
- mHomeAppAnimationLayer = makeChildSurface(null)
- .setName("homeAnimationLayer")
- .build();
- mSplitScreenDividerAnchor = makeChildSurface(null)
- .setName("splitScreenDividerAnchor")
- .build();
- getPendingTransaction()
- .show(mAppAnimationLayer)
- .show(mBoostedAppAnimationLayer)
- .show(mHomeAppAnimationLayer)
- .show(mSplitScreenDividerAnchor);
- scheduleAnimation();
+ super.onParentChanged(() -> {
+ mAppAnimationLayer = makeChildSurface(null)
+ .setName("animationLayer")
+ .build();
+ mBoostedAppAnimationLayer = makeChildSurface(null)
+ .setName("boostedAnimationLayer")
+ .build();
+ mHomeAppAnimationLayer = makeChildSurface(null)
+ .setName("homeAnimationLayer")
+ .build();
+ mSplitScreenDividerAnchor = makeChildSurface(null)
+ .setName("splitScreenDividerAnchor")
+ .build();
+ getPendingTransaction()
+ .show(mAppAnimationLayer)
+ .show(mBoostedAppAnimationLayer)
+ .show(mHomeAppAnimationLayer)
+ .show(mSplitScreenDividerAnchor);
+ });
} else {
+ super.onParentChanged();
mWmService.mTransactionFactory.get()
.remove(mAppAnimationLayer)
.remove(mBoostedAppAnimationLayer)
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 586375f9d714..ec43ec56a573 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -137,6 +137,14 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
*/
private boolean mCommittedReparentToAnimationLeash;
+ /**
+ * Callback which is triggered while changing the parent, after setting up the surface but
+ * before asking the parent to assign child layers.
+ */
+ interface PreAssignChildLayersCallback {
+ void onPreAssignChildLayers();
+ }
+
WindowContainer(WindowManagerService wms) {
mWmService = wms;
mPendingTransaction = wms.mTransactionFactory.get();
@@ -176,6 +184,10 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
*/
@Override
void onParentChanged() {
+ onParentChanged(null);
+ }
+
+ void onParentChanged(PreAssignChildLayersCallback callback) {
super.onParentChanged();
if (mParent == null) {
return;
@@ -195,6 +207,10 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
reparentSurfaceControl(getPendingTransaction(), mParent.mSurfaceControl);
}
+ if (callback != null) {
+ callback.onPreAssignChildLayers();
+ }
+
// Either way we need to ask the parent to assign us a Z-order.
mParent.assignChildLayers();
scheduleAnimation();
diff --git a/services/net/Android.bp b/services/net/Android.bp
index 8f8f9f9bbf55..1ca96ed80e5e 100644
--- a/services/net/Android.bp
+++ b/services/net/Android.bp
@@ -1,87 +1,10 @@
-// AIDL interfaces between the core system and the networking mainline module.
-aidl_interface {
- name: "ipmemorystore-aidl-interfaces",
- local_include_dir: "java",
- srcs: [
- "java/android/net/IIpMemoryStore.aidl",
- "java/android/net/IIpMemoryStoreCallbacks.aidl",
- "java/android/net/ipmemorystore/**/*.aidl",
- ],
- backend: {
- ndk: {
- enabled: false,
- },
- cpp: {
- enabled: false,
- },
- },
- api_dir: "aidl/ipmemorystore",
- versions: [
- "1",
- "2",
- "3",
- ],
-}
-
-aidl_interface {
- name: "networkstack-aidl-interfaces",
- local_include_dir: "java",
- include_dirs: ["frameworks/base/core/java"], // For framework parcelables.
- srcs: [
- "java/android/net/DhcpResultsParcelable.aidl",
- "java/android/net/INetworkMonitor.aidl",
- "java/android/net/INetworkMonitorCallbacks.aidl",
- "java/android/net/INetworkStackConnector.aidl",
- "java/android/net/INetworkStackStatusCallback.aidl",
- "java/android/net/InitialConfigurationParcelable.aidl",
- "java/android/net/NattKeepalivePacketDataParcelable.aidl",
- "java/android/net/PrivateDnsConfigParcel.aidl",
- "java/android/net/ProvisioningConfigurationParcelable.aidl",
- "java/android/net/TcpKeepalivePacketDataParcelable.aidl",
- "java/android/net/dhcp/DhcpServingParamsParcel.aidl",
- "java/android/net/dhcp/IDhcpServer.aidl",
- "java/android/net/dhcp/IDhcpServerCallbacks.aidl",
- "java/android/net/ip/IIpClient.aidl",
- "java/android/net/ip/IIpClientCallbacks.aidl",
- ],
- backend: {
- ndk: {
- enabled: false,
- },
- cpp: {
- enabled: false,
- },
- },
- api_dir: "aidl/networkstack",
- imports: ["ipmemorystore-aidl-interfaces"],
- versions: [
- "1",
- "2",
- "3",
- ],
-}
-
java_library_static {
name: "services.net",
srcs: ["java/**/*.java"],
static_libs: [
"dnsresolver_aidl_interface-V2-java",
- "ipmemorystore-client",
"netd_aidl_interface-java",
- "networkstack-aidl-interfaces-V3-java",
- ],
-}
-
-java_library_static {
- name: "ipmemorystore-client",
- sdk_version: "system_current",
- srcs: [
- ":framework-annotations",
- "java/android/net/IpMemoryStoreClient.java",
- "java/android/net/ipmemorystore/**/*.java",
- ],
- static_libs: [
- "ipmemorystore-aidl-interfaces-V3-java",
+ "networkstack-client",
],
}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl b/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index a8cbab26190f..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,9 +0,0 @@
-package android.net;
-interface IIpMemoryStore {
- oneway void storeNetworkAttributes(String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnStatusListener listener);
- oneway void storeBlob(String l2Key, String clientId, String name, in android.net.ipmemorystore.Blob data, android.net.ipmemorystore.IOnStatusListener listener);
- oneway void findL2Key(in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnL2KeyResponseListener listener);
- oneway void isSameNetwork(String l2Key1, String l2Key2, android.net.ipmemorystore.IOnSameL3NetworkResponseListener listener);
- oneway void retrieveNetworkAttributes(String l2Key, android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener listener);
- oneway void retrieveBlob(String l2Key, String clientId, String name, android.net.ipmemorystore.IOnBlobRetrievedListener listener);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index cf02c26c2fe3..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface IIpMemoryStoreCallbacks {
- oneway void onIpMemoryStoreFetched(in android.net.IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 291dbef817e6..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable Blob {
- byte[] data;
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 52f40d49abd5..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnBlobRetrievedListener {
- oneway void onBlobRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in String name, in android.net.ipmemorystore.Blob data);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index 785351435d73..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnL2KeyResponseListener {
- oneway void onL2KeyResponse(in android.net.ipmemorystore.StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index 3dd2ae6e9bab..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnNetworkAttributesRetrievedListener {
- oneway void onNetworkAttributesRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index 46d4ecb9ed7c..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnSameL3NetworkResponseListener {
- oneway void onSameL3NetworkResponse(in android.net.ipmemorystore.StatusParcelable status, in android.net.ipmemorystore.SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 54e654b80c9e..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnStatusListener {
- oneway void onComplete(in android.net.ipmemorystore.StatusParcelable status);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 9531ea3963fb..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net.ipmemorystore;
-parcelable NetworkAttributesParcelable {
- byte[] assignedV4Address;
- long assignedV4AddressExpiry;
- String groupHint;
- android.net.ipmemorystore.Blob[] dnsAddresses;
- int mtu;
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 414272b49f1d..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,6 +0,0 @@
-package android.net.ipmemorystore;
-parcelable SameL3NetworkResponseParcelable {
- String l2Key1;
- String l2Key2;
- float confidence;
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index 92c6779b5dc0..000000000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable StatusParcelable {
- int resultCode;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl b/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index a8cbab26190f..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,9 +0,0 @@
-package android.net;
-interface IIpMemoryStore {
- oneway void storeNetworkAttributes(String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnStatusListener listener);
- oneway void storeBlob(String l2Key, String clientId, String name, in android.net.ipmemorystore.Blob data, android.net.ipmemorystore.IOnStatusListener listener);
- oneway void findL2Key(in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnL2KeyResponseListener listener);
- oneway void isSameNetwork(String l2Key1, String l2Key2, android.net.ipmemorystore.IOnSameL3NetworkResponseListener listener);
- oneway void retrieveNetworkAttributes(String l2Key, android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener listener);
- oneway void retrieveBlob(String l2Key, String clientId, String name, android.net.ipmemorystore.IOnBlobRetrievedListener listener);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index cf02c26c2fe3..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface IIpMemoryStoreCallbacks {
- oneway void onIpMemoryStoreFetched(in android.net.IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 291dbef817e6..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable Blob {
- byte[] data;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 52f40d49abd5..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnBlobRetrievedListener {
- oneway void onBlobRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in String name, in android.net.ipmemorystore.Blob data);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index 785351435d73..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnL2KeyResponseListener {
- oneway void onL2KeyResponse(in android.net.ipmemorystore.StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index 3dd2ae6e9bab..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnNetworkAttributesRetrievedListener {
- oneway void onNetworkAttributesRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index 46d4ecb9ed7c..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnSameL3NetworkResponseListener {
- oneway void onSameL3NetworkResponse(in android.net.ipmemorystore.StatusParcelable status, in android.net.ipmemorystore.SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 54e654b80c9e..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnStatusListener {
- oneway void onComplete(in android.net.ipmemorystore.StatusParcelable status);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 9531ea3963fb..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net.ipmemorystore;
-parcelable NetworkAttributesParcelable {
- byte[] assignedV4Address;
- long assignedV4AddressExpiry;
- String groupHint;
- android.net.ipmemorystore.Blob[] dnsAddresses;
- int mtu;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 414272b49f1d..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,6 +0,0 @@
-package android.net.ipmemorystore;
-parcelable SameL3NetworkResponseParcelable {
- String l2Key1;
- String l2Key2;
- float confidence;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index 92c6779b5dc0..000000000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable StatusParcelable {
- int resultCode;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl b/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index 30893b215001..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface IIpMemoryStore {
- oneway void storeNetworkAttributes(String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnStatusListener listener);
- oneway void storeBlob(String l2Key, String clientId, String name, in android.net.ipmemorystore.Blob data, android.net.ipmemorystore.IOnStatusListener listener);
- oneway void findL2Key(in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnL2KeyResponseListener listener);
- oneway void isSameNetwork(String l2Key1, String l2Key2, android.net.ipmemorystore.IOnSameL3NetworkResponseListener listener);
- oneway void retrieveNetworkAttributes(String l2Key, android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener listener);
- oneway void retrieveBlob(String l2Key, String clientId, String name, android.net.ipmemorystore.IOnBlobRetrievedListener listener);
- oneway void factoryReset();
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index 535ae2cf25e4..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface IIpMemoryStoreCallbacks {
- oneway void onIpMemoryStoreFetched(in android.net.IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 6d2dc0ccaaac..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable Blob {
- byte[] data;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 48c1fb8c180a..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnBlobRetrievedListener {
- oneway void onBlobRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in String name, in android.net.ipmemorystore.Blob data);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index aebc7240bc9e..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnL2KeyResponseListener {
- oneway void onL2KeyResponse(in android.net.ipmemorystore.StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index b66db5ab21cb..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnNetworkAttributesRetrievedListener {
- oneway void onNetworkAttributesRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index e9f2db445d38..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnSameL3NetworkResponseListener {
- oneway void onSameL3NetworkResponse(in android.net.ipmemorystore.StatusParcelable status, in android.net.ipmemorystore.SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 49172cea9587..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnStatusListener {
- oneway void onComplete(in android.net.ipmemorystore.StatusParcelable status);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 188db20b531a..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable NetworkAttributesParcelable {
- byte[] assignedV4Address;
- long assignedV4AddressExpiry;
- String groupHint;
- android.net.ipmemorystore.Blob[] dnsAddresses;
- int mtu;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 7a2ed48241e7..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,23 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable SameL3NetworkResponseParcelable {
- String l2Key1;
- String l2Key2;
- float confidence;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index d9b067875e84..000000000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable StatusParcelable {
- int resultCode;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl b/services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index 92b5345ee221..000000000000
--- a/services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net;
-parcelable DhcpResultsParcelable {
- android.net.StaticIpConfiguration baseConfiguration;
- int leaseDuration;
- int mtu;
- String serverAddress;
- String vendorInfo;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl b/services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl
deleted file mode 100644
index b19f522880ec..000000000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,17 +0,0 @@
-package android.net;
-interface INetworkMonitor {
- oneway void start();
- oneway void launchCaptivePortalApp();
- oneway void notifyCaptivePortalAppFinished(int response);
- oneway void setAcceptPartialConnectivity();
- oneway void forceReevaluation(int uid);
- oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
- oneway void notifyDnsResponse(int returnCode);
- oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
- oneway void notifyNetworkDisconnected();
- oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
- oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
- const int NETWORK_TEST_RESULT_VALID = 0;
- const int NETWORK_TEST_RESULT_INVALID = 1;
- const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl b/services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index ee9871ddcd15..000000000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net;
-interface INetworkMonitorCallbacks {
- oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor);
- oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl);
- oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config);
- oneway void showProvisioningNotification(String action, String packageName);
- oneway void hideProvisioningNotification();
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl b/services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index 7da11e476c0e..000000000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-interface INetworkStackConnector {
- oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
- oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
- oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
- oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl b/services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index f6ca6f7a78e2..000000000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface INetworkStackStatusCallback {
- oneway void onStatusAvailable(int statusCode);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl b/services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index c80a78785b3b..000000000000
--- a/services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-parcelable InitialConfigurationParcelable {
- android.net.LinkAddress[] ipAddresses;
- android.net.IpPrefix[] directlyConnectedRoutes;
- String[] dnsServers;
- String gateway;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl b/services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index 2de790bb7754..000000000000
--- a/services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,5 +0,0 @@
-package android.net;
-parcelable PrivateDnsConfigParcel {
- String hostname;
- String[] ips;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index 3a6c30496fd8..000000000000
--- a/services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package android.net;
-parcelable ProvisioningConfigurationParcelable {
- boolean enableIPv4;
- boolean enableIPv6;
- boolean usingMultinetworkPolicyTracker;
- boolean usingIpReachabilityMonitor;
- int requestedPreDhcpActionMs;
- android.net.InitialConfigurationParcelable initialConfig;
- android.net.StaticIpConfiguration staticIpConfig;
- android.net.apf.ApfCapabilities apfCapabilities;
- int provisioningTimeoutMs;
- int ipv6AddrGenMode;
- android.net.Network network;
- String displayName;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index e121c064f7ac..000000000000
--- a/services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,13 +0,0 @@
-package android.net;
-parcelable TcpKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
- int seq;
- int ack;
- int rcvWnd;
- int rcvWndScale;
- int tos;
- int ttl;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 67193ae904bc..000000000000
--- a/services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,11 +0,0 @@
-package android.net.dhcp;
-parcelable DhcpServingParamsParcel {
- int serverAddr;
- int serverAddrPrefixLength;
- int[] defaultRouters;
- int[] dnsServers;
- int[] excludedAddrs;
- long dhcpLeaseTimeSecs;
- int linkMtu;
- boolean metered;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl b/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index 914315855496..000000000000
--- a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,10 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServer {
- oneway void start(in android.net.INetworkStackStatusCallback cb);
- oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb);
- oneway void stop(in android.net.INetworkStackStatusCallback cb);
- const int STATUS_UNKNOWN = 0;
- const int STATUS_SUCCESS = 1;
- const int STATUS_INVALID_ARGUMENT = 2;
- const int STATUS_UNKNOWN_ERROR = 3;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index dcc4489d52a6..000000000000
--- a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServerCallbacks {
- oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl b/services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 95a15742a684..000000000000
--- a/services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,14 +0,0 @@
-package android.net.ip;
-interface IIpClient {
- oneway void completedPreDhcpAction();
- oneway void confirmConfiguration();
- oneway void readPacketFilterComplete(in byte[] data);
- oneway void shutdown();
- oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
- oneway void stop();
- oneway void setTcpBufferSizes(in String tcpBufferSizes);
- oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
- oneway void setMulticastFilter(boolean enabled);
- oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
- oneway void removeKeepalivePacketFilter(int slot);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl b/services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index d6bc8089a0be..000000000000
--- a/services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,16 +0,0 @@
-package android.net.ip;
-interface IIpClientCallbacks {
- oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
- oneway void onPreDhcpAction();
- oneway void onPostDhcpAction();
- oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
- oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
- oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
- oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
- oneway void onReachabilityLost(in String logMsg);
- oneway void onQuit();
- oneway void installPacketFilter(in byte[] filter);
- oneway void startReadPacketFilter();
- oneway void setFallbackMulticastFilter(boolean enabled);
- oneway void setNeighborDiscoveryOffload(boolean enable);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl b/services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index 31891de7230a..000000000000
--- a/services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,9 +0,0 @@
-package android.net;
-parcelable DhcpResultsParcelable {
- android.net.StaticIpConfiguration baseConfiguration;
- int leaseDuration;
- int mtu;
- String serverAddress;
- String vendorInfo;
- String serverHostName;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl b/services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl
deleted file mode 100644
index 029968b6f324..000000000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-package android.net;
-interface INetworkMonitor {
- oneway void start();
- oneway void launchCaptivePortalApp();
- oneway void notifyCaptivePortalAppFinished(int response);
- oneway void setAcceptPartialConnectivity();
- oneway void forceReevaluation(int uid);
- oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
- oneway void notifyDnsResponse(int returnCode);
- oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
- oneway void notifyNetworkDisconnected();
- oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
- oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
- const int NETWORK_TEST_RESULT_VALID = 0;
- const int NETWORK_TEST_RESULT_INVALID = 1;
- const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
- const int NETWORK_VALIDATION_RESULT_VALID = 1;
- const int NETWORK_VALIDATION_RESULT_PARTIAL = 2;
- const int NETWORK_VALIDATION_PROBE_DNS = 4;
- const int NETWORK_VALIDATION_PROBE_HTTP = 8;
- const int NETWORK_VALIDATION_PROBE_HTTPS = 16;
- const int NETWORK_VALIDATION_PROBE_FALLBACK = 32;
- const int NETWORK_VALIDATION_PROBE_PRIVDNS = 64;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl b/services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index ee9871ddcd15..000000000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net;
-interface INetworkMonitorCallbacks {
- oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor);
- oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl);
- oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config);
- oneway void showProvisioningNotification(String action, String packageName);
- oneway void hideProvisioningNotification();
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl b/services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index 7da11e476c0e..000000000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-interface INetworkStackConnector {
- oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
- oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
- oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
- oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl b/services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index f6ca6f7a78e2..000000000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface INetworkStackStatusCallback {
- oneway void onStatusAvailable(int statusCode);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl b/services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index c80a78785b3b..000000000000
--- a/services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-parcelable InitialConfigurationParcelable {
- android.net.LinkAddress[] ipAddresses;
- android.net.IpPrefix[] directlyConnectedRoutes;
- String[] dnsServers;
- String gateway;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index 65de8833e6c5..000000000000
--- a/services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-parcelable NattKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl b/services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index 2de790bb7754..000000000000
--- a/services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,5 +0,0 @@
-package android.net;
-parcelable PrivateDnsConfigParcel {
- String hostname;
- String[] ips;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index 3a6c30496fd8..000000000000
--- a/services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package android.net;
-parcelable ProvisioningConfigurationParcelable {
- boolean enableIPv4;
- boolean enableIPv6;
- boolean usingMultinetworkPolicyTracker;
- boolean usingIpReachabilityMonitor;
- int requestedPreDhcpActionMs;
- android.net.InitialConfigurationParcelable initialConfig;
- android.net.StaticIpConfiguration staticIpConfig;
- android.net.apf.ApfCapabilities apfCapabilities;
- int provisioningTimeoutMs;
- int ipv6AddrGenMode;
- android.net.Network network;
- String displayName;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index e121c064f7ac..000000000000
--- a/services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,13 +0,0 @@
-package android.net;
-parcelable TcpKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
- int seq;
- int ack;
- int rcvWnd;
- int rcvWndScale;
- int tos;
- int ttl;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 67193ae904bc..000000000000
--- a/services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,11 +0,0 @@
-package android.net.dhcp;
-parcelable DhcpServingParamsParcel {
- int serverAddr;
- int serverAddrPrefixLength;
- int[] defaultRouters;
- int[] dnsServers;
- int[] excludedAddrs;
- long dhcpLeaseTimeSecs;
- int linkMtu;
- boolean metered;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl b/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index 914315855496..000000000000
--- a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,10 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServer {
- oneway void start(in android.net.INetworkStackStatusCallback cb);
- oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb);
- oneway void stop(in android.net.INetworkStackStatusCallback cb);
- const int STATUS_UNKNOWN = 0;
- const int STATUS_SUCCESS = 1;
- const int STATUS_INVALID_ARGUMENT = 2;
- const int STATUS_UNKNOWN_ERROR = 3;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index dcc4489d52a6..000000000000
--- a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServerCallbacks {
- oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl b/services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 77d5917de913..000000000000
--- a/services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package android.net.ip;
-interface IIpClient {
- oneway void completedPreDhcpAction();
- oneway void confirmConfiguration();
- oneway void readPacketFilterComplete(in byte[] data);
- oneway void shutdown();
- oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
- oneway void stop();
- oneway void setTcpBufferSizes(in String tcpBufferSizes);
- oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
- oneway void setMulticastFilter(boolean enabled);
- oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
- oneway void removeKeepalivePacketFilter(int slot);
- oneway void setL2KeyAndGroupHint(in String l2Key, in String groupHint);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl b/services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index d6bc8089a0be..000000000000
--- a/services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,16 +0,0 @@
-package android.net.ip;
-interface IIpClientCallbacks {
- oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
- oneway void onPreDhcpAction();
- oneway void onPostDhcpAction();
- oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
- oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
- oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
- oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
- oneway void onReachabilityLost(in String logMsg);
- oneway void onQuit();
- oneway void installPacketFilter(in byte[] filter);
- oneway void startReadPacketFilter();
- oneway void setFallbackMulticastFilter(boolean enabled);
- oneway void setNeighborDiscoveryOffload(boolean enable);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl b/services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index 07ff32111bb1..000000000000
--- a/services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,26 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable DhcpResultsParcelable {
- android.net.StaticIpConfiguration baseConfiguration;
- int leaseDuration;
- int mtu;
- String serverAddress;
- String vendorInfo;
- String serverHostName;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl b/services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl
deleted file mode 100644
index 8aa68bd1c7bf..000000000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,41 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkMonitor {
- oneway void start();
- oneway void launchCaptivePortalApp();
- oneway void notifyCaptivePortalAppFinished(int response);
- oneway void setAcceptPartialConnectivity();
- oneway void forceReevaluation(int uid);
- oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
- oneway void notifyDnsResponse(int returnCode);
- oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
- oneway void notifyNetworkDisconnected();
- oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
- oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
- const int NETWORK_TEST_RESULT_VALID = 0;
- const int NETWORK_TEST_RESULT_INVALID = 1;
- const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
- const int NETWORK_VALIDATION_RESULT_VALID = 1;
- const int NETWORK_VALIDATION_RESULT_PARTIAL = 2;
- const int NETWORK_VALIDATION_PROBE_DNS = 4;
- const int NETWORK_VALIDATION_PROBE_HTTP = 8;
- const int NETWORK_VALIDATION_PROBE_HTTPS = 16;
- const int NETWORK_VALIDATION_PROBE_FALLBACK = 32;
- const int NETWORK_VALIDATION_PROBE_PRIVDNS = 64;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl b/services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index ea93729da5e7..000000000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkMonitorCallbacks {
- oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor);
- oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl);
- oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config);
- oneway void showProvisioningNotification(String action, String packageName);
- oneway void hideProvisioningNotification();
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl b/services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index e3a83d17eb0b..000000000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkStackConnector {
- oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
- oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
- oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
- oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl b/services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index 3112a081735a..000000000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkStackStatusCallback {
- oneway void onStatusAvailable(int statusCode);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl b/services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index f846b26af808..000000000000
--- a/services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable InitialConfigurationParcelable {
- android.net.LinkAddress[] ipAddresses;
- android.net.IpPrefix[] directlyConnectedRoutes;
- String[] dnsServers;
- String gateway;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index de75940f5a50..000000000000
--- a/services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable NattKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl b/services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index cf0fbce94c91..000000000000
--- a/services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable PrivateDnsConfigParcel {
- String hostname;
- String[] ips;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index c0f2d4d1747e..000000000000
--- a/services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,32 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable ProvisioningConfigurationParcelable {
- boolean enableIPv4;
- boolean enableIPv6;
- boolean usingMultinetworkPolicyTracker;
- boolean usingIpReachabilityMonitor;
- int requestedPreDhcpActionMs;
- android.net.InitialConfigurationParcelable initialConfig;
- android.net.StaticIpConfiguration staticIpConfig;
- android.net.apf.ApfCapabilities apfCapabilities;
- int provisioningTimeoutMs;
- int ipv6AddrGenMode;
- android.net.Network network;
- String displayName;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index 5926794c2e8a..000000000000
--- a/services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable TcpKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
- int seq;
- int ack;
- int rcvWnd;
- int rcvWndScale;
- int tos;
- int ttl;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 7ab156f10553..000000000000
--- a/services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,28 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.dhcp;
-parcelable DhcpServingParamsParcel {
- int serverAddr;
- int serverAddrPrefixLength;
- int[] defaultRouters;
- int[] dnsServers;
- int[] excludedAddrs;
- long dhcpLeaseTimeSecs;
- int linkMtu;
- boolean metered;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl b/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index d281ecfee61d..000000000000
--- a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.dhcp;
-interface IDhcpServer {
- oneway void start(in android.net.INetworkStackStatusCallback cb);
- oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb);
- oneway void stop(in android.net.INetworkStackStatusCallback cb);
- const int STATUS_UNKNOWN = 0;
- const int STATUS_SUCCESS = 1;
- const int STATUS_INVALID_ARGUMENT = 2;
- const int STATUS_UNKNOWN_ERROR = 3;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index 98be0ab1d540..000000000000
--- a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.dhcp;
-interface IDhcpServerCallbacks {
- oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl b/services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 85c8676ab8d0..000000000000
--- a/services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,33 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ip;
-interface IIpClient {
- oneway void completedPreDhcpAction();
- oneway void confirmConfiguration();
- oneway void readPacketFilterComplete(in byte[] data);
- oneway void shutdown();
- oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
- oneway void stop();
- oneway void setTcpBufferSizes(in String tcpBufferSizes);
- oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
- oneway void setMulticastFilter(boolean enabled);
- oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
- oneway void removeKeepalivePacketFilter(int slot);
- oneway void setL2KeyAndGroupHint(in String l2Key, in String groupHint);
- oneway void addNattKeepalivePacketFilter(int slot, in android.net.NattKeepalivePacketDataParcelable pkt);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl b/services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index 7fe39ed1ed7a..000000000000
--- a/services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,33 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ip;
-interface IIpClientCallbacks {
- oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
- oneway void onPreDhcpAction();
- oneway void onPostDhcpAction();
- oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
- oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
- oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
- oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
- oneway void onReachabilityLost(in String logMsg);
- oneway void onQuit();
- oneway void installPacketFilter(in byte[] filter);
- oneway void startReadPacketFilter();
- oneway void setFallbackMulticastFilter(boolean enabled);
- oneway void setNeighborDiscoveryOffload(boolean enable);
-}
diff --git a/services/net/java/android/net/DhcpResultsParcelable.aidl b/services/net/java/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index c98d9c201342..000000000000
--- a/services/net/java/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Copyright (c) 2019, 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 perNmissions and
- * limitations under the License.
- */
-
-package android.net;
-
-import android.net.StaticIpConfiguration;
-
-parcelable DhcpResultsParcelable {
- StaticIpConfiguration baseConfiguration;
- int leaseDuration;
- int mtu;
- String serverAddress;
- String vendorInfo;
- String serverHostName;
-}
diff --git a/services/net/java/android/net/IIpMemoryStore.aidl b/services/net/java/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index add221ae2e01..000000000000
--- a/services/net/java/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2018 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.net;
-
-import android.net.ipmemorystore.Blob;
-import android.net.ipmemorystore.NetworkAttributesParcelable;
-import android.net.ipmemorystore.IOnBlobRetrievedListener;
-import android.net.ipmemorystore.IOnL2KeyResponseListener;
-import android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener;
-import android.net.ipmemorystore.IOnSameL3NetworkResponseListener;
-import android.net.ipmemorystore.IOnStatusListener;
-
-/** {@hide} */
-oneway interface IIpMemoryStore {
- /**
- * Store network attributes for a given L2 key.
- * If L2Key is null, choose automatically from the attributes ; passing null is equivalent to
- * calling findL2Key with the attributes and storing in the returned value.
- *
- * @param l2Key The L2 key for the L2 network. Clients that don't know or care about the L2
- * key and only care about grouping can pass a unique ID here like the ones
- * generated by {@code java.util.UUID.randomUUID()}, but keep in mind the low
- * relevance of such a network will lead to it being evicted soon if it's not
- * refreshed. Use findL2Key to try and find a similar L2Key to these attributes.
- * @param attributes The attributes for this network.
- * @param listener A listener that will be invoked to inform of the completion of this call,
- * or null if the client is not interested in learning about success/failure.
- * @return (through the listener) The L2 key. This is useful if the L2 key was not specified.
- * If the call failed, the L2 key will be null.
- */
- void storeNetworkAttributes(String l2Key, in NetworkAttributesParcelable attributes,
- IOnStatusListener listener);
-
- /**
- * Store a binary blob associated with an L2 key and a name.
- *
- * @param l2Key The L2 key for this network.
- * @param clientId The ID of the client.
- * @param name The name of this data.
- * @param data The data to store.
- * @param listener A listener to inform of the completion of this call, or null if the client
- * is not interested in learning about success/failure.
- * @return (through the listener) A status to indicate success or failure.
- */
- void storeBlob(String l2Key, String clientId, String name, in Blob data,
- IOnStatusListener listener);
-
- /**
- * Returns the best L2 key associated with the attributes.
- *
- * This will find a record that would be in the same group as the passed attributes. This is
- * useful to choose the key for storing a sample or private data when the L2 key is not known.
- * If multiple records are group-close to these attributes, the closest match is returned.
- * If multiple records have the same closeness, the one with the smaller (unicode codepoint
- * order) L2 key is returned.
- * If no record matches these attributes, null is returned.
- *
- * @param attributes The attributes of the network to find.
- * @param listener The listener that will be invoked to return the answer.
- * @return (through the listener) The L2 key if one matched, or null.
- */
- void findL2Key(in NetworkAttributesParcelable attributes, IOnL2KeyResponseListener listener);
-
- /**
- * Returns whether, to the best of the store's ability to tell, the two specified L2 keys point
- * to the same L3 network. Group-closeness is used to determine this.
- *
- * @param l2Key1 The key for the first network.
- * @param l2Key2 The key for the second network.
- * @param listener The listener that will be invoked to return the answer.
- * @return (through the listener) A SameL3NetworkResponse containing the answer and confidence.
- */
- void isSameNetwork(String l2Key1, String l2Key2, IOnSameL3NetworkResponseListener listener);
-
- /**
- * Retrieve the network attributes for a key.
- * If no record is present for this key, this will return null attributes.
- *
- * @param l2Key The key of the network to query.
- * @param listener The listener that will be invoked to return the answer.
- * @return (through the listener) The network attributes and the L2 key associated with
- * the query.
- */
- void retrieveNetworkAttributes(String l2Key, IOnNetworkAttributesRetrievedListener listener);
-
- /**
- * Retrieve previously stored private data.
- * If no data was stored for this L2 key and name this will return null.
- *
- * @param l2Key The L2 key.
- * @param clientId The id of the client that stored this data.
- * @param name The name of the data.
- * @param listener The listener that will be invoked to return the answer.
- * @return (through the listener) The private data (or null), with the L2 key
- * and the name of the data associated with the query.
- */
- void retrieveBlob(String l2Key, String clientId, String name,
- IOnBlobRetrievedListener listener);
-
- /**
- * Delete all data because a factory reset operation is in progress.
- */
- void factoryReset();
-}
diff --git a/services/net/java/android/net/INetworkMonitor.aidl b/services/net/java/android/net/INetworkMonitor.aidl
deleted file mode 100644
index 3fc81a3dadc5..000000000000
--- a/services/net/java/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Copyright (c) 2018, 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 perNmissions and
- * limitations under the License.
- */
-package android.net;
-
-import android.net.LinkProperties;
-import android.net.NetworkCapabilities;
-import android.net.PrivateDnsConfigParcel;
-
-/** @hide */
-oneway interface INetworkMonitor {
- // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
- // The network should be used as a default internet connection. It was found to be:
- // 1. a functioning network providing internet access, or
- // 2. a captive portal and the user decided to use it as is.
- const int NETWORK_TEST_RESULT_VALID = 0;
-
- // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
- // The network should not be used as a default internet connection. It was found to be:
- // 1. a captive portal and the user is prompted to sign-in, or
- // 2. a captive portal and the user did not want to use it, or
- // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
- const int NETWORK_TEST_RESULT_INVALID = 1;
-
- // After a network has been tested, this result can be sent with EVENT_NETWORK_TESTED.
- // The network may be used as a default internet connection, but it was found to be a partial
- // connectivity network which can get the pass result for http probe but get the failed result
- // for https probe.
- const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
-
- // Network validation flags indicate probe result and types. If no NETWORK_VALIDATION_RESULT_*
- // are set, then it's equal to NETWORK_TEST_RESULT_INVALID. If NETWORK_VALIDATION_RESULT_VALID
- // is set, then the network validates and equal to NETWORK_TEST_RESULT_VALID. If
- // NETWORK_VALIDATION_RESULT_PARTIAL is set, then the network has partial connectivity which
- // is equal to NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY. NETWORK_VALIDATION_PROBE_* is set
- // when the specific probe result of the network is resolved.
- const int NETWORK_VALIDATION_RESULT_VALID = 0x01;
- const int NETWORK_VALIDATION_RESULT_PARTIAL = 0x02;
- const int NETWORK_VALIDATION_PROBE_DNS = 0x04;
- const int NETWORK_VALIDATION_PROBE_HTTP = 0x08;
- const int NETWORK_VALIDATION_PROBE_HTTPS = 0x10;
- const int NETWORK_VALIDATION_PROBE_FALLBACK = 0x20;
- const int NETWORK_VALIDATION_PROBE_PRIVDNS = 0x40;
-
- void start();
- void launchCaptivePortalApp();
- void notifyCaptivePortalAppFinished(int response);
- void setAcceptPartialConnectivity();
- void forceReevaluation(int uid);
- void notifyPrivateDnsChanged(in PrivateDnsConfigParcel config);
- void notifyDnsResponse(int returnCode);
- void notifyNetworkConnected(in LinkProperties lp, in NetworkCapabilities nc);
- void notifyNetworkDisconnected();
- void notifyLinkPropertiesChanged(in LinkProperties lp);
- void notifyNetworkCapabilitiesChanged(in NetworkCapabilities nc);
-}
diff --git a/services/net/java/android/net/INetworkMonitorCallbacks.aidl b/services/net/java/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index 2c61511feb72..000000000000
--- a/services/net/java/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2018 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.net;
-
-import android.net.INetworkMonitor;
-import android.net.PrivateDnsConfigParcel;
-
-/** @hide */
-oneway interface INetworkMonitorCallbacks {
- void onNetworkMonitorCreated(in INetworkMonitor networkMonitor);
- void notifyNetworkTested(int testResult, @nullable String redirectUrl);
- void notifyPrivateDnsConfigResolved(in PrivateDnsConfigParcel config);
- void showProvisioningNotification(String action, String packageName);
- void hideProvisioningNotification();
-} \ No newline at end of file
diff --git a/services/net/java/android/net/INetworkStackConnector.aidl b/services/net/java/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index 3751c36d6ee9..000000000000
--- a/services/net/java/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Copyright (c) 2018, 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 perNmissions and
- * limitations under the License.
- */
-package android.net;
-
-import android.net.IIpMemoryStoreCallbacks;
-import android.net.INetworkMonitorCallbacks;
-import android.net.Network;
-import android.net.dhcp.DhcpServingParamsParcel;
-import android.net.dhcp.IDhcpServerCallbacks;
-import android.net.ip.IIpClientCallbacks;
-
-/** @hide */
-oneway interface INetworkStackConnector {
- void makeDhcpServer(in String ifName, in DhcpServingParamsParcel params,
- in IDhcpServerCallbacks cb);
- void makeNetworkMonitor(in Network network, String name, in INetworkMonitorCallbacks cb);
- void makeIpClient(in String ifName, in IIpClientCallbacks callbacks);
- void fetchIpMemoryStore(in IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/java/android/net/INetworkStackStatusCallback.aidl b/services/net/java/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index 51032d80a172..000000000000
--- a/services/net/java/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2018 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.net;
-
-/** @hide */
-oneway interface INetworkStackStatusCallback {
- void onStatusAvailable(int statusCode);
-} \ No newline at end of file
diff --git a/services/net/java/android/net/InitialConfigurationParcelable.aidl b/services/net/java/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index 3fa88c377a64..000000000000
--- a/services/net/java/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-import android.net.IpPrefix;
-import android.net.LinkAddress;
-
-parcelable InitialConfigurationParcelable {
- LinkAddress[] ipAddresses;
- IpPrefix[] directlyConnectedRoutes;
- String[] dnsServers;
- String gateway;
-} \ No newline at end of file
diff --git a/services/net/java/android/net/IpMemoryStoreClient.java b/services/net/java/android/net/IpMemoryStoreClient.java
deleted file mode 100644
index 014b5289bace..000000000000
--- a/services/net/java/android/net/IpMemoryStoreClient.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.net.ipmemorystore.Blob;
-import android.net.ipmemorystore.NetworkAttributes;
-import android.net.ipmemorystore.OnBlobRetrievedListener;
-import android.net.ipmemorystore.OnL2KeyResponseListener;
-import android.net.ipmemorystore.OnNetworkAttributesRetrievedListener;
-import android.net.ipmemorystore.OnSameL3NetworkResponseListener;
-import android.net.ipmemorystore.OnStatusListener;
-import android.net.ipmemorystore.Status;
-import android.os.RemoteException;
-import android.util.Log;
-
-import java.util.concurrent.ExecutionException;
-import java.util.function.Consumer;
-
-/**
- * service used to communicate with the ip memory store service in network stack,
- * which is running in a separate module.
- * @hide
- */
-public abstract class IpMemoryStoreClient {
- private static final String TAG = IpMemoryStoreClient.class.getSimpleName();
- private final Context mContext;
-
- public IpMemoryStoreClient(@NonNull final Context context) {
- if (context == null) throw new IllegalArgumentException("missing context");
- mContext = context;
- }
-
- protected abstract void runWhenServiceReady(Consumer<IIpMemoryStore> cb)
- throws ExecutionException;
-
- @FunctionalInterface
- private interface ThrowingRunnable {
- void run() throws RemoteException;
- }
-
- private void ignoringRemoteException(ThrowingRunnable r) {
- ignoringRemoteException("Failed to execute remote procedure call", r);
- }
-
- private void ignoringRemoteException(String message, ThrowingRunnable r) {
- try {
- r.run();
- } catch (RemoteException e) {
- Log.e(TAG, message, e);
- }
- }
-
- /**
- * Store network attributes for a given L2 key.
- * If L2Key is null, choose automatically from the attributes ; passing null is equivalent to
- * calling findL2Key with the attributes and storing in the returned value.
- *
- * @param l2Key The L2 key for the L2 network. Clients that don't know or care about the L2
- * key and only care about grouping can pass a unique ID here like the ones
- * generated by {@code java.util.UUID.randomUUID()}, but keep in mind the low
- * relevance of such a network will lead to it being evicted soon if it's not
- * refreshed. Use findL2Key to try and find a similar L2Key to these attributes.
- * @param attributes The attributes for this network.
- * @param listener A listener that will be invoked to inform of the completion of this call,
- * or null if the client is not interested in learning about success/failure.
- * Through the listener, returns the L2 key. This is useful if the L2 key was not specified.
- * If the call failed, the L2 key will be null.
- */
- public void storeNetworkAttributes(@NonNull final String l2Key,
- @NonNull final NetworkAttributes attributes,
- @Nullable final OnStatusListener listener) {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.storeNetworkAttributes(l2Key, attributes.toParcelable(),
- OnStatusListener.toAIDL(listener))));
- } catch (ExecutionException m) {
- ignoringRemoteException("Error storing network attributes",
- () -> listener.onComplete(new Status(Status.ERROR_UNKNOWN)));
- }
- }
-
- /**
- * Store a binary blob associated with an L2 key and a name.
- *
- * @param l2Key The L2 key for this network.
- * @param clientId The ID of the client.
- * @param name The name of this data.
- * @param data The data to store.
- * @param listener A listener to inform of the completion of this call, or null if the client
- * is not interested in learning about success/failure.
- * Through the listener, returns a status to indicate success or failure.
- */
- public void storeBlob(@NonNull final String l2Key, @NonNull final String clientId,
- @NonNull final String name, @NonNull final Blob data,
- @Nullable final OnStatusListener listener) {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.storeBlob(l2Key, clientId, name, data,
- OnStatusListener.toAIDL(listener))));
- } catch (ExecutionException m) {
- ignoringRemoteException("Error storing blob",
- () -> listener.onComplete(new Status(Status.ERROR_UNKNOWN)));
- }
- }
-
- /**
- * Returns the best L2 key associated with the attributes.
- *
- * This will find a record that would be in the same group as the passed attributes. This is
- * useful to choose the key for storing a sample or private data when the L2 key is not known.
- * If multiple records are group-close to these attributes, the closest match is returned.
- * If multiple records have the same closeness, the one with the smaller (unicode codepoint
- * order) L2 key is returned.
- * If no record matches these attributes, null is returned.
- *
- * @param attributes The attributes of the network to find.
- * @param listener The listener that will be invoked to return the answer.
- * Through the listener, returns the L2 key if one matched, or null.
- */
- public void findL2Key(@NonNull final NetworkAttributes attributes,
- @NonNull final OnL2KeyResponseListener listener) {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.findL2Key(attributes.toParcelable(),
- OnL2KeyResponseListener.toAIDL(listener))));
- } catch (ExecutionException m) {
- ignoringRemoteException("Error finding L2 Key",
- () -> listener.onL2KeyResponse(new Status(Status.ERROR_UNKNOWN), null));
- }
- }
-
- /**
- * Returns whether, to the best of the store's ability to tell, the two specified L2 keys point
- * to the same L3 network. Group-closeness is used to determine this.
- *
- * @param l2Key1 The key for the first network.
- * @param l2Key2 The key for the second network.
- * @param listener The listener that will be invoked to return the answer.
- * Through the listener, a SameL3NetworkResponse containing the answer and confidence.
- */
- public void isSameNetwork(@NonNull final String l2Key1, @NonNull final String l2Key2,
- @NonNull final OnSameL3NetworkResponseListener listener) {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.isSameNetwork(l2Key1, l2Key2,
- OnSameL3NetworkResponseListener.toAIDL(listener))));
- } catch (ExecutionException m) {
- ignoringRemoteException("Error checking for network sameness",
- () -> listener.onSameL3NetworkResponse(new Status(Status.ERROR_UNKNOWN), null));
- }
- }
-
- /**
- * Retrieve the network attributes for a key.
- * If no record is present for this key, this will return null attributes.
- *
- * @param l2Key The key of the network to query.
- * @param listener The listener that will be invoked to return the answer.
- * Through the listener, returns the network attributes and the L2 key associated with
- * the query.
- */
- public void retrieveNetworkAttributes(@NonNull final String l2Key,
- @NonNull final OnNetworkAttributesRetrievedListener listener) {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.retrieveNetworkAttributes(l2Key,
- OnNetworkAttributesRetrievedListener.toAIDL(listener))));
- } catch (ExecutionException m) {
- ignoringRemoteException("Error retrieving network attributes",
- () -> listener.onNetworkAttributesRetrieved(new Status(Status.ERROR_UNKNOWN),
- null, null));
- }
- }
-
- /**
- * Retrieve previously stored private data.
- * If no data was stored for this L2 key and name this will return null.
- *
- * @param l2Key The L2 key.
- * @param clientId The id of the client that stored this data.
- * @param name The name of the data.
- * @param listener The listener that will be invoked to return the answer.
- * Through the listener, returns the private data (or null), with the L2 key
- * and the name of the data associated with the query.
- */
- public void retrieveBlob(@NonNull final String l2Key, @NonNull final String clientId,
- @NonNull final String name, @NonNull final OnBlobRetrievedListener listener) {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.retrieveBlob(l2Key, clientId, name,
- OnBlobRetrievedListener.toAIDL(listener))));
- } catch (ExecutionException m) {
- ignoringRemoteException("Error retrieving blob",
- () -> listener.onBlobRetrieved(new Status(Status.ERROR_UNKNOWN),
- null, null, null));
- }
- }
-
- /**
- * Wipe the data in the database upon network factory reset.
- */
- public void factoryReset() {
- try {
- runWhenServiceReady(service -> ignoringRemoteException(
- () -> service.factoryReset()));
- } catch (ExecutionException m) {
- Log.e(TAG, "Error executing factory reset", m);
- }
- }
-}
diff --git a/services/net/java/android/net/PrivateDnsConfigParcel.aidl b/services/net/java/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index b52fce643302..000000000000
--- a/services/net/java/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2018 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.net;
-
-parcelable PrivateDnsConfigParcel {
- String hostname;
- String[] ips;
-}
diff --git a/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index 99606fb4b7a2..000000000000
--- a/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
-**
-** Copyright (C) 2019 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.net;
-
-import android.net.InitialConfigurationParcelable;
-import android.net.Network;
-import android.net.StaticIpConfiguration;
-import android.net.apf.ApfCapabilities;
-
-parcelable ProvisioningConfigurationParcelable {
- boolean enableIPv4;
- boolean enableIPv6;
- boolean usingMultinetworkPolicyTracker;
- boolean usingIpReachabilityMonitor;
- int requestedPreDhcpActionMs;
- InitialConfigurationParcelable initialConfig;
- StaticIpConfiguration staticIpConfig;
- ApfCapabilities apfCapabilities;
- int provisioningTimeoutMs;
- int ipv6AddrGenMode;
- Network network;
- String displayName;
-}
diff --git a/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index e25168d588e7..000000000000
--- a/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-parcelable TcpKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
- int seq;
- int ack;
- int rcvWnd;
- int rcvWndScale;
- int tos;
- int ttl;
-}
diff --git a/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 7b8b9ee324bc..000000000000
--- a/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- *
- * Copyright (C) 2018 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.net.dhcp;
-
-parcelable DhcpServingParamsParcel {
- int serverAddr;
- int serverAddrPrefixLength;
- int[] defaultRouters;
- int[] dnsServers;
- int[] excludedAddrs;
- long dhcpLeaseTimeSecs;
- int linkMtu;
- boolean metered;
-}
-
diff --git a/services/net/java/android/net/dhcp/IDhcpServer.aidl b/services/net/java/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index 559433b13962..000000000000
--- a/services/net/java/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Copyright (c) 2018, 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 perNmissions and
- * limitations under the License.
- */
-
-package android.net.dhcp;
-
-import android.net.INetworkStackStatusCallback;
-import android.net.dhcp.DhcpServingParamsParcel;
-
-/** @hide */
-oneway interface IDhcpServer {
- const int STATUS_UNKNOWN = 0;
- const int STATUS_SUCCESS = 1;
- const int STATUS_INVALID_ARGUMENT = 2;
- const int STATUS_UNKNOWN_ERROR = 3;
-
- void start(in INetworkStackStatusCallback cb);
- void updateParams(in DhcpServingParamsParcel params, in INetworkStackStatusCallback cb);
- void stop(in INetworkStackStatusCallback cb);
-}
diff --git a/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index 7ab4dcdbe584..000000000000
--- a/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Copyright (c) 2018, 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 perNmissions and
- * limitations under the License.
- */
-
-package android.net.dhcp;
-
-import android.net.dhcp.IDhcpServer;
-
-/** @hide */
-oneway interface IDhcpServerCallbacks {
- void onDhcpServerCreated(int statusCode, in IDhcpServer server);
-}
diff --git a/services/net/java/android/net/ip/IIpClient.aidl b/services/net/java/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 9989c52fc403..000000000000
--- a/services/net/java/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Copyright (c) 2019, 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 perNmissions and
- * limitations under the License.
- */
-package android.net.ip;
-
-import android.net.ProxyInfo;
-import android.net.ProvisioningConfigurationParcelable;
-import android.net.NattKeepalivePacketDataParcelable;
-import android.net.TcpKeepalivePacketDataParcelable;
-
-/** @hide */
-oneway interface IIpClient {
- void completedPreDhcpAction();
- void confirmConfiguration();
- void readPacketFilterComplete(in byte[] data);
- void shutdown();
- void startProvisioning(in ProvisioningConfigurationParcelable req);
- void stop();
- void setTcpBufferSizes(in String tcpBufferSizes);
- void setHttpProxy(in ProxyInfo proxyInfo);
- void setMulticastFilter(boolean enabled);
- void addKeepalivePacketFilter(int slot, in TcpKeepalivePacketDataParcelable pkt);
- void removeKeepalivePacketFilter(int slot);
- void setL2KeyAndGroupHint(in String l2Key, in String groupHint);
- void addNattKeepalivePacketFilter(int slot, in NattKeepalivePacketDataParcelable pkt);
-}
diff --git a/services/net/java/android/net/ip/IIpClientCallbacks.aidl b/services/net/java/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index 3681416611a9..000000000000
--- a/services/net/java/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Copyright (c) 2019, 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 perNmissions and
- * limitations under the License.
- */
-package android.net.ip;
-
-import android.net.LinkProperties;
-import android.net.ip.IIpClient;
-import android.net.DhcpResultsParcelable;
-
-/** @hide */
-oneway interface IIpClientCallbacks {
- void onIpClientCreated(in IIpClient ipClient);
-
- void onPreDhcpAction();
- void onPostDhcpAction();
-
- // This is purely advisory and not an indication of provisioning
- // success or failure. This is only here for callers that want to
- // expose DHCPv4 results to other APIs (e.g., WifiInfo#setInetAddress).
- // DHCPv4 or static IPv4 configuration failure or success can be
- // determined by whether or not the passed-in DhcpResults object is
- // null or not.
- void onNewDhcpResults(in DhcpResultsParcelable dhcpResults);
-
- void onProvisioningSuccess(in LinkProperties newLp);
- void onProvisioningFailure(in LinkProperties newLp);
-
- // Invoked on LinkProperties changes.
- void onLinkPropertiesChange(in LinkProperties newLp);
-
- // Called when the internal IpReachabilityMonitor (if enabled) has
- // detected the loss of a critical number of required neighbors.
- void onReachabilityLost(in String logMsg);
-
- // Called when the IpClient state machine terminates.
- void onQuit();
-
- // Install an APF program to filter incoming packets.
- void installPacketFilter(in byte[] filter);
-
- // Asynchronously read back the APF program & data buffer from the wifi driver.
- // Due to Wifi HAL limitations, the current implementation only supports dumping the entire
- // buffer. In response to this request, the driver returns the data buffer asynchronously
- // by sending an IpClient#EVENT_READ_PACKET_FILTER_COMPLETE message.
- void startReadPacketFilter();
-
- // If multicast filtering cannot be accomplished with APF, this function will be called to
- // actuate multicast filtering using another means.
- void setFallbackMulticastFilter(boolean enabled);
-
- // Enabled/disable Neighbor Discover offload functionality. This is
- // called, for example, whenever 464xlat is being started or stopped.
- void setNeighborDiscoveryOffload(boolean enable);
-} \ No newline at end of file
diff --git a/services/net/java/android/net/ipmemorystore/Blob.aidl b/services/net/java/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 9dbef117f8a4..000000000000
--- a/services/net/java/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-/**
- * A blob of data opaque to the memory store. The client mutates this at its own risk,
- * and it is strongly suggested to never do it at all and treat this as immutable.
- * {@hide}
- */
-parcelable Blob {
- byte[] data;
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 4926feb06e55..000000000000
--- a/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.net.ipmemorystore.Blob;
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnBlobRetrievedListener {
- /**
- * Private data was retrieved for the L2 key and name specified.
- * Note this does not return the client ID, as clients are expected to only ever use one ID.
- */
- void onBlobRetrieved(in StatusParcelable status, in String l2Key, in String name,
- in Blob data);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index dea0cc4e2586..000000000000
--- a/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnL2KeyResponseListener {
- /**
- * The operation completed with the specified L2 key.
- */
- void onL2KeyResponse(in StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index 870e217eb5b7..000000000000
--- a/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.net.ipmemorystore.NetworkAttributesParcelable;
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnNetworkAttributesRetrievedListener {
- /**
- * Network attributes were fetched for the specified L2 key. While the L2 key will never
- * be null, the attributes may be if no data is stored about this L2 key.
- */
- void onNetworkAttributesRetrieved(in StatusParcelable status, in String l2Key,
- in NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index b8ccfb99fddd..000000000000
--- a/services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.net.ipmemorystore.SameL3NetworkResponseParcelable;
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnSameL3NetworkResponseListener {
- /**
- * The memory store has come up with the answer to a query that was sent.
- */
- void onSameL3NetworkResponse(in StatusParcelable status,
- in SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 5d0750449ec5..000000000000
--- a/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnStatusListener {
- /**
- * The operation has completed with the specified status.
- */
- void onComplete(in StatusParcelable status);
-}
diff --git a/services/net/java/android/net/ipmemorystore/NetworkAttributes.java b/services/net/java/android/net/ipmemorystore/NetworkAttributes.java
deleted file mode 100644
index 818515ac9af1..000000000000
--- a/services/net/java/android/net/ipmemorystore/NetworkAttributes.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.StringJoiner;
-
-/**
- * A POD object to represent attributes of a single L2 network entry.
- * @hide
- */
-public class NetworkAttributes {
- private static final boolean DBG = true;
-
- // Weight cutoff for grouping. To group, a similarity score is computed with the following
- // algorithm : if both fields are non-null and equals() then add their assigned weight, else if
- // both are null then add a portion of their assigned weight (see NULL_MATCH_WEIGHT),
- // otherwise add nothing.
- // As a guideline, this should be something like 60~75% of the total weights in this class. The
- // design states "in essence a reader should imagine that if two important columns don't match,
- // or one important and several unimportant columns don't match then the two records are
- // considered a different group".
- private static final float TOTAL_WEIGHT_CUTOFF = 520.0f;
- // The portion of the weight that is earned when scoring group-sameness by having both columns
- // being null. This is because some networks rightfully don't have some attributes (e.g. a
- // V6-only network won't have an assigned V4 address) and both being null should count for
- // something, but attributes may also be null just because data is unavailable.
- private static final float NULL_MATCH_WEIGHT = 0.25f;
-
- // The v4 address that was assigned to this device the last time it joined this network.
- // This typically comes from DHCP but could be something else like static configuration.
- // This does not apply to IPv6.
- // TODO : add a list of v6 prefixes for the v6 case.
- @Nullable
- public final Inet4Address assignedV4Address;
- private static final float WEIGHT_ASSIGNEDV4ADDR = 300.0f;
-
- // The lease expiry timestamp of v4 address allocated from DHCP server, in milliseconds.
- @Nullable
- public final Long assignedV4AddressExpiry;
- // lease expiry doesn't imply any correlation between "the same lease expiry value" and "the
- // same L3 network".
- private static final float WEIGHT_ASSIGNEDV4ADDREXPIRY = 0.0f;
-
- // Optionally supplied by the client if it has an opinion on L3 network. For example, this
- // could be a hash of the SSID + security type on WiFi.
- @Nullable
- public final String groupHint;
- private static final float WEIGHT_GROUPHINT = 300.0f;
-
- // The list of DNS server addresses.
- @Nullable
- public final List<InetAddress> dnsAddresses;
- private static final float WEIGHT_DNSADDRESSES = 200.0f;
-
- // The mtu on this network.
- @Nullable
- public final Integer mtu;
- private static final float WEIGHT_MTU = 50.0f;
-
- // The sum of all weights in this class. Tests ensure that this stays equal to the total of
- // all weights.
- /** @hide */
- @VisibleForTesting
- public static final float TOTAL_WEIGHT = WEIGHT_ASSIGNEDV4ADDR
- + WEIGHT_ASSIGNEDV4ADDREXPIRY
- + WEIGHT_GROUPHINT
- + WEIGHT_DNSADDRESSES
- + WEIGHT_MTU;
-
- /** @hide */
- @VisibleForTesting
- public NetworkAttributes(
- @Nullable final Inet4Address assignedV4Address,
- @Nullable final Long assignedV4AddressExpiry,
- @Nullable final String groupHint,
- @Nullable final List<InetAddress> dnsAddresses,
- @Nullable final Integer mtu) {
- if (mtu != null && mtu < 0) throw new IllegalArgumentException("MTU can't be negative");
- if (assignedV4AddressExpiry != null && assignedV4AddressExpiry <= 0) {
- throw new IllegalArgumentException("lease expiry can't be negative or zero");
- }
- this.assignedV4Address = assignedV4Address;
- this.assignedV4AddressExpiry = assignedV4AddressExpiry;
- this.groupHint = groupHint;
- this.dnsAddresses = null == dnsAddresses ? null :
- Collections.unmodifiableList(new ArrayList<>(dnsAddresses));
- this.mtu = mtu;
- }
-
- @VisibleForTesting
- public NetworkAttributes(@NonNull final NetworkAttributesParcelable parcelable) {
- // The call to the other constructor must be the first statement of this constructor,
- // so everything has to be inline
- this((Inet4Address) getByAddressOrNull(parcelable.assignedV4Address),
- parcelable.assignedV4AddressExpiry > 0
- ? parcelable.assignedV4AddressExpiry : null,
- parcelable.groupHint,
- blobArrayToInetAddressList(parcelable.dnsAddresses),
- parcelable.mtu >= 0 ? parcelable.mtu : null);
- }
-
- @Nullable
- private static InetAddress getByAddressOrNull(@Nullable final byte[] address) {
- if (null == address) return null;
- try {
- return InetAddress.getByAddress(address);
- } catch (UnknownHostException e) {
- return null;
- }
- }
-
- @Nullable
- private static List<InetAddress> blobArrayToInetAddressList(@Nullable final Blob[] blobs) {
- if (null == blobs) return null;
- final ArrayList<InetAddress> list = new ArrayList<>(blobs.length);
- for (final Blob b : blobs) {
- final InetAddress addr = getByAddressOrNull(b.data);
- if (null != addr) list.add(addr);
- }
- return list;
- }
-
- @Nullable
- private static Blob[] inetAddressListToBlobArray(@Nullable final List<InetAddress> addresses) {
- if (null == addresses) return null;
- final ArrayList<Blob> blobs = new ArrayList<>();
- for (int i = 0; i < addresses.size(); ++i) {
- final InetAddress addr = addresses.get(i);
- if (null == addr) continue;
- final Blob b = new Blob();
- b.data = addr.getAddress();
- blobs.add(b);
- }
- return blobs.toArray(new Blob[0]);
- }
-
- /** Converts this NetworkAttributes to a parcelable object */
- @NonNull
- public NetworkAttributesParcelable toParcelable() {
- final NetworkAttributesParcelable parcelable = new NetworkAttributesParcelable();
- parcelable.assignedV4Address =
- (null == assignedV4Address) ? null : assignedV4Address.getAddress();
- parcelable.assignedV4AddressExpiry =
- (null == assignedV4AddressExpiry) ? 0 : assignedV4AddressExpiry;
- parcelable.groupHint = groupHint;
- parcelable.dnsAddresses = inetAddressListToBlobArray(dnsAddresses);
- parcelable.mtu = (null == mtu) ? -1 : mtu;
- return parcelable;
- }
-
- private float samenessContribution(final float weight,
- @Nullable final Object o1, @Nullable final Object o2) {
- if (null == o1) {
- return (null == o2) ? weight * NULL_MATCH_WEIGHT : 0f;
- }
- return Objects.equals(o1, o2) ? weight : 0f;
- }
-
- /** @hide */
- public float getNetworkGroupSamenessConfidence(@NonNull final NetworkAttributes o) {
- final float samenessScore =
- samenessContribution(WEIGHT_ASSIGNEDV4ADDR, assignedV4Address, o.assignedV4Address)
- + samenessContribution(WEIGHT_ASSIGNEDV4ADDREXPIRY, assignedV4AddressExpiry,
- o.assignedV4AddressExpiry)
- + samenessContribution(WEIGHT_GROUPHINT, groupHint, o.groupHint)
- + samenessContribution(WEIGHT_DNSADDRESSES, dnsAddresses, o.dnsAddresses)
- + samenessContribution(WEIGHT_MTU, mtu, o.mtu);
- // The minimum is 0, the max is TOTAL_WEIGHT and should be represented by 1.0, and
- // TOTAL_WEIGHT_CUTOFF should represent 0.5, but there is no requirement that
- // TOTAL_WEIGHT_CUTOFF would be half of TOTAL_WEIGHT (indeed, it should not be).
- // So scale scores under the cutoff between 0 and 0.5, and the scores over the cutoff
- // between 0.5 and 1.0.
- if (samenessScore < TOTAL_WEIGHT_CUTOFF) {
- return samenessScore / (TOTAL_WEIGHT_CUTOFF * 2);
- } else {
- return (samenessScore - TOTAL_WEIGHT_CUTOFF) / (TOTAL_WEIGHT - TOTAL_WEIGHT_CUTOFF) / 2
- + 0.5f;
- }
- }
-
- /** @hide */
- public static class Builder {
- @Nullable
- private Inet4Address mAssignedAddress;
- @Nullable
- private Long mAssignedAddressExpiry;
- @Nullable
- private String mGroupHint;
- @Nullable
- private List<InetAddress> mDnsAddresses;
- @Nullable
- private Integer mMtu;
-
- /**
- * Set the assigned address.
- * @param assignedV4Address The assigned address.
- * @return This builder.
- */
- public Builder setAssignedV4Address(@Nullable final Inet4Address assignedV4Address) {
- mAssignedAddress = assignedV4Address;
- return this;
- }
-
- /**
- * Set the lease expiry timestamp of assigned v4 address. Long.MAX_VALUE is used
- * to represent "infinite lease".
- *
- * @param assignedV4AddressExpiry The lease expiry timestamp of assigned v4 address.
- * @return This builder.
- */
- public Builder setAssignedV4AddressExpiry(
- @Nullable final Long assignedV4AddressExpiry) {
- if (null != assignedV4AddressExpiry && assignedV4AddressExpiry <= 0) {
- throw new IllegalArgumentException("lease expiry can't be negative or zero");
- }
- mAssignedAddressExpiry = assignedV4AddressExpiry;
- return this;
- }
-
- /**
- * Set the group hint.
- * @param groupHint The group hint.
- * @return This builder.
- */
- public Builder setGroupHint(@Nullable final String groupHint) {
- mGroupHint = groupHint;
- return this;
- }
-
- /**
- * Set the DNS addresses.
- * @param dnsAddresses The DNS addresses.
- * @return This builder.
- */
- public Builder setDnsAddresses(@Nullable final List<InetAddress> dnsAddresses) {
- if (DBG && null != dnsAddresses) {
- // Parceling code crashes if one of the addresses is null, therefore validate
- // them when running in debug.
- for (final InetAddress address : dnsAddresses) {
- if (null == address) throw new IllegalArgumentException("Null DNS address");
- }
- }
- this.mDnsAddresses = dnsAddresses;
- return this;
- }
-
- /**
- * Set the MTU.
- * @param mtu The MTU.
- * @return This builder.
- */
- public Builder setMtu(@Nullable final Integer mtu) {
- if (null != mtu && mtu < 0) throw new IllegalArgumentException("MTU can't be negative");
- mMtu = mtu;
- return this;
- }
-
- /**
- * Return the built NetworkAttributes object.
- * @return The built NetworkAttributes object.
- */
- public NetworkAttributes build() {
- return new NetworkAttributes(mAssignedAddress, mAssignedAddressExpiry,
- mGroupHint, mDnsAddresses, mMtu);
- }
- }
-
- /** @hide */
- public boolean isEmpty() {
- return (null == assignedV4Address) && (null == assignedV4AddressExpiry)
- && (null == groupHint) && (null == dnsAddresses) && (null == mtu);
- }
-
- @Override
- public boolean equals(@Nullable final Object o) {
- if (!(o instanceof NetworkAttributes)) return false;
- final NetworkAttributes other = (NetworkAttributes) o;
- return Objects.equals(assignedV4Address, other.assignedV4Address)
- && Objects.equals(assignedV4AddressExpiry, other.assignedV4AddressExpiry)
- && Objects.equals(groupHint, other.groupHint)
- && Objects.equals(dnsAddresses, other.dnsAddresses)
- && Objects.equals(mtu, other.mtu);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(assignedV4Address, assignedV4AddressExpiry,
- groupHint, dnsAddresses, mtu);
- }
-
- /** Pretty print */
- @Override
- public String toString() {
- final StringJoiner resultJoiner = new StringJoiner(" ", "{", "}");
- final ArrayList<String> nullFields = new ArrayList<>();
-
- if (null != assignedV4Address) {
- resultJoiner.add("assignedV4Addr :");
- resultJoiner.add(assignedV4Address.toString());
- } else {
- nullFields.add("assignedV4Addr");
- }
-
- if (null != assignedV4AddressExpiry) {
- resultJoiner.add("assignedV4AddressExpiry :");
- resultJoiner.add(assignedV4AddressExpiry.toString());
- } else {
- nullFields.add("assignedV4AddressExpiry");
- }
-
- if (null != groupHint) {
- resultJoiner.add("groupHint :");
- resultJoiner.add(groupHint);
- } else {
- nullFields.add("groupHint");
- }
-
- if (null != dnsAddresses) {
- resultJoiner.add("dnsAddr : [");
- for (final InetAddress addr : dnsAddresses) {
- resultJoiner.add(addr.getHostAddress());
- }
- resultJoiner.add("]");
- } else {
- nullFields.add("dnsAddr");
- }
-
- if (null != mtu) {
- resultJoiner.add("mtu :");
- resultJoiner.add(mtu.toString());
- } else {
- nullFields.add("mtu");
- }
-
- if (!nullFields.isEmpty()) {
- resultJoiner.add("; Null fields : [");
- for (final String field : nullFields) {
- resultJoiner.add(field);
- }
- resultJoiner.add("]");
- }
-
- return resultJoiner.toString();
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 997eb2b5128b..000000000000
--- a/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-// Blob[] is used to represent an array of byte[], as structured AIDL does not support arrays
-// of arrays.
-import android.net.ipmemorystore.Blob;
-
-/**
- * An object to represent attributes of a single L2 network entry.
- * See NetworkAttributes.java for a description of each field. The types used in this class
- * are structured parcelable types instead of the richer types of the NetworkAttributes object,
- * but they have the same purpose. The NetworkAttributes.java file also contains the code
- * to convert the richer types to the parcelable types and back.
- * @hide
- */
-parcelable NetworkAttributesParcelable {
- byte[] assignedV4Address;
- long assignedV4AddressExpiry;
- String groupHint;
- Blob[] dnsAddresses;
- int mtu;
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java b/services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java
deleted file mode 100644
index a17483a84e78..000000000000
--- a/services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return a blob.
- * @hide
- */
-public interface OnBlobRetrievedListener {
- /**
- * The memory store has come up with the answer to a query that was sent.
- */
- void onBlobRetrieved(Status status, String l2Key, String name, Blob blob);
-
- /** Converts this OnBlobRetrievedListener to a parcelable object */
- @NonNull
- static IOnBlobRetrievedListener toAIDL(@NonNull final OnBlobRetrievedListener listener) {
- return new IOnBlobRetrievedListener.Stub() {
- @Override
- public void onBlobRetrieved(final StatusParcelable statusParcelable, final String l2Key,
- final String name, final Blob blob) {
- // NonNull, but still don't crash the system server if null
- if (null != listener) {
- listener.onBlobRetrieved(new Status(statusParcelable), l2Key, name, blob);
- }
- }
-
- @Override
- public int getInterfaceVersion() {
- return this.VERSION;
- }
- };
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java b/services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java
deleted file mode 100644
index e608aecbf498..000000000000
--- a/services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return a L2 key.
- * @hide
- */
-public interface OnL2KeyResponseListener {
- /**
- * The operation has completed with the specified status.
- */
- void onL2KeyResponse(Status status, String l2Key);
-
- /** Converts this OnL2KeyResponseListener to a parcelable object */
- @NonNull
- static IOnL2KeyResponseListener toAIDL(@NonNull final OnL2KeyResponseListener listener) {
- return new IOnL2KeyResponseListener.Stub() {
- @Override
- public void onL2KeyResponse(final StatusParcelable statusParcelable,
- final String l2Key) {
- // NonNull, but still don't crash the system server if null
- if (null != listener) {
- listener.onL2KeyResponse(new Status(statusParcelable), l2Key);
- }
- }
-
- @Override
- public int getInterfaceVersion() {
- return this.VERSION;
- }
- };
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java b/services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java
deleted file mode 100644
index 395ad98f38e0..000000000000
--- a/services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return network attributes.
- * @hide
- */
-public interface OnNetworkAttributesRetrievedListener {
- /**
- * The memory store has come up with the answer to a query that was sent.
- */
- void onNetworkAttributesRetrieved(Status status, String l2Key, NetworkAttributes attributes);
-
- /** Converts this OnNetworkAttributesRetrievedListener to a parcelable object */
- @NonNull
- static IOnNetworkAttributesRetrievedListener toAIDL(
- @NonNull final OnNetworkAttributesRetrievedListener listener) {
- return new IOnNetworkAttributesRetrievedListener.Stub() {
- @Override
- public void onNetworkAttributesRetrieved(final StatusParcelable statusParcelable,
- final String l2Key,
- final NetworkAttributesParcelable networkAttributesParcelable) {
- // NonNull, but still don't crash the system server if null
- if (null != listener) {
- listener.onNetworkAttributesRetrieved(
- new Status(statusParcelable), l2Key, null == networkAttributesParcelable
- ? null : new NetworkAttributes(networkAttributesParcelable));
- }
- }
-
- @Override
- public int getInterfaceVersion() {
- return this.VERSION;
- }
- };
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java b/services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java
deleted file mode 100644
index 67f8da81c3f2..000000000000
--- a/services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return a response about network sameness.
- * @hide
- */
-public interface OnSameL3NetworkResponseListener {
- /**
- * The memory store has come up with the answer to a query that was sent.
- */
- void onSameL3NetworkResponse(Status status, SameL3NetworkResponse response);
-
- /** Converts this OnSameL3NetworkResponseListener to a parcelable object */
- @NonNull
- static IOnSameL3NetworkResponseListener toAIDL(
- @NonNull final OnSameL3NetworkResponseListener listener) {
- return new IOnSameL3NetworkResponseListener.Stub() {
- @Override
- public void onSameL3NetworkResponse(final StatusParcelable statusParcelable,
- final SameL3NetworkResponseParcelable sameL3NetworkResponseParcelable) {
- // NonNull, but still don't crash the system server if null
- if (null != listener) {
- listener.onSameL3NetworkResponse(
- new Status(statusParcelable),
- new SameL3NetworkResponse(sameL3NetworkResponseParcelable));
- }
- }
-
- @Override
- public int getInterfaceVersion() {
- return this.VERSION;
- }
- };
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnStatusListener.java b/services/net/java/android/net/ipmemorystore/OnStatusListener.java
deleted file mode 100644
index 4262efde8843..000000000000
--- a/services/net/java/android/net/ipmemorystore/OnStatusListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-
-/**
- * A listener for the IpMemoryStore to return a status to a client.
- * @hide
- */
-public interface OnStatusListener {
- /**
- * The operation has completed with the specified status.
- */
- void onComplete(Status status);
-
- /** Converts this OnStatusListener to a parcelable object */
- @NonNull
- static IOnStatusListener toAIDL(@Nullable final OnStatusListener listener) {
- return new IOnStatusListener.Stub() {
- @Override
- public void onComplete(final StatusParcelable statusParcelable) {
- if (null != listener) {
- listener.onComplete(new Status(statusParcelable));
- }
- }
-
- @Override
- public int getInterfaceVersion() {
- return this.VERSION;
- }
- };
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java b/services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java
deleted file mode 100644
index 291aca8fc611..000000000000
--- a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-
-/**
- * An object representing the answer to a query whether two given L2 networks represent the
- * same L3 network. Parcels as a SameL3NetworkResponseParceled object.
- * @hide
- */
-public class SameL3NetworkResponse {
- @IntDef(prefix = "NETWORK_",
- value = {NETWORK_SAME, NETWORK_DIFFERENT, NETWORK_NEVER_CONNECTED})
- @Retention(RetentionPolicy.SOURCE)
- public @interface NetworkSameness {}
-
- /**
- * Both L2 networks represent the same L3 network.
- */
- public static final int NETWORK_SAME = 1;
-
- /**
- * The two L2 networks represent a different L3 network.
- */
- public static final int NETWORK_DIFFERENT = 2;
-
- /**
- * The device has never connected to at least one of these two L2 networks, or data
- * has been wiped. Therefore the device has never seen the L3 network behind at least
- * one of these two L2 networks, and can't evaluate whether it's the same as the other.
- */
- public static final int NETWORK_NEVER_CONNECTED = 3;
-
- /**
- * The first L2 key specified in the query.
- */
- @NonNull
- public final String l2Key1;
-
- /**
- * The second L2 key specified in the query.
- */
- @NonNull
- public final String l2Key2;
-
- /**
- * A confidence value indicating whether the two L2 networks represent the same L3 network.
- *
- * If both L2 networks were known, this value will be between 0.0 and 1.0, with 0.0
- * representing complete confidence that the given L2 networks represent a different
- * L3 network, and 1.0 representing complete confidence that the given L2 networks
- * represent the same L3 network.
- * If at least one of the L2 networks was not known, this value will be outside of the
- * 0.0~1.0 range.
- *
- * Most apps should not be interested in this, and are encouraged to use the collapsing
- * {@link #getNetworkSameness()} function below.
- */
- public final float confidence;
-
- /**
- * @return whether the two L2 networks represent the same L3 network. Either
- * {@code NETWORK_SAME}, {@code NETWORK_DIFFERENT} or {@code NETWORK_NEVER_CONNECTED}.
- */
- @NetworkSameness
- public final int getNetworkSameness() {
- if (confidence > 1.0 || confidence < 0.0) return NETWORK_NEVER_CONNECTED;
- return confidence > 0.5 ? NETWORK_SAME : NETWORK_DIFFERENT;
- }
-
- /** @hide */
- public SameL3NetworkResponse(@NonNull final String l2Key1, @NonNull final String l2Key2,
- final float confidence) {
- this.l2Key1 = l2Key1;
- this.l2Key2 = l2Key2;
- this.confidence = confidence;
- }
-
- /** Builds a SameL3NetworkResponse from a parcelable object */
- @VisibleForTesting
- public SameL3NetworkResponse(@NonNull final SameL3NetworkResponseParcelable parceled) {
- this(parceled.l2Key1, parceled.l2Key2, parceled.confidence);
- }
-
- /** Converts this SameL3NetworkResponse to a parcelable object */
- @NonNull
- public SameL3NetworkResponseParcelable toParcelable() {
- final SameL3NetworkResponseParcelable parcelable = new SameL3NetworkResponseParcelable();
- parcelable.l2Key1 = l2Key1;
- parcelable.l2Key2 = l2Key2;
- parcelable.confidence = confidence;
- return parcelable;
- }
-
- // Note key1 and key2 have to match each other for this to return true. If
- // key1 matches o.key2 and the other way around this returns false.
- @Override
- public boolean equals(@Nullable final Object o) {
- if (!(o instanceof SameL3NetworkResponse)) return false;
- final SameL3NetworkResponse other = (SameL3NetworkResponse) o;
- return l2Key1.equals(other.l2Key1) && l2Key2.equals(other.l2Key2)
- && confidence == other.confidence;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(l2Key1, l2Key2, confidence);
- }
-
- @Override
- /** Pretty print */
- public String toString() {
- switch (getNetworkSameness()) {
- case NETWORK_SAME:
- return "\"" + l2Key1 + "\" same L3 network as \"" + l2Key2 + "\"";
- case NETWORK_DIFFERENT:
- return "\"" + l2Key1 + "\" different L3 network from \"" + l2Key2 + "\"";
- case NETWORK_NEVER_CONNECTED:
- return "\"" + l2Key1 + "\" can't be tested against \"" + l2Key2 + "\"";
- default:
- return "Buggy sameness value ? \"" + l2Key1 + "\", \"" + l2Key2 + "\"";
- }
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 71966998a68a..000000000000
--- a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-/** {@hide} */
-parcelable SameL3NetworkResponseParcelable {
- String l2Key1;
- String l2Key2;
- float confidence;
-}
diff --git a/services/net/java/android/net/ipmemorystore/Status.java b/services/net/java/android/net/ipmemorystore/Status.java
deleted file mode 100644
index 13242c03ce01..000000000000
--- a/services/net/java/android/net/ipmemorystore/Status.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-/**
- * A parcelable status representing the result of an operation.
- * Parcels as StatusParceled.
- * @hide
- */
-public class Status {
- public static final int SUCCESS = 0;
-
- public static final int ERROR_GENERIC = -1;
- public static final int ERROR_ILLEGAL_ARGUMENT = -2;
- public static final int ERROR_DATABASE_CANNOT_BE_OPENED = -3;
- public static final int ERROR_STORAGE = -4;
- public static final int ERROR_UNKNOWN = -5;
-
- public final int resultCode;
-
- public Status(final int resultCode) {
- this.resultCode = resultCode;
- }
-
- @VisibleForTesting
- public Status(@NonNull final StatusParcelable parcelable) {
- this(parcelable.resultCode);
- }
-
- /** Converts this Status to a parcelable object */
- @NonNull
- public StatusParcelable toParcelable() {
- final StatusParcelable parcelable = new StatusParcelable();
- parcelable.resultCode = resultCode;
- return parcelable;
- }
-
- public boolean isSuccess() {
- return SUCCESS == resultCode;
- }
-
- /** Pretty print */
- @Override
- public String toString() {
- switch (resultCode) {
- case SUCCESS: return "SUCCESS";
- case ERROR_GENERIC: return "GENERIC ERROR";
- case ERROR_ILLEGAL_ARGUMENT: return "ILLEGAL ARGUMENT";
- case ERROR_DATABASE_CANNOT_BE_OPENED: return "DATABASE CANNOT BE OPENED";
- // "DB storage error" is not very helpful but SQLite does not provide specific error
- // codes upon store failure. Thus this indicates SQLite returned some error upon store
- case ERROR_STORAGE: return "DATABASE STORAGE ERROR";
- default: return "Unknown value ?!";
- }
- }
-}
diff --git a/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index fb36ef4a56ff..000000000000
--- a/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2018 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.net.ipmemorystore;
-
-/** {@hide} */
-parcelable StatusParcelable {
- int resultCode;
-}
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterTest.java b/services/tests/servicestests/src/com/android/server/display/utils/AmbientFilterTest.java
index 78164939aa49..9b76b13d2ede 100644
--- a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/utils/AmbientFilterTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.display.whitebalance;
+package com.android.server.display.utils;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
@@ -38,6 +38,7 @@ import org.junit.runners.JUnit4;
public final class AmbientFilterTest {
private ContextWrapper mContextSpy;
private Resources mResourcesSpy;
+ private static String TAG = "AmbientFilterTest";
@Before
public void setUp() throws Exception {
@@ -54,7 +55,7 @@ public final class AmbientFilterTest {
final int prediction_time = 100; // Hardcoded in AmbientFilter: prediction of how long the
// latest prediction will last before a new prediction.
setMockValues(mResourcesSpy, horizon, intercept);
- AmbientFilter filter = DisplayWhiteBalanceFactory.createBrightnessFilter(mResourcesSpy);
+ AmbientFilter filter = AmbientFilterFactory.createBrightnessFilter(TAG, mResourcesSpy);
// Add first value and verify
filter.addValue(time_start, 30);
@@ -85,7 +86,7 @@ public final class AmbientFilterTest {
final int prediction_time = 100;
setMockValues(mResourcesSpy, horizon, intercept);
- AmbientFilter filter = DisplayWhiteBalanceFactory.createBrightnessFilter(mResourcesSpy);
+ AmbientFilter filter = AmbientFilterFactory.createBrightnessFilter(TAG, mResourcesSpy);
// Add first value and verify
filter.addValue(time_start, 30);
diff --git a/services/net/java/android/net/IIpMemoryStoreCallbacks.aidl b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterStubber.java
index 53108dbca097..4d2551087c59 100644
--- a/services/net/java/android/net/IIpMemoryStoreCallbacks.aidl
+++ b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterStubber.java
@@ -14,11 +14,14 @@
* limitations under the License.
*/
-package android.net;
+package com.android.server.display.utils;
-import android.net.IIpMemoryStore;
+public class AmbientFilterStubber extends AmbientFilter {
+ public AmbientFilterStubber() {
+ super(null, 1);
+ }
-/** {@hide} */
-oneway interface IIpMemoryStoreCallbacks {
- void onIpMemoryStoreFetched(in IIpMemoryStore ipMemoryStore);
+ protected float filter(long time, RollingBuffer buffer) {
+ return 0f;
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
index 6b0798bdce22..0d5a7d6c1952 100644
--- a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
@@ -17,6 +17,8 @@
package com.android.server.display.whitebalance;
import com.android.internal.R;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterStubber;
import com.google.common.collect.ImmutableList;
import static org.junit.Assert.assertEquals;
@@ -132,7 +134,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -152,7 +154,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
setEstimatedBrightnessAndUpdate(controller,
@@ -184,7 +186,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
float luxOverride = mix(brightness0, brightness1, t);
@@ -221,7 +223,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
setEstimatedBrightnessAndUpdate(controller, 0.0f);
assertEquals(controller.mPendingAmbientColorTemperature,
@@ -240,7 +242,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -258,7 +260,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -278,7 +280,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
setEstimatedBrightnessAndUpdate(controller,
@@ -311,7 +313,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 6000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
float luxOverride = mix(brightness0, brightness1, t);
@@ -350,7 +352,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = 8000.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -370,7 +372,7 @@ public final class AmbientLuxTest {
DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
final float ambientColorTemperature = -1.0f;
setEstimatedColorTemperature(controller, ambientColorTemperature);
- controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+ controller.mBrightnessFilter = spy(new AmbientFilterStubber());
for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
setEstimatedBrightnessAndUpdate(controller,
@@ -426,7 +428,7 @@ public final class AmbientLuxTest {
private void setEstimatedColorTemperature(DisplayWhiteBalanceController controller,
float ambientColorTemperature) {
- AmbientFilter colorTemperatureFilter = spy(controller.mColorTemperatureFilter);
+ AmbientFilter colorTemperatureFilter = spy(new AmbientFilterStubber());
controller.mColorTemperatureFilter = colorTemperatureFilter;
when(colorTemperatureFilter.getEstimate(anyLong())).thenReturn(ambientColorTemperature);
}
diff --git a/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java b/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java
index 7aa3d0dfdd1f..3e9f625ecdd9 100644
--- a/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java
@@ -351,7 +351,7 @@ public class ProtoLogImplTest {
ProtoLogData data = readProtoLogSingle(ip);
assertNotNull(data);
assertEquals(1234, data.mMessageHash.longValue());
- assertTrue(before < data.mElapsedTime && data.mElapsedTime < after);
+ assertTrue(before <= data.mElapsedTime && data.mElapsedTime <= after);
assertArrayEquals(new String[]{"test"}, data.mStrParams.toArray());
assertArrayEquals(new Long[]{1L, 2L, 3L}, data.mSint64Params.toArray());
assertArrayEquals(new Double[]{0.4, 0.5, 0.6}, data.mDoubleParams.toArray());
@@ -376,7 +376,7 @@ public class ProtoLogImplTest {
ProtoLogData data = readProtoLogSingle(ip);
assertNotNull(data);
assertEquals(1234, data.mMessageHash.longValue());
- assertTrue(before < data.mElapsedTime && data.mElapsedTime < after);
+ assertTrue(before <= data.mElapsedTime && data.mElapsedTime <= after);
assertArrayEquals(new String[]{"test", "(INVALID PARAMS_MASK) true"},
data.mStrParams.toArray());
assertArrayEquals(new Long[]{1L}, data.mSint64Params.toArray());
diff --git a/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java b/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java
index ae5777403528..dd2ee5cce13b 100644
--- a/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java
+++ b/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java
@@ -16,7 +16,6 @@
package com.android.server.stats;
import static com.android.server.stats.ProcfsMemoryUtil.parseMemorySnapshotFromStatus;
-import static com.android.server.stats.ProcfsMemoryUtil.parseVmHWMFromStatus;
import static com.google.common.truth.Truth.assertThat;
@@ -80,45 +79,25 @@ public class ProcfsMemoryUtilTest {
+ "nonvoluntary_ctxt_switches:\t104\n";
@Test
- public void testParseVmHWMFromStatus_parsesCorrectValue() {
- assertThat(parseVmHWMFromStatus(STATUS_CONTENTS)).isEqualTo(137668);
- }
-
- @Test
- public void testParseVmHWMFromStatus_invalidValue() {
- assertThat(parseVmHWMFromStatus("test\nVmHWM: x0x0x\ntest")).isEqualTo(0);
- }
-
- @Test
- public void testParseVmHWMFromStatus_emptyContents() {
- assertThat(parseVmHWMFromStatus("")).isEqualTo(0);
- }
-
- @Test
public void testParseMemorySnapshotFromStatus_parsesCorrectValue() {
MemorySnapshot snapshot = parseMemorySnapshotFromStatus(STATUS_CONTENTS);
+ assertThat(snapshot.uid).isEqualTo(10083);
+ assertThat(snapshot.rssHighWaterMarkInKilobytes).isEqualTo(137668);
assertThat(snapshot.rssInKilobytes).isEqualTo(126776);
assertThat(snapshot.anonRssInKilobytes).isEqualTo(37860);
assertThat(snapshot.swapInKilobytes).isEqualTo(22);
- assertThat(snapshot.isEmpty()).isFalse();
}
@Test
public void testParseMemorySnapshotFromStatus_invalidValue() {
MemorySnapshot snapshot =
parseMemorySnapshotFromStatus("test\nVmRSS:\tx0x0x\nVmSwap:\t1 kB\ntest");
- assertThat(snapshot.rssInKilobytes).isEqualTo(0);
- assertThat(snapshot.anonRssInKilobytes).isEqualTo(0);
- assertThat(snapshot.swapInKilobytes).isEqualTo(1);
- assertThat(snapshot.isEmpty()).isFalse();
+ assertThat(snapshot).isNull();
}
@Test
public void testParseMemorySnapshotFromStatus_emptyContents() {
MemorySnapshot snapshot = parseMemorySnapshotFromStatus("");
- assertThat(snapshot.rssInKilobytes).isEqualTo(0);
- assertThat(snapshot.anonRssInKilobytes).isEqualTo(0);
- assertThat(snapshot.swapInKilobytes).isEqualTo(0);
- assertThat(snapshot.isEmpty()).isTrue();
+ assertThat(snapshot).isNull();
}
}
diff --git a/services/wifi/Android.bp b/services/wifi/Android.bp
index 608fc2c7a55e..3c916a6d00cd 100644
--- a/services/wifi/Android.bp
+++ b/services/wifi/Android.bp
@@ -5,9 +5,6 @@ java_library_static {
"java/**/*.java",
"java/**/*.aidl",
],
- aidl: {
- local_include_dirs: ["java"]
- },
libs: [
"services.net",
],
diff --git a/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl b/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl
index 3af4666b8d9c..eadc7260e81b 100644
--- a/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl
+++ b/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl
@@ -15,9 +15,8 @@
*/
package android.net.wifi;
-import android.net.wifi.WifiApiServiceInfo;
-
/** @hide */
interface IWifiStackConnector {
- List<WifiApiServiceInfo> getWifiApiServiceInfos();
+ IBinder retrieveApiServiceImpl(String serviceName);
+ boolean startApiService(String serviceName);
}
diff --git a/services/wifi/java/android/net/wifi/WifiStackClient.java b/services/wifi/java/android/net/wifi/WifiStackClient.java
index dcdfbc54687c..64af7a8845a7 100644
--- a/services/wifi/java/android/net/wifi/WifiStackClient.java
+++ b/services/wifi/java/android/net/wifi/WifiStackClient.java
@@ -21,13 +21,12 @@ import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
import android.annotation.NonNull;
import android.content.Context;
import android.net.ConnectivityModuleConnector;
+import android.os.HandlerThread;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
-import java.util.List;
-
/**
* Service used to communicate with the wifi stack, which could be running in a separate
* module.
@@ -57,23 +56,21 @@ public class WifiStackClient {
@Override
public void onModuleServiceConnected(IBinder service) {
Log.i(TAG, "Wifi stack connected");
- registerWifiStackService(service);
-
- IWifiStackConnector connector = IWifiStackConnector.Stub.asInterface(service);
- List<WifiApiServiceInfo> wifiApiServiceInfos;
- try {
- wifiApiServiceInfos = connector.getWifiApiServiceInfos();
- } catch (RemoteException e) {
- throw new RuntimeException("Failed to getWifiApiServiceInfos()", e);
- }
+ // spin up a new thread to not block system_server main thread
+ HandlerThread thread = new HandlerThread("InitWifiServicesThread");
+ thread.start();
+ thread.getThreadHandler().post(() -> {
+ registerWifiStackService(service);
+ IWifiStackConnector connector = IWifiStackConnector.Stub.asInterface(service);
+ registerApiServiceAndStart(connector, Context.WIFI_SCANNING_SERVICE);
+ registerApiServiceAndStart(connector, Context.WIFI_SERVICE);
+ registerApiServiceAndStart(connector, Context.WIFI_P2P_SERVICE);
+ registerApiServiceAndStart(connector, Context.WIFI_AWARE_SERVICE);
+ registerApiServiceAndStart(connector, Context.WIFI_RTT_RANGING_SERVICE);
- for (WifiApiServiceInfo wifiApiServiceInfo : wifiApiServiceInfos) {
- String serviceName = wifiApiServiceInfo.name;
- IBinder binder = wifiApiServiceInfo.binder;
- Log.i(TAG, "Registering " + serviceName);
- ServiceManager.addService(serviceName, binder);
- }
+ thread.quitSafely();
+ });
}
}
@@ -84,6 +81,32 @@ public class WifiStackClient {
Log.i(TAG, "Wifi stack service registered");
}
+ private void registerApiServiceAndStart(
+ IWifiStackConnector stackConnector, String serviceName) {
+ IBinder service = null;
+ try {
+ service = stackConnector.retrieveApiServiceImpl(serviceName);
+ } catch (RemoteException e) {
+ throw new RuntimeException("Failed to retrieve service impl " + serviceName, e);
+ }
+ if (service == null) {
+ Log.i(TAG, "Service " + serviceName + " not available");
+ return;
+ }
+ Log.i(TAG, "Registering " + serviceName);
+ ServiceManager.addService(serviceName, service);
+
+ boolean success = false;
+ try {
+ success = stackConnector.startApiService(serviceName);
+ } catch (RemoteException e) {
+ throw new RuntimeException("Failed to start service " + serviceName, e);
+ }
+ if (!success) {
+ throw new RuntimeException("Service " + serviceName + " start failed");
+ }
+ }
+
/**
* Start the wifi stack. Should be called only once on device startup.
*
diff --git a/startop/view_compiler/dex_builder.cc b/startop/view_compiler/dex_builder.cc
index 499c42e2888b..48b44d0fc99b 100644
--- a/startop/view_compiler/dex_builder.cc
+++ b/startop/view_compiler/dex_builder.cc
@@ -161,7 +161,7 @@ void WriteTestDexFile(const string& filename) {
MethodBuilder method{cbuilder.CreateMethod("foo", Prototype{TypeDescriptor::Int(), string_type})};
- Value result = method.MakeRegister();
+ LiveRegister result = method.AllocRegister();
MethodDeclData string_length =
dex_file.GetOrDeclareMethod(string_type, "length", Prototype{TypeDescriptor::Int()});
@@ -314,7 +314,7 @@ ir::EncodedMethod* MethodBuilder::Encode() {
CHECK(decl_->prototype != nullptr);
size_t const num_args =
decl_->prototype->param_types != nullptr ? decl_->prototype->param_types->types.size() : 0;
- code->registers = num_registers_ + num_args + kMaxScratchRegisters;
+ code->registers = NumRegisters() + num_args + kMaxScratchRegisters;
code->ins_count = num_args;
EncodeInstructions();
code->instructions = slicer::ArrayView<const ::dex::u2>(buffer_.data(), buffer_.size());
@@ -327,7 +327,20 @@ ir::EncodedMethod* MethodBuilder::Encode() {
return method;
}
-Value MethodBuilder::MakeRegister() { return Value::Local(num_registers_++); }
+LiveRegister MethodBuilder::AllocRegister() {
+ // Find a free register
+ for (size_t i = 0; i < register_liveness_.size(); ++i) {
+ if (!register_liveness_[i]) {
+ register_liveness_[i] = true;
+ return LiveRegister{&register_liveness_, i};
+ }
+ }
+
+ // If we get here, all the registers are in use, so we have to allocate a new
+ // one.
+ register_liveness_.push_back(true);
+ return LiveRegister{&register_liveness_, register_liveness_.size() - 1};
+}
Value MethodBuilder::MakeLabel() {
labels_.push_back({});
@@ -600,7 +613,7 @@ size_t MethodBuilder::RegisterValue(const Value& value) const {
if (value.is_register()) {
return value.value();
} else if (value.is_parameter()) {
- return value.value() + num_registers_ + kMaxScratchRegisters;
+ return value.value() + NumRegisters() + kMaxScratchRegisters;
}
CHECK(false && "Must be either a parameter or a register");
return 0;
diff --git a/startop/view_compiler/dex_builder.h b/startop/view_compiler/dex_builder.h
index 292d6599c115..3924e77fab59 100644
--- a/startop/view_compiler/dex_builder.h
+++ b/startop/view_compiler/dex_builder.h
@@ -140,6 +140,29 @@ class Value {
constexpr Value(size_t value, Kind kind) : value_{value}, kind_{kind} {}
};
+// Represents an allocated register returned by MethodBuilder::AllocRegister
+class LiveRegister {
+ friend class MethodBuilder;
+
+ public:
+ LiveRegister(LiveRegister&& other) : liveness_{other.liveness_}, index_{other.index_} {
+ other.index_ = {};
+ };
+ ~LiveRegister() {
+ if (index_.has_value()) {
+ (*liveness_)[*index_] = false;
+ }
+ };
+
+ operator const Value() const { return Value::Local(*index_); }
+
+ private:
+ LiveRegister(std::vector<bool>* liveness, size_t index) : liveness_{liveness}, index_{index} {}
+
+ std::vector<bool>* const liveness_;
+ std::optional<size_t> index_;
+};
+
// A virtual instruction. We convert these to real instructions in MethodBuilder::Encode.
// Virtual instructions are needed to keep track of information that is not known until all of the
// code is generated. This information includes things like how many local registers are created and
@@ -178,7 +201,8 @@ class Instruction {
}
// For most instructions, which take some number of arguments and have an optional return value.
template <typename... T>
- static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest, T... args) {
+ static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest,
+ const T&... args) {
return Instruction{opcode, /*index_argument=*/0, /*result_is_object=*/false, dest, args...};
}
@@ -199,14 +223,14 @@ class Instruction {
template <typename... T>
static inline Instruction InvokeVirtualObject(size_t index_argument,
std::optional<const Value> dest, Value this_arg,
- T... args) {
+ const T&... args) {
return Instruction{
Op::kInvokeVirtual, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
}
// For direct calls (basically, constructors).
template <typename... T>
static inline Instruction InvokeDirect(size_t index_argument, std::optional<const Value> dest,
- Value this_arg, T... args) {
+ Value this_arg, const T&... args) {
return Instruction{
Op::kInvokeDirect, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
}
@@ -234,7 +258,7 @@ class Instruction {
// For static calls.
template <typename... T>
static inline Instruction InvokeInterface(size_t index_argument, std::optional<const Value> dest,
- T... args) {
+ const T&... args) {
return Instruction{
Op::kInvokeInterface, index_argument, /*result_is_object=*/false, dest, args...};
}
@@ -277,7 +301,7 @@ class Instruction {
template <typename... T>
inline Instruction(Op opcode, size_t index_argument, bool result_is_object,
- std::optional<const Value> dest, T... args)
+ std::optional<const Value> dest, const T&... args)
: opcode_{opcode},
index_argument_{index_argument},
result_is_object_{result_is_object},
@@ -309,10 +333,8 @@ class MethodBuilder {
// Encode the method into DEX format.
ir::EncodedMethod* Encode();
- // Create a new register to be used to storing values. Note that these are not SSA registers, like
- // might be expected in similar code generators. This does no liveness tracking or anything, so
- // it's up to the caller to reuse registers as appropriate.
- Value MakeRegister();
+ // Create a new register to be used to storing values.
+ LiveRegister AllocRegister();
Value MakeLabel();
@@ -329,7 +351,7 @@ class MethodBuilder {
void BuildConst4(Value target, int value);
void BuildConstString(Value target, const std::string& value);
template <typename... T>
- void BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args);
+ void BuildNew(Value target, TypeDescriptor type, Prototype constructor, const T&... args);
// TODO: add builders for more instructions
@@ -427,7 +449,7 @@ class MethodBuilder {
static_assert(num_regs <= kMaxScratchRegisters);
std::array<Value, num_regs> regs;
for (size_t i = 0; i < num_regs; ++i) {
- regs[i] = std::move(Value::Local(num_registers_ + i));
+ regs[i] = std::move(Value::Local(NumRegisters() + i));
}
return regs;
}
@@ -457,8 +479,9 @@ class MethodBuilder {
// around to make legal DEX code.
static constexpr size_t kMaxScratchRegisters = 5;
- // How many registers we've allocated
- size_t num_registers_{0};
+ size_t NumRegisters() const {
+ return register_liveness_.size();
+ }
// Stores information needed to back-patch a label once it is bound. We need to know the start of
// the instruction that refers to the label, and the offset to where the actual label value should
@@ -478,6 +501,8 @@ class MethodBuilder {
// During encoding, keep track of the largest number of arguments needed, so we can use it for our
// outs count
size_t max_args_{0};
+
+ std::vector<bool> register_liveness_;
};
// A helper to build class definitions.
@@ -576,7 +601,8 @@ class DexBuilder {
};
template <typename... T>
-void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args) {
+void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor,
+ const T&... args) {
MethodDeclData constructor_data{dex_->GetOrDeclareMethod(type, "<init>", constructor)};
// allocate the object
ir::Type* type_def = dex_->GetOrAddType(type.descriptor());
diff --git a/startop/view_compiler/dex_layout_compiler.cc b/startop/view_compiler/dex_layout_compiler.cc
index 8febfb71ecd1..cb820f8f20fb 100644
--- a/startop/view_compiler/dex_layout_compiler.cc
+++ b/startop/view_compiler/dex_layout_compiler.cc
@@ -22,76 +22,94 @@
namespace startop {
using android::base::StringPrintf;
+using dex::Instruction;
+using dex::LiveRegister;
+using dex::Prototype;
+using dex::TypeDescriptor;
+using dex::Value;
+
+namespace {
+// TODO: these are a bunch of static initializers, which we should avoid. See if
+// we can make them constexpr.
+const TypeDescriptor kAttributeSet = TypeDescriptor::FromClassname("android.util.AttributeSet");
+const TypeDescriptor kContext = TypeDescriptor::FromClassname("android.content.Context");
+const TypeDescriptor kLayoutInflater = TypeDescriptor::FromClassname("android.view.LayoutInflater");
+const TypeDescriptor kResources = TypeDescriptor::FromClassname("android.content.res.Resources");
+const TypeDescriptor kString = TypeDescriptor::FromClassname("java.lang.String");
+const TypeDescriptor kView = TypeDescriptor::FromClassname("android.view.View");
+const TypeDescriptor kViewGroup = TypeDescriptor::FromClassname("android.view.ViewGroup");
+const TypeDescriptor kXmlResourceParser =
+ TypeDescriptor::FromClassname("android.content.res.XmlResourceParser");
+} // namespace
DexViewBuilder::DexViewBuilder(dex::MethodBuilder* method)
: method_{method},
- context_{dex::Value::Parameter(0)},
- resid_{dex::Value::Parameter(1)},
- inflater_{method->MakeRegister()},
- xml_{method->MakeRegister()},
- attrs_{method->MakeRegister()},
- classname_tmp_{method->MakeRegister()},
- xml_next_{method->dex_file()->GetOrDeclareMethod(
- dex::TypeDescriptor::FromClassname("android.content.res.XmlResourceParser"), "next",
- dex::Prototype{dex::TypeDescriptor::Int()})},
+ context_{Value::Parameter(0)},
+ resid_{Value::Parameter(1)},
+ inflater_{method->AllocRegister()},
+ xml_{method->AllocRegister()},
+ attrs_{method->AllocRegister()},
+ classname_tmp_{method->AllocRegister()},
+ xml_next_{method->dex_file()->GetOrDeclareMethod(kXmlResourceParser, "next",
+ Prototype{TypeDescriptor::Int()})},
try_create_view_{method->dex_file()->GetOrDeclareMethod(
- dex::TypeDescriptor::FromClassname("android.view.LayoutInflater"), "tryCreateView",
- dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.View"),
- dex::TypeDescriptor::FromClassname("android.view.View"),
- dex::TypeDescriptor::FromClassname("java.lang.String"),
- dex::TypeDescriptor::FromClassname("android.content.Context"),
- dex::TypeDescriptor::FromClassname("android.util.AttributeSet")})},
+ kLayoutInflater, "tryCreateView",
+ Prototype{kView, kView, kString, kContext, kAttributeSet})},
generate_layout_params_{method->dex_file()->GetOrDeclareMethod(
- dex::TypeDescriptor::FromClassname("android.view.ViewGroup"), "generateLayoutParams",
- dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams"),
- dex::TypeDescriptor::FromClassname("android.util.AttributeSet")})},
+ kViewGroup, "generateLayoutParams",
+ Prototype{TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams"),
+ kAttributeSet})},
add_view_{method->dex_file()->GetOrDeclareMethod(
- dex::TypeDescriptor::FromClassname("android.view.ViewGroup"), "addView",
- dex::Prototype{
- dex::TypeDescriptor::Void(),
- dex::TypeDescriptor::FromClassname("android.view.View"),
- dex::TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams")})},
- // The register stack starts with one register, which will be null for the root view.
- register_stack_{{method->MakeRegister()}} {}
-
-void DexViewBuilder::Start() {
- dex::DexBuilder* const dex = method_->dex_file();
-
- // LayoutInflater inflater = LayoutInflater.from(context);
- auto layout_inflater_from = dex->GetOrDeclareMethod(
- dex::TypeDescriptor::FromClassname("android.view.LayoutInflater"),
- "from",
- dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.LayoutInflater"),
- dex::TypeDescriptor::FromClassname("android.content.Context")});
- method_->AddInstruction(
- dex::Instruction::InvokeStaticObject(layout_inflater_from.id, /*dest=*/inflater_, context_));
+ kViewGroup, "addView",
+ Prototype{TypeDescriptor::Void(),
+ kView,
+ TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams")})} {}
+
+void DexViewBuilder::BuildGetLayoutInflater(Value dest) {
+ // dest = LayoutInflater.from(context);
+ auto layout_inflater_from = method_->dex_file()->GetOrDeclareMethod(
+ kLayoutInflater, "from", Prototype{kLayoutInflater, kContext});
+ method_->AddInstruction(Instruction::InvokeStaticObject(layout_inflater_from.id, dest, context_));
+}
- // Resources res = context.getResources();
- auto context_type = dex::TypeDescriptor::FromClassname("android.content.Context");
- auto resources_type = dex::TypeDescriptor::FromClassname("android.content.res.Resources");
+void DexViewBuilder::BuildGetResources(Value dest) {
+ // dest = context.getResources();
auto get_resources =
- dex->GetOrDeclareMethod(context_type, "getResources", dex::Prototype{resources_type});
- method_->AddInstruction(dex::Instruction::InvokeVirtualObject(get_resources.id, xml_, context_));
-
- // XmlResourceParser xml = res.getLayout(resid);
- auto xml_resource_parser_type =
- dex::TypeDescriptor::FromClassname("android.content.res.XmlResourceParser");
- auto get_layout =
- dex->GetOrDeclareMethod(resources_type,
- "getLayout",
- dex::Prototype{xml_resource_parser_type, dex::TypeDescriptor::Int()});
- method_->AddInstruction(dex::Instruction::InvokeVirtualObject(get_layout.id, xml_, xml_, resid_));
-
- // AttributeSet attrs = Xml.asAttributeSet(xml);
- auto as_attribute_set = dex->GetOrDeclareMethod(
- dex::TypeDescriptor::FromClassname("android.util.Xml"),
+ method_->dex_file()->GetOrDeclareMethod(kContext, "getResources", Prototype{kResources});
+ method_->AddInstruction(Instruction::InvokeVirtualObject(get_resources.id, dest, context_));
+}
+
+void DexViewBuilder::BuildGetLayoutResource(Value dest, Value resources, Value resid) {
+ // dest = resources.getLayout(resid);
+ auto get_layout = method_->dex_file()->GetOrDeclareMethod(
+ kResources, "getLayout", Prototype{kXmlResourceParser, TypeDescriptor::Int()});
+ method_->AddInstruction(Instruction::InvokeVirtualObject(get_layout.id, dest, resources, resid));
+}
+
+void DexViewBuilder::BuildLayoutResourceToAttributeSet(dex::Value dest,
+ dex::Value layout_resource) {
+ // dest = Xml.asAttributeSet(layout_resource);
+ auto as_attribute_set = method_->dex_file()->GetOrDeclareMethod(
+ TypeDescriptor::FromClassname("android.util.Xml"),
"asAttributeSet",
- dex::Prototype{dex::TypeDescriptor::FromClassname("android.util.AttributeSet"),
- dex::TypeDescriptor::FromClassname("org.xmlpull.v1.XmlPullParser")});
- method_->AddInstruction(dex::Instruction::InvokeStaticObject(as_attribute_set.id, attrs_, xml_));
+ Prototype{kAttributeSet, TypeDescriptor::FromClassname("org.xmlpull.v1.XmlPullParser")});
+ method_->AddInstruction(
+ Instruction::InvokeStaticObject(as_attribute_set.id, dest, layout_resource));
+}
- // xml.next(); // start document
- method_->AddInstruction(dex::Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+void DexViewBuilder::BuildXmlNext() {
+ // xml_.next();
+ method_->AddInstruction(Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+}
+
+void DexViewBuilder::Start() {
+ BuildGetLayoutInflater(/*dest=*/inflater_);
+ BuildGetResources(/*dest=*/xml_);
+ BuildGetLayoutResource(/*dest=*/xml_, /*resources=*/xml_, resid_);
+ BuildLayoutResourceToAttributeSet(/*dest=*/attrs_, /*layout_resource=*/xml_);
+
+ // Advance past start document tag
+ BuildXmlNext();
}
void DexViewBuilder::Finish() {}
@@ -107,58 +125,57 @@ std::string ResolveName(const std::string& name) {
}
} // namespace
+void DexViewBuilder::BuildTryCreateView(Value dest, Value parent, Value classname) {
+ // dest = inflater_.tryCreateView(parent, classname, context_, attrs_);
+ method_->AddInstruction(Instruction::InvokeVirtualObject(
+ try_create_view_.id, dest, inflater_, parent, classname, context_, attrs_));
+}
+
void DexViewBuilder::StartView(const std::string& name, bool is_viewgroup) {
bool const is_root_view = view_stack_.empty();
- // xml.next(); // start tag
- method_->AddInstruction(dex::Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+ // Advance to start tag
+ BuildXmlNext();
- dex::Value view = AcquireRegister();
+ LiveRegister view = AcquireRegister();
// try to create the view using the factories
method_->BuildConstString(classname_tmp_,
name); // TODO: the need to fully qualify the classname
if (is_root_view) {
- dex::Value null = AcquireRegister();
+ LiveRegister null = AcquireRegister();
method_->BuildConst4(null, 0);
- method_->AddInstruction(dex::Instruction::InvokeVirtualObject(
- try_create_view_.id, view, inflater_, null, classname_tmp_, context_, attrs_));
- ReleaseRegister();
+ BuildTryCreateView(/*dest=*/view, /*parent=*/null, classname_tmp_);
} else {
- method_->AddInstruction(dex::Instruction::InvokeVirtualObject(
- try_create_view_.id, view, inflater_, GetCurrentView(), classname_tmp_, context_, attrs_));
+ BuildTryCreateView(/*dest=*/view, /*parent=*/GetCurrentView(), classname_tmp_);
}
auto label = method_->MakeLabel();
// branch if not null
method_->AddInstruction(
- dex::Instruction::OpWithArgs(dex::Instruction::Op::kBranchNEqz, /*dest=*/{}, view, label));
+ Instruction::OpWithArgs(Instruction::Op::kBranchNEqz, /*dest=*/{}, view, label));
// If null, create the class directly.
method_->BuildNew(view,
- dex::TypeDescriptor::FromClassname(ResolveName(name)),
- dex::Prototype{dex::TypeDescriptor::Void(),
- dex::TypeDescriptor::FromClassname("android.content.Context"),
- dex::TypeDescriptor::FromClassname("android.util.AttributeSet")},
+ TypeDescriptor::FromClassname(ResolveName(name)),
+ Prototype{TypeDescriptor::Void(), kContext, kAttributeSet},
context_,
attrs_);
- method_->AddInstruction(
- dex::Instruction::OpWithArgs(dex::Instruction::Op::kBindLabel, /*dest=*/{}, label));
+ method_->AddInstruction(Instruction::OpWithArgs(Instruction::Op::kBindLabel, /*dest=*/{}, label));
if (is_viewgroup) {
// Cast to a ViewGroup so we can add children later.
- const ir::Type* view_group_def = method_->dex_file()->GetOrAddType(
- dex::TypeDescriptor::FromClassname("android.view.ViewGroup").descriptor());
- method_->AddInstruction(dex::Instruction::Cast(view, dex::Value::Type(view_group_def->orig_index)));
+ const ir::Type* view_group_def = method_->dex_file()->GetOrAddType(kViewGroup.descriptor());
+ method_->AddInstruction(Instruction::Cast(view, Value::Type(view_group_def->orig_index)));
}
if (!is_root_view) {
// layout_params = parent.generateLayoutParams(attrs);
- dex::Value layout_params{AcquireRegister()};
- method_->AddInstruction(dex::Instruction::InvokeVirtualObject(
+ LiveRegister layout_params{AcquireRegister()};
+ method_->AddInstruction(Instruction::InvokeVirtualObject(
generate_layout_params_.id, layout_params, GetCurrentView(), attrs_));
- view_stack_.push_back({view, layout_params});
+ view_stack_.push_back({std::move(view), std::move(layout_params)});
} else {
- view_stack_.push_back({view, {}});
+ view_stack_.push_back({std::move(view), {}});
}
}
@@ -167,40 +184,24 @@ void DexViewBuilder::FinishView() {
method_->BuildReturn(GetCurrentView(), /*is_object=*/true);
} else {
// parent.add(view, layout_params)
- method_->AddInstruction(dex::Instruction::InvokeVirtual(
+ method_->AddInstruction(Instruction::InvokeVirtual(
add_view_.id, /*dest=*/{}, GetParentView(), GetCurrentView(), GetCurrentLayoutParams()));
// xml.next(); // end tag
- method_->AddInstruction(dex::Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+ method_->AddInstruction(Instruction::InvokeInterface(xml_next_.id, {}, xml_));
}
PopViewStack();
}
-dex::Value DexViewBuilder::AcquireRegister() {
- top_register_++;
- if (register_stack_.size() == top_register_) {
- register_stack_.push_back(method_->MakeRegister());
- }
- return register_stack_[top_register_];
-}
-
-void DexViewBuilder::ReleaseRegister() { top_register_--; }
+LiveRegister DexViewBuilder::AcquireRegister() { return method_->AllocRegister(); }
-dex::Value DexViewBuilder::GetCurrentView() const { return view_stack_.back().view; }
-dex::Value DexViewBuilder::GetCurrentLayoutParams() const {
+Value DexViewBuilder::GetCurrentView() const { return view_stack_.back().view; }
+Value DexViewBuilder::GetCurrentLayoutParams() const {
return view_stack_.back().layout_params.value();
}
-dex::Value DexViewBuilder::GetParentView() const {
- return view_stack_[view_stack_.size() - 2].view;
-}
+Value DexViewBuilder::GetParentView() const { return view_stack_[view_stack_.size() - 2].view; }
void DexViewBuilder::PopViewStack() {
- const auto& top = view_stack_.back();
- // release the layout params if we have them
- if (top.layout_params.has_value()) {
- ReleaseRegister();
- }
// Unconditionally release the view register.
- ReleaseRegister();
view_stack_.pop_back();
}
diff --git a/startop/view_compiler/dex_layout_compiler.h b/startop/view_compiler/dex_layout_compiler.h
index 170a1a610297..a34ed1f0168e 100644
--- a/startop/view_compiler/dex_layout_compiler.h
+++ b/startop/view_compiler/dex_layout_compiler.h
@@ -79,36 +79,41 @@ class DexViewBuilder {
private:
// Accessors for the stack of views that are under construction.
- dex::Value AcquireRegister();
- void ReleaseRegister();
+ dex::LiveRegister AcquireRegister();
dex::Value GetCurrentView() const;
dex::Value GetCurrentLayoutParams() const;
dex::Value GetParentView() const;
void PopViewStack();
+ // Methods to simplify building different code fragments.
+ void BuildGetLayoutInflater(dex::Value dest);
+ void BuildGetResources(dex::Value dest);
+ void BuildGetLayoutResource(dex::Value dest, dex::Value resources, dex::Value resid);
+ void BuildLayoutResourceToAttributeSet(dex::Value dest, dex::Value layout_resource);
+ void BuildXmlNext();
+ void BuildTryCreateView(dex::Value dest, dex::Value parent, dex::Value classname);
+
dex::MethodBuilder* method_;
- // Registers used for code generation
+ // Parameters to the generated method
dex::Value const context_;
dex::Value const resid_;
- const dex::Value inflater_;
- const dex::Value xml_;
- const dex::Value attrs_;
- const dex::Value classname_tmp_;
+
+ // Registers used for code generation
+ const dex::LiveRegister inflater_;
+ const dex::LiveRegister xml_;
+ const dex::LiveRegister attrs_;
+ const dex::LiveRegister classname_tmp_;
const dex::MethodDeclData xml_next_;
const dex::MethodDeclData try_create_view_;
const dex::MethodDeclData generate_layout_params_;
const dex::MethodDeclData add_view_;
- // used for keeping track of which registers are in use
- size_t top_register_{0};
- std::vector<dex::Value> register_stack_;
-
// Keep track of the views currently in progress.
struct ViewEntry {
- dex::Value view;
- std::optional<dex::Value> layout_params;
+ dex::LiveRegister view;
+ std::optional<dex::LiveRegister> layout_params;
};
std::vector<ViewEntry> view_stack_;
};
diff --git a/startop/view_compiler/dex_testcase_generator.cc b/startop/view_compiler/dex_testcase_generator.cc
index 6dedf24e290d..5dda59e3473f 100644
--- a/startop/view_compiler/dex_testcase_generator.cc
+++ b/startop/view_compiler/dex_testcase_generator.cc
@@ -47,7 +47,7 @@ void GenerateSimpleTestCases(const string& outdir) {
// int return5() { return 5; }
auto return5{cbuilder.CreateMethod("return5", Prototype{TypeDescriptor::Int()})};
{
- Value r{return5.MakeRegister()};
+ LiveRegister r{return5.AllocRegister()};
return5.BuildConst4(r, 5);
return5.BuildReturn(r);
}
@@ -57,9 +57,9 @@ void GenerateSimpleTestCases(const string& outdir) {
auto integer_type{TypeDescriptor::FromClassname("java.lang.Integer")};
auto returnInteger5{cbuilder.CreateMethod("returnInteger5", Prototype{integer_type})};
[&](MethodBuilder& method) {
- Value five{method.MakeRegister()};
+ LiveRegister five{method.AllocRegister()};
method.BuildConst4(five, 5);
- Value object{method.MakeRegister()};
+ LiveRegister object{method.AllocRegister()};
method.BuildNew(
object, integer_type, Prototype{TypeDescriptor::Void(), TypeDescriptor::Int()}, five);
method.BuildReturn(object, /*is_object=*/true);
@@ -80,7 +80,7 @@ void GenerateSimpleTestCases(const string& outdir) {
auto returnStringLength{
cbuilder.CreateMethod("returnStringLength", Prototype{TypeDescriptor::Int(), string_type})};
{
- Value result = returnStringLength.MakeRegister();
+ LiveRegister result = returnStringLength.AllocRegister();
returnStringLength.AddInstruction(
Instruction::InvokeVirtual(string_length.id, result, Value::Parameter(0)));
returnStringLength.BuildReturn(result);
@@ -91,7 +91,7 @@ void GenerateSimpleTestCases(const string& outdir) {
MethodBuilder returnIfZero{cbuilder.CreateMethod(
"returnIfZero", Prototype{TypeDescriptor::Int(), TypeDescriptor::Int()})};
{
- Value resultIfZero{returnIfZero.MakeRegister()};
+ LiveRegister resultIfZero{returnIfZero.AllocRegister()};
Value else_target{returnIfZero.MakeLabel()};
returnIfZero.AddInstruction(Instruction::OpWithArgs(
Instruction::Op::kBranchEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -112,7 +112,7 @@ void GenerateSimpleTestCases(const string& outdir) {
MethodBuilder returnIfNotZero{cbuilder.CreateMethod(
"returnIfNotZero", Prototype{TypeDescriptor::Int(), TypeDescriptor::Int()})};
{
- Value resultIfNotZero{returnIfNotZero.MakeRegister()};
+ LiveRegister resultIfNotZero{returnIfNotZero.AllocRegister()};
Value else_target{returnIfNotZero.MakeLabel()};
returnIfNotZero.AddInstruction(Instruction::OpWithArgs(
Instruction::Op::kBranchNEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -148,8 +148,8 @@ void GenerateSimpleTestCases(const string& outdir) {
MethodBuilder backwardsBranch{
cbuilder.CreateMethod("backwardsBranch", Prototype{TypeDescriptor::Int()})};
[](MethodBuilder& method) {
- Value zero = method.MakeRegister();
- Value result = method.MakeRegister();
+ LiveRegister zero = method.AllocRegister();
+ LiveRegister result = method.AllocRegister();
Value labelA = method.MakeLabel();
Value labelB = method.MakeLabel();
method.BuildConst4(zero, 0);
@@ -177,7 +177,7 @@ void GenerateSimpleTestCases(const string& outdir) {
// public static String returnNull() { return null; }
MethodBuilder returnNull{cbuilder.CreateMethod("returnNull", Prototype{string_type})};
[](MethodBuilder& method) {
- Value zero = method.MakeRegister();
+ LiveRegister zero = method.AllocRegister();
method.BuildConst4(zero, 0);
method.BuildReturn(zero, /*is_object=*/true);
}(returnNull);
@@ -188,7 +188,7 @@ void GenerateSimpleTestCases(const string& outdir) {
// public static String makeString() { return "Hello, World!"; }
MethodBuilder makeString{cbuilder.CreateMethod("makeString", Prototype{string_type})};
[](MethodBuilder& method) {
- Value string = method.MakeRegister();
+ LiveRegister string = method.AllocRegister();
method.BuildConstString(string, "Hello, World!");
method.BuildReturn(string, /*is_object=*/true);
}(makeString);
@@ -200,7 +200,7 @@ void GenerateSimpleTestCases(const string& outdir) {
MethodBuilder returnStringIfZeroAB{
cbuilder.CreateMethod("returnStringIfZeroAB", Prototype{string_type, TypeDescriptor::Int()})};
[&](MethodBuilder& method) {
- Value resultIfZero{method.MakeRegister()};
+ LiveRegister resultIfZero{method.AllocRegister()};
Value else_target{method.MakeLabel()};
method.AddInstruction(Instruction::OpWithArgs(
Instruction::Op::kBranchEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -220,7 +220,7 @@ void GenerateSimpleTestCases(const string& outdir) {
MethodBuilder returnStringIfZeroBA{
cbuilder.CreateMethod("returnStringIfZeroBA", Prototype{string_type, TypeDescriptor::Int()})};
[&](MethodBuilder& method) {
- Value resultIfZero{method.MakeRegister()};
+ LiveRegister resultIfZero{method.AllocRegister()};
Value else_target{method.MakeLabel()};
method.AddInstruction(Instruction::OpWithArgs(
Instruction::Op::kBranchEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -244,7 +244,7 @@ void GenerateSimpleTestCases(const string& outdir) {
cbuilder.CreateMethod("invokeStaticReturnObject",
Prototype{string_type, TypeDescriptor::Int(), TypeDescriptor::Int()})};
[&](MethodBuilder& method) {
- Value result{method.MakeRegister()};
+ LiveRegister result{method.AllocRegister()};
MethodDeclData to_string{dex_file.GetOrDeclareMethod(
TypeDescriptor::FromClassname("java.lang.Integer"),
"toString",
@@ -260,7 +260,7 @@ void GenerateSimpleTestCases(const string& outdir) {
MethodBuilder invokeVirtualReturnObject{cbuilder.CreateMethod(
"invokeVirtualReturnObject", Prototype{string_type, string_type, TypeDescriptor::Int()})};
[&](MethodBuilder& method) {
- Value result{method.MakeRegister()};
+ LiveRegister result{method.AllocRegister()};
MethodDeclData substring{dex_file.GetOrDeclareMethod(
string_type, "substring", Prototype{string_type, TypeDescriptor::Int()})};
method.AddInstruction(Instruction::InvokeVirtualObject(
@@ -291,7 +291,7 @@ void GenerateSimpleTestCases(const string& outdir) {
[&](MethodBuilder& method) {
const ir::FieldDecl* field =
dex_file.GetOrAddField(test_class, "staticInteger", TypeDescriptor::Int());
- Value result{method.MakeRegister()};
+ LiveRegister result{method.AllocRegister()};
method.AddInstruction(Instruction::GetStaticField(field->orig_index, result));
method.BuildReturn(result, /*is_object=*/false);
method.Encode();
@@ -304,7 +304,7 @@ void GenerateSimpleTestCases(const string& outdir) {
[&](MethodBuilder& method) {
const ir::FieldDecl* field =
dex_file.GetOrAddField(test_class, "staticInteger", TypeDescriptor::Int());
- Value number{method.MakeRegister()};
+ LiveRegister number{method.AllocRegister()};
method.BuildConst4(number, 7);
method.AddInstruction(Instruction::SetStaticField(field->orig_index, number));
method.BuildReturn();
@@ -318,7 +318,7 @@ void GenerateSimpleTestCases(const string& outdir) {
[&](MethodBuilder& method) {
const ir::FieldDecl* field =
dex_file.GetOrAddField(test_class, "instanceField", TypeDescriptor::Int());
- Value result{method.MakeRegister()};
+ LiveRegister result{method.AllocRegister()};
method.AddInstruction(Instruction::GetField(field->orig_index, result, Value::Parameter(0)));
method.BuildReturn(result, /*is_object=*/false);
method.Encode();
@@ -331,7 +331,7 @@ void GenerateSimpleTestCases(const string& outdir) {
[&](MethodBuilder& method) {
const ir::FieldDecl* field =
dex_file.GetOrAddField(test_class, "instanceField", TypeDescriptor::Int());
- Value number{method.MakeRegister()};
+ LiveRegister number{method.AllocRegister()};
method.BuildConst4(number, 7);
method.AddInstruction(Instruction::SetField(field->orig_index, Value::Parameter(0), number));
method.BuildReturn();
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 51de903ed37e..dcd35fdc4e16 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -896,6 +896,11 @@ public class SubscriptionManager {
*/
public static final String EXTRA_SUBSCRIPTION_INDEX = "android.telephony.extra.SUBSCRIPTION_INDEX";
+ /**
+ * Integer extra to specify SIM slot index.
+ */
+ public static final String EXTRA_SLOT_INDEX = "android.telephony.extra.SLOT_INDEX";
+
private final Context mContext;
private volatile INetworkPolicyManager mNetworkPolicy;
@@ -2123,6 +2128,7 @@ public class SubscriptionManager {
if (VDBG) logd("putPhoneIdAndSubIdExtra: phoneId=" + phoneId + " subId=" + subId);
intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
intent.putExtra(EXTRA_SUBSCRIPTION_INDEX, subId);
+ intent.putExtra(EXTRA_SLOT_INDEX, phoneId);
intent.putExtra(PhoneConstants.PHONE_KEY, phoneId);
}
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 4fb9903a10be..4f276bc845ca 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -2449,41 +2449,37 @@ public class TelephonyManager {
* @return the lowercase 2 character ISO-3166 country code, or empty string if not available.
*/
public String getNetworkCountryIso() {
- return getNetworkCountryIsoForPhone(getPhoneId());
+ return getNetworkCountryIso(getPhoneId());
}
/**
- * Returns the ISO country code equivalent of the MCC (Mobile Country Code) of the current
+ * Returns the ISO-3166 country code equivalent of the MCC (Mobile Country Code) of the current
* registered operator or the cell nearby, if available.
* <p>
+ * The ISO-3166 country code is provided in lowercase 2 character format.
+ * <p>
+ * Note: In multi-sim, this returns a shared emergency network country iso from other
+ * subscription if the subscription used to create the TelephonyManager doesn't camp on
+ * a network due to some reason (e.g. pin/puk locked), or sim is absent in the corresponding
+ * slot.
* Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
* if on a CDMA network).
- *
- * @param subId for which Network CountryIso is returned
- * @hide
- */
- @UnsupportedAppUsage
- public String getNetworkCountryIso(int subId) {
- return getNetworkCountryIsoForPhone(getPhoneId(subId));
- }
-
- /**
- * Returns the ISO country code equivalent of the current registered
- * operator's MCC (Mobile Country Code) of a subscription.
* <p>
- * Availability: Only when user is registered to a network. Result may be
- * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
- * on a CDMA network).
*
- * @param phoneId for which Network CountryIso is returned
+ * @param slotIndex the SIM slot index to get network country ISO.
+ *
+ * @return the lowercase 2 character ISO-3166 country code, or empty string if not available.
+ *
+ * {@hide}
*/
- /** {@hide} */
- @UnsupportedAppUsage
- public String getNetworkCountryIsoForPhone(int phoneId) {
+ @SystemApi
+ @TestApi
+ @NonNull
+ public String getNetworkCountryIso(int slotIndex) {
try {
ITelephony telephony = getITelephony();
if (telephony == null) return "";
- return telephony.getNetworkCountryIsoForPhone(phoneId);
+ return telephony.getNetworkCountryIsoForPhone(slotIndex);
} catch (RemoteException ex) {
return "";
}
diff --git a/tests/ApkVerityTest/Android.bp b/tests/ApkVerityTest/Android.bp
new file mode 100644
index 000000000000..adcbb4287dd0
--- /dev/null
+++ b/tests/ApkVerityTest/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2019 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.
+
+java_test_host {
+ name: "ApkVerityTests",
+ srcs: ["src/**/*.java"],
+ libs: ["tradefed", "compatibility-tradefed", "compatibility-host-util"],
+ test_suites: ["general-tests"],
+ target_required: [
+ "block_device_writer_module",
+ "ApkVerityTestApp",
+ "ApkVerityTestAppSplit",
+ ],
+ data: [
+ ":ApkVerityTestCertDer",
+ ":ApkVerityTestAppFsvSig",
+ ":ApkVerityTestAppDm",
+ ":ApkVerityTestAppDmFsvSig",
+ ":ApkVerityTestAppSplitFsvSig",
+ ":ApkVerityTestAppSplitDm",
+ ":ApkVerityTestAppSplitDmFsvSig",
+ ],
+}
diff --git a/tests/ApkVerityTest/AndroidTest.xml b/tests/ApkVerityTest/AndroidTest.xml
new file mode 100644
index 000000000000..73779cbd1a87
--- /dev/null
+++ b/tests/ApkVerityTest/AndroidTest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<configuration description="APK fs-verity integration/regression test">
+ <option name="test-suite-tag" value="apct" />
+
+ <!-- This test requires root to write against block device. -->
+ <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer" />
+
+ <target_preparer class="com.android.tradefed.targetprep.DeviceSetup">
+ <!-- Disable package verifier prevents it holding the target APK's fd that prevents cache
+ eviction. -->
+ <option name="set-global-setting" key="package_verifier_enable" value="0" />
+ <option name="restore-settings" value="true" />
+
+ <!-- Skip in order to prevent reboot that confuses the test flow. -->
+ <option name="force-skip-system-props" value="true" />
+ </target_preparer>
+
+ <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+ <option name="cleanup" value="true" />
+ <option name="push" value="block_device_writer->/data/local/tmp/block_device_writer" />
+ <option name="push" value="ApkVerityTestCert.der->/data/local/tmp/ApkVerityTestCert.der" />
+ </target_preparer>
+
+ <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+ <option name="jar" value="ApkVerityTests.jar" />
+ </test>
+</configuration>
diff --git a/tests/FlickerTests/lib/test/Android.bp b/tests/ApkVerityTest/ApkVerityTestApp/Android.bp
index bfeb75b23469..69632b215822 100644
--- a/tests/FlickerTests/lib/test/Android.bp
+++ b/tests/ApkVerityTest/ApkVerityTestApp/Android.bp
@@ -1,5 +1,4 @@
-//
-// Copyright (C) 2018 The Android Open Source Project
+// Copyright (C) 2019 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.
@@ -12,22 +11,19 @@
// 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.
-//
-android_test {
- name: "FlickerLibTest",
- // sign this with platform cert, so this test is allowed to call private platform apis
- certificate: "platform",
- platform_apis: true,
- test_suites: ["tests"],
- srcs: ["src/**/*.java"],
- libs: ["android.test.runner"],
- static_libs: [
- "androidx.test.rules",
- "platform-test-annotations",
- "truth-prebuilt",
- "platformprotosnano",
- "layersprotosnano",
- "flickerlib",
- ],
+android_test_helper_app {
+ name: "ApkVerityTestApp",
+ manifest: "AndroidManifest.xml",
+ srcs: ["src/**/*.java"],
+}
+
+android_test_helper_app {
+ name: "ApkVerityTestAppSplit",
+ manifest: "feature_split/AndroidManifest.xml",
+ srcs: ["src/**/*.java"],
+ aaptflags: [
+ "--custom-package com.android.apkverity.feature_x",
+ "--package-id 0x80",
+ ],
}
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml b/tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml
new file mode 100644
index 000000000000..0b3ff77c2cdf
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.apkverity">
+ <application>
+ <activity android:name=".DummyActivity"/>
+ </application>
+</manifest>
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml
new file mode 100644
index 000000000000..3f1a4f3a26a1
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.apkverity"
+ android:isFeatureSplit="true"
+ split="feature_x">
+ <application>
+ <activity android:name=".feature_x.DummyActivity"/>
+ </application>
+</manifest>
diff --git a/services/wifi/java/android/net/wifi/WifiApiServiceInfo.aidl b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
index 45e4c69102f0..0f694c293330 100644
--- a/services/wifi/java/android/net/wifi/WifiApiServiceInfo.aidl
+++ b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
@@ -14,10 +14,9 @@
* limitations under the License.
*/
-package android.net.wifi;
+package com.android.apkverity.feature_x;
-/** @hide */
-parcelable WifiApiServiceInfo {
- String name;
- IBinder binder;
-}
+import android.app.Activity;
+
+/** Dummy class just to generate some dex */
+public class DummyActivity extends Activity {}
diff --git a/services/net/java/android/net/NattKeepalivePacketDataParcelable.aidl b/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
index 6f006d4971fb..837c7be37504 100644
--- a/services/net/java/android/net/NattKeepalivePacketDataParcelable.aidl
+++ b/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
@@ -14,12 +14,9 @@
* limitations under the License.
*/
-package android.net;
+package com.android.apkverity;
-parcelable NattKeepalivePacketDataParcelable {
- byte[] srcAddress;
- int srcPort;
- byte[] dstAddress;
- int dstPort;
-}
+import android.app.Activity;
+/** Dummy class just to generate some dex */
+public class DummyActivity extends Activity {}
diff --git a/tests/ApkVerityTest/block_device_writer/Android.bp b/tests/ApkVerityTest/block_device_writer/Android.bp
new file mode 100644
index 000000000000..deed3a00d2fe
--- /dev/null
+++ b/tests/ApkVerityTest/block_device_writer/Android.bp
@@ -0,0 +1,30 @@
+// Copyright (C) 2019 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.
+
+// This is a cc_test just because it supports test_suites. This should be converted to something
+// like cc_binary_test_helper once supported.
+cc_test {
+ // Depending on how the test runs, the executable may be uploaded to different location.
+ // Before the bug in the file pusher is fixed, workaround by making the name unique.
+ // See b/124718249#comment12.
+ name: "block_device_writer_module",
+ stem: "block_device_writer",
+
+ srcs: ["block_device_writer.cpp"],
+ cflags: ["-Wall", "-Werror", "-Wextra", "-g"],
+ shared_libs: ["libbase", "libutils"],
+
+ test_suites: ["general-tests"],
+ gtest: false,
+}
diff --git a/tests/ApkVerityTest/block_device_writer/block_device_writer.cpp b/tests/ApkVerityTest/block_device_writer/block_device_writer.cpp
new file mode 100644
index 000000000000..b0c7251e77f5
--- /dev/null
+++ b/tests/ApkVerityTest/block_device_writer/block_device_writer.cpp
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/fiemap.h>
+#include <linux/fs.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/unique_fd.h>
+
+// This program modifies a file at given offset, but directly against the block
+// device, purposely to bypass the filesystem. Note that the change on block
+// device may not reflect the same way when read from filesystem, for example,
+// when the file is encrypted on disk.
+//
+// Only one byte is supported for now just so that we don't need to handle the
+// case when the range crosses different "extents".
+//
+// References:
+// https://www.kernel.org/doc/Documentation/filesystems/fiemap.txt
+// https://git.kernel.org/pub/scm/fs/xfs/xfsprogs-dev.git/tree/io/fiemap.c
+
+ssize_t get_logical_block_size(const char* block_device) {
+ android::base::unique_fd fd(open(block_device, O_RDONLY));
+ if (fd.get() < 0) {
+ fprintf(stderr, "open %s failed\n", block_device);
+ return -1;
+ }
+
+ int size;
+ if (ioctl(fd, BLKSSZGET, &size) < 0) {
+ fprintf(stderr, "ioctl(BLKSSZGET) failed: %s\n", strerror(errno));
+ return -1;
+ }
+ return size;
+}
+
+int64_t get_physical_offset(const char* file_name, uint64_t byte_offset) {
+ android::base::unique_fd fd(open(file_name, O_RDONLY));
+ if (fd.get() < 0) {
+ fprintf(stderr, "open %s failed\n", file_name);
+ return -1;
+ }
+
+ const int map_size = sizeof(struct fiemap) + sizeof(struct fiemap_extent);
+ char fiemap_buffer[map_size] = {0};
+ struct fiemap* fiemap = reinterpret_cast<struct fiemap*>(&fiemap_buffer);
+
+ fiemap->fm_flags = FIEMAP_FLAG_SYNC;
+ fiemap->fm_start = byte_offset;
+ fiemap->fm_length = 1;
+ fiemap->fm_extent_count = 1;
+
+ int ret = ioctl(fd.get(), FS_IOC_FIEMAP, fiemap);
+ if (ret < 0) {
+ fprintf(stderr, "ioctl(FS_IOC_FIEMAP) failed: %s\n", strerror(errno));
+ return -1;
+ }
+
+ if (fiemap->fm_mapped_extents != 1) {
+ fprintf(stderr, "fm_mapped_extents != 1 (is %d)\n",
+ fiemap->fm_mapped_extents);
+ return -1;
+ }
+
+ struct fiemap_extent* extent = &fiemap->fm_extents[0];
+ printf(
+ "logical offset: %llu, physical offset: %llu, length: %llu, "
+ "flags: %x\n",
+ extent->fe_logical, extent->fe_physical, extent->fe_length,
+ extent->fe_flags);
+ if (extent->fe_flags & (FIEMAP_EXTENT_UNKNOWN |
+ FIEMAP_EXTENT_UNWRITTEN)) {
+ fprintf(stderr, "Failed to locate physical offset safely\n");
+ return -1;
+ }
+
+ return extent->fe_physical + (byte_offset - extent->fe_logical);
+}
+
+int read_block_from_device(const char* device_path, uint64_t block_offset,
+ ssize_t block_size, char* block_buffer) {
+ assert(block_offset % block_size == 0);
+ android::base::unique_fd fd(open(device_path, O_RDONLY | O_DIRECT));
+ if (fd.get() < 0) {
+ fprintf(stderr, "open %s failed\n", device_path);
+ return -1;
+ }
+
+ ssize_t retval =
+ TEMP_FAILURE_RETRY(pread(fd, block_buffer, block_size, block_offset));
+ if (retval != block_size) {
+ fprintf(stderr, "read returns error or incomplete result (%zu): %s\n",
+ retval, strerror(errno));
+ return -1;
+ }
+ return 0;
+}
+
+int write_block_to_device(const char* device_path, uint64_t block_offset,
+ ssize_t block_size, char* block_buffer) {
+ assert(block_offset % block_size == 0);
+ android::base::unique_fd fd(open(device_path, O_WRONLY | O_DIRECT));
+ if (fd.get() < 0) {
+ fprintf(stderr, "open %s failed\n", device_path);
+ return -1;
+ }
+
+ ssize_t retval = TEMP_FAILURE_RETRY(
+ pwrite(fd.get(), block_buffer, block_size, block_offset));
+ if (retval != block_size) {
+ fprintf(stderr, "write returns error or incomplete result (%zu): %s\n",
+ retval, strerror(errno));
+ return -1;
+ }
+ return 0;
+}
+
+int main(int argc, const char** argv) {
+ if (argc != 4) {
+ fprintf(stderr,
+ "Usage: %s block_dev filename byte_offset\n"
+ "\n"
+ "This program bypasses filesystem and damages the specified byte\n"
+ "at the physical position on <block_dev> corresponding to the\n"
+ "logical byte location in <filename>.\n",
+ argv[0]);
+ return -1;
+ }
+
+ const char* block_device = argv[1];
+ const char* file_name = argv[2];
+ uint64_t byte_offset = strtoull(argv[3], nullptr, 10);
+
+ ssize_t block_size = get_logical_block_size(block_device);
+ if (block_size < 0) {
+ return -1;
+ }
+
+ int64_t physical_offset_signed = get_physical_offset(file_name, byte_offset);
+ if (physical_offset_signed < 0) {
+ return -1;
+ }
+
+ uint64_t physical_offset = static_cast<uint64_t>(physical_offset_signed);
+ uint64_t offset_within_block = physical_offset % block_size;
+ uint64_t physical_block_offset = physical_offset - offset_within_block;
+
+ // Direct I/O requires aligned buffer
+ std::unique_ptr<char> buf(static_cast<char*>(
+ aligned_alloc(block_size /* alignment */, block_size /* size */)));
+
+ if (read_block_from_device(block_device, physical_block_offset, block_size,
+ buf.get()) < 0) {
+ return -1;
+ }
+ char* p = buf.get() + offset_within_block;
+ printf("before: %hhx\n", *p);
+ *p ^= 0xff;
+ printf("after: %hhx\n", *p);
+ if (write_block_to_device(block_device, physical_block_offset, block_size,
+ buf.get()) < 0) {
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java b/tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java
new file mode 100644
index 000000000000..761c5ceb2413
--- /dev/null
+++ b/tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java
@@ -0,0 +1,496 @@
+/*
+ * Copyright (C) 2019 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 com.android.apkverity;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.platform.test.annotations.RootPermissionTest;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.FileNotFoundException;
+import java.util.Arrays;
+import java.util.HashSet;
+
+/**
+ * This test makes sure app installs with fs-verity signature, and on-access verification works.
+ *
+ * <p>When an app is installed, all or none of the files should have their corresponding .fsv_sig
+ * signature file. Otherwise, install will fail.
+ *
+ * <p>Once installed, file protected by fs-verity is verified by kernel every time a block is loaded
+ * from disk to memory. The file is immutable by design, enforced by filesystem.
+ *
+ * <p>In order to make sure a block of the file is readable only if the underlying block on disk
+ * stay intact, the test needs to bypass the filesystem and tampers with the corresponding physical
+ * address against the block device.
+ *
+ * <p>Requirements to run this test:
+ * <ul>
+ * <li>Device is rootable</li>
+ * <li>The filesystem supports fs-verity</li>
+ * <li>The feature flag is enabled</li>
+ * </ul>
+ */
+@RootPermissionTest
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class ApkVerityTest extends BaseHostJUnit4Test {
+ private static final String TARGET_PACKAGE = "com.android.apkverity";
+
+ private static final String BASE_APK = "ApkVerityTestApp.apk";
+ private static final String BASE_APK_DM = "ApkVerityTestApp.dm";
+ private static final String SPLIT_APK = "ApkVerityTestAppSplit.apk";
+ private static final String SPLIT_APK_DM = "ApkVerityTestAppSplit.dm";
+
+ private static final String INSTALLED_BASE_APK = "base.apk";
+ private static final String INSTALLED_BASE_DM = "base.dm";
+ private static final String INSTALLED_SPLIT_APK = "split_feature_x.apk";
+ private static final String INSTALLED_SPLIT_DM = "split_feature_x.dm";
+ private static final String INSTALLED_BASE_APK_FSV_SIG = "base.apk.fsv_sig";
+ private static final String INSTALLED_BASE_DM_FSV_SIG = "base.dm.fsv_sig";
+ private static final String INSTALLED_SPLIT_APK_FSV_SIG = "split_feature_x.apk.fsv_sig";
+ private static final String INSTALLED_SPLIT_DM_FSV_SIG = "split_feature_x.dm.fsv_sig";
+
+ private static final String DAMAGING_EXECUTABLE = "/data/local/tmp/block_device_writer";
+ private static final String CERT_PATH = "/data/local/tmp/ApkVerityTestCert.der";
+
+ private static final String APK_VERITY_STANDARD_MODE = "2";
+
+ /** Only 4K page is supported by fs-verity currently. */
+ private static final int FSVERITY_PAGE_SIZE = 4096;
+
+ private ITestDevice mDevice;
+ private String mKeyId;
+
+ @Before
+ public void setUp() throws DeviceNotAvailableException {
+ mDevice = getDevice();
+
+ String apkVerityMode = mDevice.getProperty("ro.apk_verity.mode");
+ assumeTrue(APK_VERITY_STANDARD_MODE.equals(apkVerityMode));
+
+ mKeyId = expectRemoteCommandToSucceed(
+ "mini-keyctl padd asymmetric fsv_test .fs-verity < " + CERT_PATH).trim();
+ if (!mKeyId.matches("^\\d+$")) {
+ String keyId = mKeyId;
+ mKeyId = null;
+ fail("Key ID is not decimal: " + keyId);
+ }
+
+ uninstallPackage(TARGET_PACKAGE);
+ }
+
+ @After
+ public void tearDown() throws DeviceNotAvailableException {
+ uninstallPackage(TARGET_PACKAGE);
+
+ if (mKeyId != null) {
+ expectRemoteCommandToSucceed("mini-keyctl unlink " + mKeyId + " .fs-verity");
+ }
+ }
+
+ @Test
+ public void testFsverityKernelSupports() throws DeviceNotAvailableException {
+ ITestDevice.MountPointInfo mountPoint = mDevice.getMountPointInfo("/data");
+ expectRemoteCommandToSucceed("test -f /sys/fs/" + mountPoint.type + "/features/verity");
+ }
+
+ @Test
+ public void testInstallBase() throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG);
+ verifyInstalledFilesHaveFsverity();
+ }
+
+ @Test
+ public void testInstallBaseWithWrongSignature()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFile(BASE_APK)
+ .addFile(SPLIT_APK_DM + ".fsv_sig",
+ BASE_APK + ".fsv_sig")
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testInstallBaseWithSplit()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .addFileAndSignature(SPLIT_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG,
+ INSTALLED_SPLIT_APK,
+ INSTALLED_SPLIT_APK_FSV_SIG);
+ verifyInstalledFilesHaveFsverity();
+ }
+
+ @Test
+ public void testInstallBaseWithDm() throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .addFileAndSignature(BASE_APK_DM)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG,
+ INSTALLED_BASE_DM,
+ INSTALLED_BASE_DM_FSV_SIG);
+ verifyInstalledFilesHaveFsverity();
+ }
+
+ @Test
+ public void testInstallEverything() throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .addFileAndSignature(BASE_APK_DM)
+ .addFileAndSignature(SPLIT_APK)
+ .addFileAndSignature(SPLIT_APK_DM)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG,
+ INSTALLED_BASE_DM,
+ INSTALLED_BASE_DM_FSV_SIG,
+ INSTALLED_SPLIT_APK,
+ INSTALLED_SPLIT_APK_FSV_SIG,
+ INSTALLED_SPLIT_DM,
+ INSTALLED_SPLIT_DM_FSV_SIG);
+ verifyInstalledFilesHaveFsverity();
+ }
+
+ @Test
+ public void testInstallSplitOnly()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG);
+
+ new InstallMultiple()
+ .inheritFrom(TARGET_PACKAGE)
+ .addFileAndSignature(SPLIT_APK)
+ .run();
+
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG,
+ INSTALLED_SPLIT_APK,
+ INSTALLED_SPLIT_APK_FSV_SIG);
+ verifyInstalledFilesHaveFsverity();
+ }
+
+ @Test
+ public void testInstallSplitOnlyMissingSignature()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG);
+
+ new InstallMultiple()
+ .inheritFrom(TARGET_PACKAGE)
+ .addFile(SPLIT_APK)
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testInstallSplitOnlyWithoutBaseSignature()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFile(BASE_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+ verifyInstalledFiles(INSTALLED_BASE_APK);
+
+ new InstallMultiple()
+ .inheritFrom(TARGET_PACKAGE)
+ .addFileAndSignature(SPLIT_APK)
+ .run();
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_SPLIT_APK,
+ INSTALLED_SPLIT_APK_FSV_SIG);
+
+ }
+
+ @Test
+ public void testInstallOnlyBaseHasFsvSig()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .addFile(BASE_APK_DM)
+ .addFile(SPLIT_APK)
+ .addFile(SPLIT_APK_DM)
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testInstallOnlyDmHasFsvSig()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFile(BASE_APK)
+ .addFileAndSignature(BASE_APK_DM)
+ .addFile(SPLIT_APK)
+ .addFile(SPLIT_APK_DM)
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testInstallOnlySplitHasFsvSig()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFile(BASE_APK)
+ .addFile(BASE_APK_DM)
+ .addFileAndSignature(SPLIT_APK)
+ .addFile(SPLIT_APK_DM)
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testInstallBaseWithFsvSigThenSplitWithout()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFileAndSignature(BASE_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+ verifyInstalledFiles(
+ INSTALLED_BASE_APK,
+ INSTALLED_BASE_APK_FSV_SIG);
+
+ new InstallMultiple()
+ .addFile(SPLIT_APK)
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testInstallBaseWithoutFsvSigThenSplitWith()
+ throws DeviceNotAvailableException, FileNotFoundException {
+ new InstallMultiple()
+ .addFile(BASE_APK)
+ .run();
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+ verifyInstalledFiles(INSTALLED_BASE_APK);
+
+ new InstallMultiple()
+ .addFileAndSignature(SPLIT_APK)
+ .runExpectingFailure();
+ }
+
+ @Test
+ public void testFsverityFileIsImmutableAndReadable() throws DeviceNotAvailableException {
+ new InstallMultiple().addFileAndSignature(BASE_APK).run();
+ String apkPath = getApkPath(TARGET_PACKAGE);
+
+ assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+ expectRemoteCommandToFail("echo -n '' >> " + apkPath);
+ expectRemoteCommandToSucceed("cat " + apkPath + " > /dev/null");
+ }
+
+ @Test
+ public void testFsverityFailToReadModifiedBlockAtFront() throws DeviceNotAvailableException {
+ new InstallMultiple().addFileAndSignature(BASE_APK).run();
+ String apkPath = getApkPath(TARGET_PACKAGE);
+
+ long apkSize = getFileSizeInBytes(apkPath);
+ long offsetFirstByte = 0;
+
+ // The first two pages should be both readable at first.
+ assertTrue(canReadByte(apkPath, offsetFirstByte));
+ if (apkSize > offsetFirstByte + FSVERITY_PAGE_SIZE) {
+ assertTrue(canReadByte(apkPath, offsetFirstByte + FSVERITY_PAGE_SIZE));
+ }
+
+ // Damage the file directly against the block device.
+ damageFileAgainstBlockDevice(apkPath, offsetFirstByte);
+
+ // Expect actual read from disk to fail but only at damaged page.
+ dropCaches();
+ assertFalse(canReadByte(apkPath, offsetFirstByte));
+ if (apkSize > offsetFirstByte + FSVERITY_PAGE_SIZE) {
+ long lastByteOfTheSamePage =
+ offsetFirstByte % FSVERITY_PAGE_SIZE + FSVERITY_PAGE_SIZE - 1;
+ assertFalse(canReadByte(apkPath, lastByteOfTheSamePage));
+ assertTrue(canReadByte(apkPath, lastByteOfTheSamePage + 1));
+ }
+ }
+
+ @Test
+ public void testFsverityFailToReadModifiedBlockAtBack() throws DeviceNotAvailableException {
+ new InstallMultiple().addFileAndSignature(BASE_APK).run();
+ String apkPath = getApkPath(TARGET_PACKAGE);
+
+ long apkSize = getFileSizeInBytes(apkPath);
+ long offsetOfLastByte = apkSize - 1;
+
+ // The first two pages should be both readable at first.
+ assertTrue(canReadByte(apkPath, offsetOfLastByte));
+ if (offsetOfLastByte - FSVERITY_PAGE_SIZE > 0) {
+ assertTrue(canReadByte(apkPath, offsetOfLastByte - FSVERITY_PAGE_SIZE));
+ }
+
+ // Damage the file directly against the block device.
+ damageFileAgainstBlockDevice(apkPath, offsetOfLastByte);
+
+ // Expect actual read from disk to fail but only at damaged page.
+ dropCaches();
+ assertFalse(canReadByte(apkPath, offsetOfLastByte));
+ if (offsetOfLastByte - FSVERITY_PAGE_SIZE > 0) {
+ long firstByteOfTheSamePage = offsetOfLastByte - offsetOfLastByte % FSVERITY_PAGE_SIZE;
+ assertFalse(canReadByte(apkPath, firstByteOfTheSamePage));
+ assertTrue(canReadByte(apkPath, firstByteOfTheSamePage - 1));
+ }
+ }
+
+ private void verifyInstalledFilesHaveFsverity() throws DeviceNotAvailableException {
+ // Verify that all files are protected by fs-verity
+ String apkPath = getApkPath(TARGET_PACKAGE);
+ String appDir = apkPath.substring(0, apkPath.lastIndexOf("/"));
+ long kTargetOffset = 0;
+ for (String basename : expectRemoteCommandToSucceed("ls " + appDir).split("\n")) {
+ if (basename.endsWith(".apk") || basename.endsWith(".dm")) {
+ String path = appDir + "/" + basename;
+ damageFileAgainstBlockDevice(path, kTargetOffset);
+
+ // Retry is sometimes needed to pass the test. Package manager may have FD leaks
+ // (see b/122744005 as example) that prevents the file in question to be evicted
+ // from filesystem cache. Forcing GC workarounds the problem.
+ int retry = 5;
+ for (; retry > 0; retry--) {
+ dropCaches();
+ if (!canReadByte(path, kTargetOffset)) {
+ break;
+ }
+ try {
+ Thread.sleep(1000);
+ String pid = expectRemoteCommandToSucceed("pidof system_server");
+ mDevice.executeShellV2Command("kill -10 " + pid); // force GC
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ }
+ assertTrue("Read from " + path + " should fail", retry > 0);
+ }
+ }
+ }
+
+ private void verifyInstalledFiles(String... filenames) throws DeviceNotAvailableException {
+ String apkPath = getApkPath(TARGET_PACKAGE);
+ String appDir = apkPath.substring(0, apkPath.lastIndexOf("/"));
+ HashSet<String> actualFiles = new HashSet<>(Arrays.asList(
+ expectRemoteCommandToSucceed("ls " + appDir).split("\n")));
+ assertTrue(actualFiles.remove("lib"));
+ assertTrue(actualFiles.remove("oat"));
+
+ HashSet<String> expectedFiles = new HashSet<>(Arrays.asList(filenames));
+ assertEquals(expectedFiles, actualFiles);
+ }
+
+ private void damageFileAgainstBlockDevice(String path, long offsetOfTargetingByte)
+ throws DeviceNotAvailableException {
+ assertTrue(path.startsWith("/data/"));
+ ITestDevice.MountPointInfo mountPoint = mDevice.getMountPointInfo("/data");
+ expectRemoteCommandToSucceed(String.join(" ", DAMAGING_EXECUTABLE,
+ mountPoint.filesystem, path, Long.toString(offsetOfTargetingByte)));
+ }
+
+ private String getApkPath(String packageName) throws DeviceNotAvailableException {
+ String line = expectRemoteCommandToSucceed("pm path " + packageName + " | grep base.apk");
+ int index = line.trim().indexOf(":");
+ assertTrue(index >= 0);
+ return line.substring(index + 1);
+ }
+
+ private long getFileSizeInBytes(String packageName) throws DeviceNotAvailableException {
+ return Long.parseLong(expectRemoteCommandToSucceed("stat -c '%s' " + packageName).trim());
+ }
+
+ private void dropCaches() throws DeviceNotAvailableException {
+ expectRemoteCommandToSucceed("sync && echo 1 > /proc/sys/vm/drop_caches");
+ }
+
+ private boolean canReadByte(String filePath, long offset) throws DeviceNotAvailableException {
+ CommandResult result = mDevice.executeShellV2Command(
+ "dd if=" + filePath + " bs=1 count=1 skip=" + Long.toString(offset));
+ return result.getStatus() == CommandStatus.SUCCESS;
+ }
+
+ private String expectRemoteCommandToSucceed(String cmd) throws DeviceNotAvailableException {
+ CommandResult result = mDevice.executeShellV2Command(cmd);
+ assertEquals("`" + cmd + "` failed: " + result.getStderr(), CommandStatus.SUCCESS,
+ result.getStatus());
+ return result.getStdout();
+ }
+
+ private void expectRemoteCommandToFail(String cmd) throws DeviceNotAvailableException {
+ CommandResult result = mDevice.executeShellV2Command(cmd);
+ assertTrue("Unexpected success from `" + cmd + "`: " + result.getStderr(),
+ result.getStatus() != CommandStatus.SUCCESS);
+ }
+
+ private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+ InstallMultiple() {
+ super(getDevice(), getBuild());
+ }
+
+ InstallMultiple addFileAndSignature(String filename) {
+ try {
+ addFile(filename);
+ addFile(filename + ".fsv_sig");
+ } catch (FileNotFoundException e) {
+ fail("Missing test file: " + e);
+ }
+ return this;
+ }
+ }
+}
diff --git a/tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java b/tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java
new file mode 100644
index 000000000000..02e73d157dde
--- /dev/null
+++ b/tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2019 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 com.android.apkverity;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Base class for invoking the install-multiple command via ADB. Subclass this for less typing:
+ *
+ * <code> private class InstallMultiple extends BaseInstallMultiple&lt;InstallMultiple&gt; { public
+ * InstallMultiple() { super(getDevice(), null); } } </code>
+ */
+/*package*/ class BaseInstallMultiple<T extends BaseInstallMultiple<?>> {
+
+ private final ITestDevice mDevice;
+ private final IBuildInfo mBuild;
+
+ private final List<String> mArgs = new ArrayList<>();
+ private final Map<File, String> mFileToRemoteMap = new HashMap<>();
+
+ /*package*/ BaseInstallMultiple(ITestDevice device, IBuildInfo buildInfo) {
+ mDevice = device;
+ mBuild = buildInfo;
+ addArg("-g");
+ }
+
+ T addArg(String arg) {
+ mArgs.add(arg);
+ return (T) this;
+ }
+
+ T addFile(String filename) throws FileNotFoundException {
+ return addFile(filename, filename);
+ }
+
+ T addFile(String filename, String remoteName) throws FileNotFoundException {
+ CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
+ mFileToRemoteMap.put(buildHelper.getTestFile(filename), remoteName);
+ return (T) this;
+ }
+
+ T inheritFrom(String packageName) {
+ addArg("-r");
+ addArg("-p " + packageName);
+ return (T) this;
+ }
+
+ void run() throws DeviceNotAvailableException {
+ run(true);
+ }
+
+ void runExpectingFailure() throws DeviceNotAvailableException {
+ run(false);
+ }
+
+ private void run(boolean expectingSuccess) throws DeviceNotAvailableException {
+ final ITestDevice device = mDevice;
+
+ // Create an install session
+ final StringBuilder cmd = new StringBuilder();
+ cmd.append("pm install-create");
+ for (String arg : mArgs) {
+ cmd.append(' ').append(arg);
+ }
+
+ String result = device.executeShellCommand(cmd.toString());
+ TestCase.assertTrue(result, result.startsWith("Success"));
+
+ final int start = result.lastIndexOf("[");
+ final int end = result.lastIndexOf("]");
+ int sessionId = -1;
+ try {
+ if (start != -1 && end != -1 && start < end) {
+ sessionId = Integer.parseInt(result.substring(start + 1, end));
+ }
+ } catch (NumberFormatException e) {
+ throw new IllegalStateException("Failed to parse install session: " + result);
+ }
+ if (sessionId == -1) {
+ throw new IllegalStateException("Failed to create install session: " + result);
+ }
+
+ // Push our files into session. Ideally we'd use stdin streaming,
+ // but ddmlib doesn't support it yet.
+ for (final Map.Entry<File, String> entry : mFileToRemoteMap.entrySet()) {
+ final File file = entry.getKey();
+ final String remoteName = entry.getValue();
+ final String remotePath = "/data/local/tmp/" + file.getName();
+ if (!device.pushFile(file, remotePath)) {
+ throw new IllegalStateException("Failed to push " + file);
+ }
+
+ cmd.setLength(0);
+ cmd.append("pm install-write");
+ cmd.append(' ').append(sessionId);
+ cmd.append(' ').append(remoteName);
+ cmd.append(' ').append(remotePath);
+
+ result = device.executeShellCommand(cmd.toString());
+ TestCase.assertTrue(result, result.startsWith("Success"));
+ }
+
+ // Everything staged; let's pull trigger
+ cmd.setLength(0);
+ cmd.append("pm install-commit");
+ cmd.append(' ').append(sessionId);
+
+ result = device.executeShellCommand(cmd.toString());
+ if (expectingSuccess) {
+ TestCase.assertTrue(result, result.contains("Success"));
+ } else {
+ TestCase.assertFalse(result, result.contains("Success"));
+ }
+ }
+}
diff --git a/tests/ApkVerityTest/testdata/Android.bp b/tests/ApkVerityTest/testdata/Android.bp
new file mode 100644
index 000000000000..c10b0cef21d7
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/Android.bp
@@ -0,0 +1,77 @@
+// Copyright (C) 2019 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.
+
+filegroup {
+ name: "ApkVerityTestKeyPem",
+ srcs: ["ApkVerityTestKey.pem"],
+}
+
+filegroup {
+ name: "ApkVerityTestCertPem",
+ srcs: ["ApkVerityTestCert.pem"],
+}
+
+filegroup {
+ name: "ApkVerityTestCertDer",
+ srcs: ["ApkVerityTestCert.der"],
+}
+
+filegroup {
+ name: "ApkVerityTestAppDm",
+ srcs: ["ApkVerityTestApp.dm"],
+}
+
+filegroup {
+ name: "ApkVerityTestAppSplitDm",
+ srcs: ["ApkVerityTestAppSplit.dm"],
+}
+
+genrule_defaults {
+ name: "apk_verity_sig_gen_default",
+ tools: ["fsverity"],
+ tool_files: [":ApkVerityTestKeyPem", ":ApkVerityTestCertPem"],
+ cmd: "$(location fsverity) sign $(in) $(out) " +
+ "--key=$(location :ApkVerityTestKeyPem) " +
+ "--cert=$(location :ApkVerityTestCertPem) " +
+ "> /dev/null",
+}
+
+genrule {
+ name: "ApkVerityTestAppFsvSig",
+ defaults: ["apk_verity_sig_gen_default"],
+ srcs: [":ApkVerityTestApp"],
+ out: ["ApkVerityTestApp.apk.fsv_sig"],
+}
+
+genrule {
+ name: "ApkVerityTestAppDmFsvSig",
+ defaults: ["apk_verity_sig_gen_default"],
+ srcs: [":ApkVerityTestAppDm"],
+ out: ["ApkVerityTestApp.dm.fsv_sig"],
+}
+
+genrule {
+ name: "ApkVerityTestAppSplitFsvSig",
+ defaults: ["apk_verity_sig_gen_default"],
+ srcs: [":ApkVerityTestAppSplit"],
+ out: ["ApkVerityTestAppSplit.apk.fsv_sig"],
+}
+
+genrule {
+ name: "ApkVerityTestAppSplitDmFsvSig",
+ defaults: ["apk_verity_sig_gen_default"],
+ srcs: [":ApkVerityTestAppSplitDm"],
+ out: ["ApkVerityTestAppSplit.dm.fsv_sig"],
+}
+
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestApp.dm b/tests/ApkVerityTest/testdata/ApkVerityTestApp.dm
new file mode 100644
index 000000000000..e53a86131366
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestApp.dm
Binary files differ
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dm b/tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dm
new file mode 100644
index 000000000000..75396f1ba730
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dm
Binary files differ
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestCert.der b/tests/ApkVerityTest/testdata/ApkVerityTestCert.der
new file mode 100644
index 000000000000..fe9029b53aa1
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestCert.der
Binary files differ
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestCert.pem b/tests/ApkVerityTest/testdata/ApkVerityTestCert.pem
new file mode 100644
index 000000000000..6c0b7b1f635a
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestCert.pem
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFLjCCAxagAwIBAgIJAKZbtMlZZwtdMA0GCSqGSIb3DQEBCwUAMCwxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIDAJDQTEQMA4GA1UECgwHQW5kcm9pZDAeFw0xODEyMTky
+MTA5MzVaFw0xOTAxMTgyMTA5MzVaMCwxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJD
+QTEQMA4GA1UECgwHQW5kcm9pZDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC
+ggIBAKnrw4WiFgFBq6vXqcLc97iwvcYPZmeIjQqYRF+CHwXBXx8IyDlMfPrgyIYo
+ZLkosnUK/Exuypdu6UEtdqtYPknC6w9z4YkxqsKtyxyB1b13ptcTHh3bf2N8bqGr
+8gWWLxj0QjumCtFi7Z/TCwB5t3b3gtC+0jVfABSWrm5PNkgk7jIP+4KeYLDCDfiJ
+XH3uHu6OASiSHTOnrmLWSaSw0y6G4OFthHqQnMywasly0r6m+Mif+K0ZUV7hBRi/
+SfqcJ1HTCXTJMskEyV6Qx2sHF/VbK2gdUv56z6OVRNSs/FxPBiWVMuZZKh1FpBVI
+gbGxusf2Awwtc+Soxr4/P1YFcrwfA/ff9FK3Yg/Cd3ZMGbzUkbEMEkE5BW7Gbjmx
+wz3mYTiRfa2L/Bl4MiMqNi0tfORLkmg+V/EItzfhZ/HsXMOCBsnuj4KnFslmbamz
+t9opypj2JLGk+lXhZ5gFNFw8tYH1AnG1AIXe5u+6Fq2nQ1y/ncGUTR5Sw4de/Gee
+C0UgR+KiFEdKupMKbXgSKl+0QPz/i2eSpcDOKMwZ4WiNrkbccbCyr38so+j5DfWF
+IeZA9a/IlysA6G8yU2TfXBc65VCIEQRJOQdUOZFDO8OSoqGP+fbA6edpmovGw+TH
+sM/NkmpEXpQm7BVOI4oVjdf4pKPp0zaW2YcaA3xU2w6eF17pAgMBAAGjUzBRMB0G
+A1UdDgQWBBRGpHYy7yiLEYalGuF1va6zJKGD/zAfBgNVHSMEGDAWgBRGpHYy7yiL
+EYalGuF1va6zJKGD/zAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IC
+AQAao6ZBM122F0pYb2QLahIyyGEr3LfSdBGID4068pVik4ncIefFz36Xf9AFxRQd
+KHmwRYNPHiLRIEGdtqplC5pZDeHz41txIArNIZKzDWOYtdcFyCz8umuj912BmsoM
+YUQhT6F1sX53SWcKxEP/aJ2kltSlPFX99e3Vx9eRkceV1oe2NM6ZG8hnYCfCAMeJ
+jRTpbqCGaAsEHFtIx6wt3zEtUXIVg4aYFQs/qjTjeP8ByIj0b4lZrceEoTeRimuj
++4aAI+jBxLkwaN3hseQHzRNpgPehIVV/0RU92yzOD/WN4YwE6rwjKEI1lihHNBDa
++DwGtGbHmIUzjW1qArig+mzUIhfYIJAxrx20ynPz/Q+C7+iXhTDAYQlxTle0pX8m
+yM2DUdPo97eLOzQ4JDHxtcN3ntTEJKKvrmzKvWuxy/yoLwS7MtLH6RETTHabH3Qd
+CP83X7z8zTyxgPxHdfHo9sgR/4C9RHGJx4OpBTQaiqfjSpDqJSIQdbrHGOQDgYwL
+KQyiQuhukmNgRCB6dJoZJ/MyaNuMsXV9QobsDHW1oSuCvPAihVoWHJxt8m4Ma0jJ
+EIbEPT2Umw1F/P+CeXnVQwhPvzQKHCa+6cC/YdjTqIKLmQV8X3HUBUIMhP2JGDic
+MnUipTm/RwWZVOjCJaFqk5sVq3L0Lyd0XVUWSK1a4IcrsA==
+-----END CERTIFICATE-----
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestKey.pem b/tests/ApkVerityTest/testdata/ApkVerityTestKey.pem
new file mode 100644
index 000000000000..f0746c162421
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestKey.pem
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCp68OFohYBQaur
+16nC3Pe4sL3GD2ZniI0KmERfgh8FwV8fCMg5THz64MiGKGS5KLJ1CvxMbsqXbulB
+LXarWD5JwusPc+GJMarCrcscgdW9d6bXEx4d239jfG6hq/IFli8Y9EI7pgrRYu2f
+0wsAebd294LQvtI1XwAUlq5uTzZIJO4yD/uCnmCwwg34iVx97h7ujgEokh0zp65i
+1kmksNMuhuDhbYR6kJzMsGrJctK+pvjIn/itGVFe4QUYv0n6nCdR0wl0yTLJBMle
+kMdrBxf1WytoHVL+es+jlUTUrPxcTwYllTLmWSodRaQVSIGxsbrH9gMMLXPkqMa+
+Pz9WBXK8HwP33/RSt2IPwnd2TBm81JGxDBJBOQVuxm45scM95mE4kX2ti/wZeDIj
+KjYtLXzkS5JoPlfxCLc34Wfx7FzDggbJ7o+CpxbJZm2ps7faKcqY9iSxpPpV4WeY
+BTRcPLWB9QJxtQCF3ubvuhatp0Ncv53BlE0eUsOHXvxnngtFIEfiohRHSrqTCm14
+EipftED8/4tnkqXAzijMGeFoja5G3HGwsq9/LKPo+Q31hSHmQPWvyJcrAOhvMlNk
+31wXOuVQiBEESTkHVDmRQzvDkqKhj/n2wOnnaZqLxsPkx7DPzZJqRF6UJuwVTiOK
+FY3X+KSj6dM2ltmHGgN8VNsOnhde6QIDAQABAoICAGT21tWnisWyXKwd2BwWKgeO
+1SRDcEiihZO/CBlr+rzzum55TGdngHedauj0RW0Ttn3/SgysZCp415ZHylRjeZdg
+f0VOSLu5TEqi86X7q6IJ35O6I1IAY4AcpqvfvE3/f/qm4FgLADCMRL+LqeTdbdr9
+lLguOj9GNIkHQ5v96zYQ44vRnVNugetlUuHT1KZq/+wlaqDNuRZBU0gdJeL6wnDJ
+6gNojKg7F0A0ry8F0B1Cn16uVxebjJMAx4N93hpQALkI2XyQNGHnOzO6eROqQl0i
+j/csPW1CUfBUOHLaWpUKy483SOhAINsFz0pqK84G2gIItqTcuRksA/N1J1AYqqQO
++/8IK5Mb9j0RaYYrBG83luGCWYauAsWg2Yol6fUGju8IY/zavOaES42XogY588Ad
+JzW+njjxXcnoD/u5keWrGwbPdGfoaLLg4eMlRBT4yNicyT04knXjFG4QTfLY5lF/
+VKdvZk6RMoCLdAtgN6EKHtcwuoYR967otsbavshngZ9HE/ic5/TdNFCBjxs6q9bm
+docC4CLHU/feXvOCYSnIfUpDzEPV96Gbk6o0qeYn3RUSGzRpXQHxXXfszEESUWnd
+2rtfXxqA7C5n8CshBfKJND7/LKRGpBRaYWJtc4hFmo8prhXfOb40PEZNlx8mcsEz
+WYZpmvFQHU8+bZIm0a5RAoIBAQDaCAje9xLKN1CYzygA/U3x2CsGuWWyh9xM1oR5
+5t+nn0EeIMrzGuHrD4hdbZiTiJcO5dpSg/3dssc/QLJEdv+BoMEgSYTf3TX03dIb
+kSlj+ONobejO4nVoUP0axTvVe/nuMYvLguTM6OCFvgV752TFxVyVHl6RM+rQYGCl
+ajbBCsCRg4QgpZ/RHWf+3KMJunzwWBlsAXcjOudneYqEl713h/q1lc5cONIglQDU
+E+bc5q6q++c/H8dYaWq4QE4CQU8wsq77/bZk8z1jheOV0HkwaH5ShtKD7bk/4MA9
+jWQUDW6/LRXkNiPExsAZxnP3mxhtUToWq1nedF6kPmNBko+9AoIBAQDHgvAql6i7
+osTYUcY/GldPmnrvfqbKmD0nI8mnaJfN2vGwjB/ol3lm+pviKIQ4ER80xsdn4xK0
+2cC9OdkY2UX7zilKohxvKVsbVOYpUwfpoRQO1Euddb6iAMqgGDyDzRBDTzTx5pB5
+XL9B/XuJVCMkjsNdD9iEbjdY1Epv7kYf53zfvrXdqv24uSNAszPFBLLPHSC9yONE
+a/t3mHGZ2cjr52leGNGY7ib6GNGBUeA34SM9g97tU9pAgy712RfZhH6fA93CLk6T
+DKoch56YId71vZt2J0Lrk4TWnnpidSoRmzKfVIJwjCmgYbI+2eDp7h0Z0DnDbji6
+9BPt3RWsoZidAoIBAA2A7+O3U7+Ye3JraiPdjGVNKSUKeIT9KyTLKHtQVEvSbjsK
+dudlo9ZmKOD4d7mzfP+cNtBjgmanuvVs8V2SLTL/HNb+Fq+yyLO4xVmVvQWHFbaT
+EBc4KWNjmLl+u7z2J72b7feVzMvwJG/EHBzXcQNavOgzcFH38DQls/aqxGdiXhjl
+F1raRzKxao57ZdGlbjWIj1KEKLfS3yAmg/DAYSi1EE8MzzIhBsqjz+BStzq5Qtou
+Ld1X/4W3SbfNq8cx+lCe0H2k8hYAhq3STg0qU0cvQZuk5Abtw0p0hhOJ3UfsqQ5I
+IZH31HFMiftOskIEphenLzzWMgO4G2B6yLT3+dUCggEAOLF1i7Ti5sbfBtVd70qN
+6vnr2yhzPvi5z+h0ghTPpliD+3YmDxMUFXY7W63FvKTo6DdgLJ4zD58dDOhmT5BW
+ObKguyuLxu7Ki965NJ76jaIPMBOVlR4DWMe+zHV2pMFd0LKuSdsJzOLVGmxscV6u
+SdIjo8s/7InhQmW47UuZM7G1I2NvDJltVdOON/F0UZT/NqmBR0zRf/zrTVXNWjmv
+xZFRuMJ2tO1fuAvbZNMeUuKv/+f8LhZ424IrkwLoqw/iZ09S8b306AZeRJMpNvPR
+BqWlipKnioe15MLN5jKDDNO8M9hw5Ih/v6pjW0bQicj3DgHEmEs25bE8BIihgxe8
+ZQKCAQEAsWKsUv13OEbYYAoJgbzDesWF9NzamFB0NLyno9SChvFPH/d8RmAuti7Y
+BQUoBswLK24DF/TKf1YocsZq8tu+pnv0Nx1wtK4K+J3A1BYDm7ElpO3Km+HPUBtf
+C9KGT5hotlMQVTpYSDG/QeWbfl4UnNZcbg8pmv38NwV1eDoVDfaVrRYJzQn75+Tf
+s/WUq1x5PElR/4pNIU2i6pJGd6FimhRweJu/INR36spWmbMRNX8fyXx+9EBqMbVp
+vS2xGgxxQT6bAvBfRlpgi87T9v5Gqoy6/jM/wX9smH9PfUV1vK32n3Zrbd46gwZW
+p2aUlQOLXU9SjQTirZbdCZP0XHtFsg==
+-----END PRIVATE KEY-----
diff --git a/tests/ApkVerityTest/testdata/README.md b/tests/ApkVerityTest/testdata/README.md
new file mode 100644
index 000000000000..163cb183a5ad
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/README.md
@@ -0,0 +1,13 @@
+This test only runs on rooted / debuggable device.
+
+The test tries to install subsets of base.{apk,dm}, split.{apk,dm} and their
+corresponding .fsv_sig files (generated by build rule). If installed, the
+tests also tries to tamper with the file at absolute disk offset to verify
+if fs-verity is effective.
+
+How to generate dex metadata (.dm)
+==================================
+
+ adb shell profman --generate-test-profile=/data/local/tmp/primary.prof
+ adb pull /data/local/tmp/primary.prof
+ zip foo.dm primary.prof
diff --git a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
index 17986a3c9d61..730b210f1529 100644
--- a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
+++ b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
@@ -66,10 +66,18 @@ public class BootImageProfileTest implements IDeviceTest {
String res;
res = mTestDevice.executeShellCommand("truncate -s 0 " + SYSTEM_SERVER_PROFILE).trim();
assertTrue(res, res.length() == 0);
- // Force save profiles in case the system just started.
+ // Wait up to 20 seconds for the profile to be saved.
+ for (int i = 0; i < 20; ++i) {
+ // Force save the profile since we truncated it.
+ forceSaveProfile("system_server");
+ String s = mTestDevice.executeShellCommand("wc -c <" + SYSTEM_SERVER_PROFILE).trim();
+ if (!"0".equals(s)) {
+ break;
+ }
+ Thread.sleep(1000);
+ }
+ // In case the profile is partially saved, wait an extra second.
Thread.sleep(1000);
- forceSaveProfile("system_server");
- Thread.sleep(2000);
// Validate that the profile is non empty.
res = mTestDevice.executeShellCommand("profman --dump-only --profile-file="
+ SYSTEM_SERVER_PROFILE);
diff --git a/tests/FlickerTests/AndroidManifest.xml b/tests/FlickerTests/AndroidManifest.xml
index 5b1a36b84cc4..9b73abfd6908 100644
--- a/tests/FlickerTests/AndroidManifest.xml
+++ b/tests/FlickerTests/AndroidManifest.xml
@@ -23,6 +23,8 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Capture screen contents -->
<uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
+ <!-- Enable / Disable tracing !-->
+ <uses-permission android:name="android.permission.DUMP" />
<!-- Run layers trace -->
<uses-permission android:name="android.permission.HARDWARE_TEST"/>
<application>
@@ -33,4 +35,4 @@
android:targetPackage="com.android.server.wm.flicker"
android:label="WindowManager Flicker Tests">
</instrumentation>
-</manifest> \ No newline at end of file
+</manifest>
diff --git a/tests/FlickerTests/AndroidTest.xml b/tests/FlickerTests/AndroidTest.xml
index e36f97656f2a..d433df56bc00 100644
--- a/tests/FlickerTests/AndroidTest.xml
+++ b/tests/FlickerTests/AndroidTest.xml
@@ -25,5 +25,6 @@
<metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector">
<option name="directory-keys" value="/sdcard/flicker" />
<option name="collect-on-run-ended-only" value="true" />
+ <option name="clean-up" value="false" />
</metrics_collector>
</configuration>
diff --git a/tests/FlickerTests/lib/Android.bp b/tests/FlickerTests/lib/Android.bp
deleted file mode 100644
index e0f0188ee618..000000000000
--- a/tests/FlickerTests/lib/Android.bp
+++ /dev/null
@@ -1,57 +0,0 @@
-//
-// Copyright (C) 2018 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.
-//
-
-java_test {
- name: "flickerlib",
- platform_apis: true,
- srcs: ["src/**/*.java"],
- static_libs: [
- "androidx.test.janktesthelper",
- "cts-wm-util",
- "platformprotosnano",
- "layersprotosnano",
- "truth-prebuilt",
- "sysui-helper",
- "launcher-helper-lib",
- ],
-}
-
-java_library {
- name: "flickerlib_without_helpers",
- platform_apis: true,
- srcs: ["src/**/*.java"],
- exclude_srcs: ["src/**/helpers/*.java"],
- static_libs: [
- "cts-wm-util",
- "platformprotosnano",
- "layersprotosnano",
- "truth-prebuilt"
- ],
-}
-
-java_library {
- name: "flickerautomationhelperlib",
- sdk_version: "test_current",
- srcs: [
- "src/com/android/server/wm/flicker/helpers/AutomationUtils.java",
- "src/com/android/server/wm/flicker/WindowUtils.java",
- ],
- static_libs: [
- "sysui-helper",
- "launcher-helper-lib",
- "compatibility-device-util-axt",
- ],
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java
deleted file mode 100644
index 38255ee6fe8d..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
-
-/**
- * Collection of functional interfaces and classes representing assertions and their associated
- * results. Assertions are functions that are applied over a single trace entry and returns a
- * result which includes a detailed reason if the assertion fails.
- */
-public class Assertions {
- /**
- * Checks assertion on a single trace entry.
- *
- * @param <T> trace entry type to perform the assertion on.
- */
- @FunctionalInterface
- public interface TraceAssertion<T> extends Function<T, Result> {
- /**
- * Returns an assertion that represents the logical negation of this assertion.
- *
- * @return a assertion that represents the logical negation of this assertion
- */
- default TraceAssertion<T> negate() {
- return (T t) -> apply(t).negate();
- }
- }
-
- /**
- * Checks assertion on a single layers trace entry.
- */
- @FunctionalInterface
- public interface LayersTraceAssertion extends TraceAssertion<LayersTrace.Entry> {
-
- }
-
- /**
- * Utility class to store assertions with an identifier to help generate more useful debug
- * data when dealing with multiple assertions.
- */
- public static class NamedAssertion<T> {
- public final TraceAssertion<T> assertion;
- public final String name;
-
- public NamedAssertion(TraceAssertion<T> assertion, String name) {
- this.assertion = assertion;
- this.name = name;
- }
- }
-
- /**
- * Contains the result of an assertion including the reason for failed assertions.
- */
- public static class Result {
- public static final String NEGATION_PREFIX = "!";
- public final boolean success;
- public final long timestamp;
- public final String assertionName;
- public final String reason;
-
- public Result(boolean success, long timestamp, String assertionName, String reason) {
- this.success = success;
- this.timestamp = timestamp;
- this.assertionName = assertionName;
- this.reason = reason;
- }
-
- public Result(boolean success, String reason) {
- this.success = success;
- this.reason = reason;
- this.assertionName = "";
- this.timestamp = 0;
- }
-
- /**
- * Returns the negated {@code Result} and adds a negation prefix to the assertion name.
- */
- public Result negate() {
- String negatedAssertionName;
- if (this.assertionName.startsWith(NEGATION_PREFIX)) {
- negatedAssertionName = this.assertionName.substring(NEGATION_PREFIX.length() + 1);
- } else {
- negatedAssertionName = NEGATION_PREFIX + this.assertionName;
- }
- return new Result(!this.success, this.timestamp, negatedAssertionName, this.reason);
- }
-
- public boolean passed() {
- return this.success;
- }
-
- public boolean failed() {
- return !this.success;
- }
-
- @Override
- public String toString() {
- return "Timestamp: " + prettyTimestamp(timestamp)
- + "\nAssertion: " + assertionName
- + "\nReason: " + reason;
- }
-
- private String prettyTimestamp(long timestamp_ns) {
- StringBuilder prettyTimestamp = new StringBuilder();
- TimeUnit[] timeUnits = {TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS, TimeUnit
- .MILLISECONDS};
- String[] unitSuffixes = {"h", "m", "s", "ms"};
-
- for (int i = 0; i < timeUnits.length; i++) {
- long convertedTime = timeUnits[i].convert(timestamp_ns, TimeUnit.NANOSECONDS);
- timestamp_ns -= TimeUnit.NANOSECONDS.convert(convertedTime, timeUnits[i]);
- prettyTimestamp.append(convertedTime).append(unitSuffixes[i]);
- }
-
- return prettyTimestamp.toString();
- }
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java
deleted file mode 100644
index 5c4df81299c1..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import com.android.server.wm.flicker.Assertions.NamedAssertion;
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.flicker.Assertions.TraceAssertion;
-
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Captures some of the common logic in {@link LayersTraceSubject} and {@link WmTraceSubject}
- * used to filter trace entries and combine multiple assertions.
- *
- * @param <T> trace entry type
- */
-public class AssertionsChecker<T extends ITraceEntry> {
- private boolean mFilterEntriesByRange = false;
- private long mFilterStartTime = 0;
- private long mFilterEndTime = 0;
- private AssertionOption mOption = AssertionOption.NONE;
- private List<NamedAssertion<T>> mAssertions = new LinkedList<>();
-
- public void add(Assertions.TraceAssertion<T> assertion, String name) {
- mAssertions.add(new NamedAssertion<>(assertion, name));
- }
-
- public void filterByRange(long startTime, long endTime) {
- mFilterEntriesByRange = true;
- mFilterStartTime = startTime;
- mFilterEndTime = endTime;
- }
-
- private void setOption(AssertionOption option) {
- if (mOption != AssertionOption.NONE && option != mOption) {
- throw new IllegalArgumentException("Cannot use " + mOption + " option with "
- + option + " option.");
- }
- mOption = option;
- }
-
- public void checkFirstEntry() {
- setOption(AssertionOption.CHECK_FIRST_ENTRY);
- }
-
- public void checkLastEntry() {
- setOption(AssertionOption.CHECK_LAST_ENTRY);
- }
-
- public void checkChangingAssertions() {
- setOption(AssertionOption.CHECK_CHANGING_ASSERTIONS);
- }
-
-
- /**
- * Filters trace entries then runs assertions returning a list of failures.
- *
- * @param entries list of entries to perform assertions on
- * @return list of failed assertion results
- */
- public List<Result> test(List<T> entries) {
- List<T> filteredEntries;
- List<Result> failures;
-
- if (mFilterEntriesByRange) {
- filteredEntries = entries.stream()
- .filter(e -> ((e.getTimestamp() >= mFilterStartTime)
- && (e.getTimestamp() <= mFilterEndTime)))
- .collect(Collectors.toList());
- } else {
- filteredEntries = entries;
- }
-
- switch (mOption) {
- case CHECK_CHANGING_ASSERTIONS:
- return assertChanges(filteredEntries);
- case CHECK_FIRST_ENTRY:
- return assertEntry(filteredEntries.get(0));
- case CHECK_LAST_ENTRY:
- return assertEntry(filteredEntries.get(filteredEntries.size() - 1));
- }
- return assertAll(filteredEntries);
- }
-
- /**
- * Steps through each trace entry checking if provided assertions are true in the order they
- * are added. Each assertion must be true for at least a single trace entry.
- *
- * This can be used to check for asserting a change in property over a trace. Such as visibility
- * for a window changes from true to false or top-most window changes from A to Bb and back to A
- * again.
- */
- private List<Result> assertChanges(List<T> entries) {
- List<Result> failures = new ArrayList<>();
- int entryIndex = 0;
- int assertionIndex = 0;
- int lastPassedAssertionIndex = -1;
-
- if (mAssertions.size() == 0) {
- return failures;
- }
-
- while (assertionIndex < mAssertions.size() && entryIndex < entries.size()) {
- TraceAssertion<T> currentAssertion = mAssertions.get(assertionIndex).assertion;
- Result result = currentAssertion.apply(entries.get(entryIndex));
- if (result.passed()) {
- lastPassedAssertionIndex = assertionIndex;
- entryIndex++;
- continue;
- }
-
- if (lastPassedAssertionIndex != assertionIndex) {
- failures.add(result);
- break;
- }
- assertionIndex++;
-
- if (assertionIndex == mAssertions.size()) {
- failures.add(result);
- break;
- }
- }
-
- if (failures.isEmpty()) {
- if (assertionIndex != mAssertions.size() - 1) {
- String reason = "\nAssertion " + mAssertions.get(assertionIndex).name
- + " never became false";
- reason += "\nPassed assertions: " + mAssertions.stream().limit(assertionIndex)
- .map(assertion -> assertion.name).collect(Collectors.joining(","));
- reason += "\nUntested assertions: " + mAssertions.stream().skip(assertionIndex + 1)
- .map(assertion -> assertion.name).collect(Collectors.joining(","));
-
- Result result = new Result(false /* success */, 0 /* timestamp */,
- "assertChanges", "Not all assertions passed." + reason);
- failures.add(result);
- }
- }
- return failures;
- }
-
- private List<Result> assertEntry(T entry) {
- List<Result> failures = new ArrayList<>();
- for (NamedAssertion<T> assertion : mAssertions) {
- Result result = assertion.assertion.apply(entry);
- if (result.failed()) {
- failures.add(result);
- }
- }
- return failures;
- }
-
- private List<Result> assertAll(List<T> entries) {
- return mAssertions.stream().flatMap(
- assertion -> entries.stream()
- .map(assertion.assertion)
- .filter(Result::failed))
- .collect(Collectors.toList());
- }
-
- private enum AssertionOption {
- NONE,
- CHECK_CHANGING_ASSERTIONS,
- CHECK_FIRST_ENTRY,
- CHECK_LAST_ENTRY,
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java
deleted file mode 100644
index c47f7f42e54e..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-/**
- * Common interface for Layer and WindowManager trace entries.
- */
-public interface ITraceEntry {
- /**
- * @return timestamp of current entry
- */
- long getTimestamp();
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java
deleted file mode 100644
index 68986d48783a..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import android.graphics.Rect;
-import android.surfaceflinger.nano.Layers.LayerProto;
-import android.surfaceflinger.nano.Layers.RectProto;
-import android.surfaceflinger.nano.Layers.RegionProto;
-import android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto;
-import android.surfaceflinger.nano.Layerstrace.LayersTraceProto;
-import android.util.SparseArray;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-/**
- * Contains a collection of parsed Layers trace entries and assertions to apply over
- * a single entry.
- *
- * Each entry is parsed into a list of {@link LayersTrace.Entry} objects.
- */
-public class LayersTrace {
- final private List<Entry> mEntries;
- @Nullable
- final private Path mSource;
-
- private LayersTrace(List<Entry> entries, Path source) {
- this.mEntries = entries;
- this.mSource = source;
- }
-
- /**
- * Parses {@code LayersTraceFileProto} from {@code data} and uses the proto to generates a list
- * of trace entries, storing the flattened layers into its hierarchical structure.
- *
- * @param data binary proto data
- * @param source Path to source of data for additional debug information
- */
- public static LayersTrace parseFrom(byte[] data, Path source) {
- List<Entry> entries = new ArrayList<>();
- LayersTraceFileProto fileProto;
- try {
- fileProto = LayersTraceFileProto.parseFrom(data);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- for (LayersTraceProto traceProto : fileProto.entry) {
- Entry entry = Entry.fromFlattenedLayers(traceProto.elapsedRealtimeNanos,
- traceProto.layers.layers);
- entries.add(entry);
- }
- return new LayersTrace(entries, source);
- }
-
- /**
- * Parses {@code LayersTraceFileProto} from {@code data} and uses the proto to generates a list
- * of trace entries, storing the flattened layers into its hierarchical structure.
- *
- * @param data binary proto data
- */
- public static LayersTrace parseFrom(byte[] data) {
- return parseFrom(data, null);
- }
-
- public List<Entry> getEntries() {
- return mEntries;
- }
-
- public Entry getEntry(long timestamp) {
- Optional<Entry> entry = mEntries.stream()
- .filter(e -> e.getTimestamp() == timestamp)
- .findFirst();
- if (!entry.isPresent()) {
- throw new RuntimeException("Entry does not exist for timestamp " + timestamp);
- }
- return entry.get();
- }
-
- public Optional<Path> getSource() {
- return Optional.ofNullable(mSource);
- }
-
- /**
- * Represents a single Layer trace entry.
- */
- public static class Entry implements ITraceEntry {
- private long mTimestamp;
- private List<Layer> mRootLayers; // hierarchical representation of layers
- private List<Layer> mFlattenedLayers = null;
-
- private Entry(long timestamp, List<Layer> rootLayers) {
- this.mTimestamp = timestamp;
- this.mRootLayers = rootLayers;
- }
-
- /**
- * Constructs the layer hierarchy from a flattened list of layers.
- */
- public static Entry fromFlattenedLayers(long timestamp, LayerProto[] protos) {
- SparseArray<Layer> layerMap = new SparseArray<>();
- ArrayList<Layer> orphans = new ArrayList<>();
- for (LayerProto proto : protos) {
- int id = proto.id;
- int parentId = proto.parent;
-
- Layer newLayer = layerMap.get(id);
- if (newLayer == null) {
- newLayer = new Layer(proto);
- layerMap.append(id, newLayer);
- } else if (newLayer.mProto != null) {
- throw new RuntimeException("Duplicate layer id found:" + id);
- } else {
- newLayer.mProto = proto;
- orphans.remove(newLayer);
- }
-
- // add parent placeholder
- if (layerMap.get(parentId) == null) {
- Layer orphanLayer = new Layer(null);
- layerMap.append(parentId, orphanLayer);
- orphans.add(orphanLayer);
- }
- layerMap.get(parentId).addChild(newLayer);
- newLayer.addParent(layerMap.get(parentId));
- }
-
- // Fail if we find orphan layers.
- orphans.remove(layerMap.get(-1));
- orphans.forEach(orphan -> {
- String childNodes = orphan.mChildren.stream().map(node ->
- Integer.toString(node.getId())).collect(Collectors.joining(", "));
- int orphanId = orphan.mChildren.get(0).mProto.parent;
- throw new RuntimeException(
- "Failed to parse layers trace. Found orphan layers with parent "
- + "layer id:" + orphanId + " : " + childNodes);
- });
-
- return new Entry(timestamp, layerMap.get(-1).mChildren);
- }
-
- /**
- * Extracts {@link Rect} from {@link RectProto}.
- */
- private static Rect extract(RectProto proto) {
- return new Rect(proto.left, proto.top, proto.right, proto.bottom);
- }
-
- /**
- * Extracts {@link Rect} from {@link RegionProto} by returning a rect that encompasses all
- * the rects making up the region.
- */
- private static Rect extract(RegionProto regionProto) {
- Rect region = new Rect();
- for (RectProto proto : regionProto.rect) {
- region.union(proto.left, proto.top, proto.right, proto.bottom);
- }
- return region;
- }
-
- /**
- * Checks if a region specified by {@code testRect} is covered by all visible layers.
- */
- public Result coversRegion(Rect testRect) {
- String assertionName = "coversRegion";
- Collection<Layer> layers = asFlattenedLayers();
-
- for (int x = testRect.left; x < testRect.right; x++) {
- for (int y = testRect.top; y < testRect.bottom; y++) {
- boolean emptyRegionFound = true;
- for (Layer layer : layers) {
- if (layer.isInvisible() || layer.isHiddenByParent()) {
- continue;
- }
- for (RectProto rectProto : layer.mProto.visibleRegion.rect) {
- Rect r = extract(rectProto);
- if (r.contains(x, y)) {
- y = r.bottom;
- emptyRegionFound = false;
- }
- }
- }
- if (emptyRegionFound) {
- String reason = "Region to test: " + testRect
- + "\nfirst empty point: " + x + ", " + y;
- reason += "\nvisible regions:";
- for (Layer layer : layers) {
- if (layer.isInvisible() || layer.isHiddenByParent()) {
- continue;
- }
- Rect r = extract(layer.mProto.visibleRegion);
- reason += "\n" + layer.mProto.name + r.toString();
- }
- return new Result(false /* success */, this.mTimestamp, assertionName,
- reason);
- }
- }
- }
- String info = "Region covered: " + testRect;
- return new Result(true /* success */, this.mTimestamp, assertionName, info);
- }
-
- /**
- * Checks if a layer with name {@code layerName} has a visible region
- * {@code expectedVisibleRegion}.
- */
- public Result hasVisibleRegion(String layerName, Rect expectedVisibleRegion) {
- String assertionName = "hasVisibleRegion";
- String reason = "Could not find " + layerName;
- for (Layer layer : asFlattenedLayers()) {
- if (layer.mProto.name.contains(layerName)) {
- if (layer.isHiddenByParent()) {
- reason = layer.getHiddenByParentReason();
- continue;
- }
- if (layer.isInvisible()) {
- reason = layer.getVisibilityReason();
- continue;
- }
- Rect visibleRegion = extract(layer.mProto.visibleRegion);
- if (visibleRegion.equals(expectedVisibleRegion)) {
- return new Result(true /* success */, this.mTimestamp, assertionName,
- layer.mProto.name + "has visible region " + expectedVisibleRegion);
- }
- reason = layer.mProto.name + " has visible region:" + visibleRegion + " "
- + "expected:" + expectedVisibleRegion;
- }
- }
- return new Result(false /* success */, this.mTimestamp, assertionName, reason);
- }
-
- /**
- * Checks if a layer with name {@code layerName} is visible.
- */
- public Result isVisible(String layerName) {
- String assertionName = "isVisible";
- String reason = "Could not find " + layerName;
- for (Layer layer : asFlattenedLayers()) {
- if (layer.mProto.name.contains(layerName)) {
- if (layer.isHiddenByParent()) {
- reason = layer.getHiddenByParentReason();
- continue;
- }
- if (layer.isInvisible()) {
- reason = layer.getVisibilityReason();
- continue;
- }
- return new Result(true /* success */, this.mTimestamp, assertionName,
- layer.mProto.name + " is visible");
- }
- }
- return new Result(false /* success */, this.mTimestamp, assertionName, reason);
- }
-
- @Override
- public long getTimestamp() {
- return mTimestamp;
- }
-
- public List<Layer> getRootLayers() {
- return mRootLayers;
- }
-
- /**
- * Returns all layers as a flattened list using a depth first traversal.
- */
- public List<Layer> asFlattenedLayers() {
- if (mFlattenedLayers == null) {
- mFlattenedLayers = new LinkedList<>();
- ArrayList<Layer> pendingLayers = new ArrayList<>(this.mRootLayers);
- while (!pendingLayers.isEmpty()) {
- Layer layer = pendingLayers.remove(0);
- mFlattenedLayers.add(layer);
- pendingLayers.addAll(0, layer.mChildren);
- }
- }
- return mFlattenedLayers;
- }
-
- public Rect getVisibleBounds(String layerName) {
- List<Layer> layers = asFlattenedLayers();
- for (Layer layer : layers) {
- if (layer.mProto.name.contains(layerName) && layer.isVisible()) {
- return extract(layer.mProto.visibleRegion);
- }
- }
- return new Rect(0, 0, 0, 0);
- }
- }
-
- /**
- * Represents a single layer with links to its parent and child layers.
- */
- public static class Layer {
- @Nullable
- public LayerProto mProto;
- public List<Layer> mChildren;
- @Nullable
- public Layer mParent = null;
-
- private Layer(LayerProto proto) {
- this.mProto = proto;
- this.mChildren = new ArrayList<>();
- }
-
- private void addChild(Layer childLayer) {
- this.mChildren.add(childLayer);
- }
-
- private void addParent(Layer parentLayer) {
- this.mParent = parentLayer;
- }
-
- public int getId() {
- return mProto.id;
- }
-
- public boolean isActiveBufferEmpty() {
- return this.mProto.activeBuffer == null || this.mProto.activeBuffer.height == 0
- || this.mProto.activeBuffer.width == 0;
- }
-
- public boolean isVisibleRegionEmpty() {
- if (this.mProto.visibleRegion == null) {
- return true;
- }
- Rect visibleRect = Entry.extract(this.mProto.visibleRegion);
- return visibleRect.height() == 0 || visibleRect.width() == 0;
- }
-
- public boolean isHidden() {
- return (this.mProto.flags & /* FLAG_HIDDEN */ 0x1) != 0x0;
- }
-
- public boolean isVisible() {
- return (!isActiveBufferEmpty() || isColorLayer())
- && !isHidden()
- && this.mProto.color != null
- && this.mProto.color.a > 0
- && !isVisibleRegionEmpty();
- }
-
- public boolean isColorLayer() {
- return this.mProto.type.equals("ColorLayer");
- }
-
- public boolean isRootLayer() {
- return mParent == null || mParent.mProto == null;
- }
-
- public boolean isInvisible() {
- return !isVisible();
- }
-
- public boolean isHiddenByParent() {
- return !isRootLayer() && (mParent.isHidden() || mParent.isHiddenByParent());
- }
-
- public String getHiddenByParentReason() {
- String reason = "Layer " + mProto.name;
- if (isHiddenByParent()) {
- reason += " is hidden by parent: " + mParent.mProto.name;
- } else {
- reason += " is not hidden by parent: " + mParent.mProto.name;
- }
- return reason;
- }
-
- public String getVisibilityReason() {
- String reason = "Layer " + mProto.name;
- if (isVisible()) {
- reason += " is visible:";
- } else {
- reason += " is invisible:";
- if (this.mProto.activeBuffer == null) {
- reason += " activeBuffer=null";
- } else if (this.mProto.activeBuffer.height == 0) {
- reason += " activeBuffer.height=0";
- } else if (this.mProto.activeBuffer.width == 0) {
- reason += " activeBuffer.width=0";
- }
- if (!isColorLayer()) {
- reason += " type != ColorLayer";
- }
- if (isHidden()) {
- reason += " flags=" + this.mProto.flags + " (FLAG_HIDDEN set)";
- }
- if (this.mProto.color == null || this.mProto.color.a == 0) {
- reason += " color.a=0";
- }
- if (isVisibleRegionEmpty()) {
- reason += " visible region is empty";
- }
- }
- return reason;
- }
- }
-} \ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java
deleted file mode 100644
index 4a5129ed2269..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.google.common.truth.Truth.assertAbout;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.graphics.Rect;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.flicker.LayersTrace.Entry;
-import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
-
-import com.google.common.truth.FailureMetadata;
-import com.google.common.truth.Subject;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Truth subject for {@link LayersTrace} objects.
- */
-public class LayersTraceSubject extends Subject<LayersTraceSubject, LayersTrace> {
- // Boiler-plate Subject.Factory for LayersTraceSubject
- private static final Subject.Factory<LayersTraceSubject, LayersTrace> FACTORY =
- new Subject.Factory<LayersTraceSubject, LayersTrace>() {
- @Override
- public LayersTraceSubject createSubject(
- FailureMetadata fm, @Nullable LayersTrace target) {
- return new LayersTraceSubject(fm, target);
- }
- };
-
- private AssertionsChecker<Entry> mChecker = new AssertionsChecker<>();
-
- private LayersTraceSubject(FailureMetadata fm, @Nullable LayersTrace subject) {
- super(fm, subject);
- }
-
- // User-defined entry point
- public static LayersTraceSubject assertThat(@Nullable LayersTrace entry) {
- return assertAbout(FACTORY).that(entry);
- }
-
- // User-defined entry point
- public static LayersTraceSubject assertThat(@Nullable TransitionResult result) {
- LayersTrace entries = LayersTrace.parseFrom(result.getLayersTrace(),
- result.getLayersTracePath());
- return assertWithMessage(result.toString()).about(FACTORY).that(entries);
- }
-
- // Static method for getting the subject factory (for use with assertAbout())
- public static Subject.Factory<LayersTraceSubject, LayersTrace> entries() {
- return FACTORY;
- }
-
- public void forAllEntries() {
- test();
- }
-
- public void forRange(long startTime, long endTime) {
- mChecker.filterByRange(startTime, endTime);
- test();
- }
-
- public LayersTraceSubject then() {
- mChecker.checkChangingAssertions();
- return this;
- }
-
- public void inTheBeginning() {
- if (getSubject().getEntries().isEmpty()) {
- fail("No entries found.");
- }
- mChecker.checkFirstEntry();
- test();
- }
-
- public void atTheEnd() {
- if (getSubject().getEntries().isEmpty()) {
- fail("No entries found.");
- }
- mChecker.checkLastEntry();
- test();
- }
-
- private void test() {
- List<Result> failures = mChecker.test(getSubject().getEntries());
- if (!failures.isEmpty()) {
- String failureLogs = failures.stream().map(Result::toString)
- .collect(Collectors.joining("\n"));
- String tracePath = "";
- if (getSubject().getSource().isPresent()) {
- tracePath = "\nLayers Trace can be found in: "
- + getSubject().getSource().get().toAbsolutePath() + "\n";
- }
- fail(tracePath + failureLogs);
- }
- }
-
- public LayersTraceSubject coversRegion(Rect rect) {
- mChecker.add(entry -> entry.coversRegion(rect),
- "coversRegion(" + rect + ")");
- return this;
- }
-
- public LayersTraceSubject hasVisibleRegion(String layerName, Rect size) {
- mChecker.add(entry -> entry.hasVisibleRegion(layerName, size),
- "hasVisibleRegion(" + layerName + size + ")");
- return this;
- }
-
- public LayersTraceSubject showsLayer(String layerName) {
- mChecker.add(entry -> entry.isVisible(layerName),
- "showsLayer(" + layerName + ")");
- return this;
- }
-
- public LayersTraceSubject hidesLayer(String layerName) {
- mChecker.add(entry -> entry.isVisible(layerName).negate(),
- "hidesLayer(" + layerName + ")");
- return this;
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java
deleted file mode 100644
index 241a1c04bdb8..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.android.server.wm.flicker.monitor.ITransitionMonitor.OUTPUT_DIR;
-
-import android.util.Log;
-
-import androidx.annotation.Nullable;
-import androidx.annotation.VisibleForTesting;
-import androidx.test.InstrumentationRegistry;
-
-import com.android.server.wm.flicker.monitor.ITransitionMonitor;
-import com.android.server.wm.flicker.monitor.LayersTraceMonitor;
-import com.android.server.wm.flicker.monitor.ScreenRecorder;
-import com.android.server.wm.flicker.monitor.WindowAnimationFrameStatsMonitor;
-import com.android.server.wm.flicker.monitor.WindowManagerTraceMonitor;
-
-import com.google.common.io.Files;
-
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Builds and runs UI transitions capturing test artifacts.
- *
- * User can compose a transition from simpler steps, specifying setup and teardown steps. During
- * a transition, Layers trace, WindowManager trace, screen recordings and window animation frame
- * stats can be captured.
- *
- * <pre>
- * Transition builder options:
- * {@link TransitionBuilder#run(Runnable)} run transition under test. Monitors will be started
- * before the transition and stopped after the transition is completed.
- * {@link TransitionBuilder#repeat(int)} repeat transitions under test multiple times recording
- * result for each run.
- * {@link TransitionBuilder#withTag(String)} specify a string identifier used to prefix logs and
- * artifacts generated.
- * {@link TransitionBuilder#runBeforeAll(Runnable)} run setup transitions once before all other
- * transition are run to set up an initial state on device.
- * {@link TransitionBuilder#runBefore(Runnable)} run setup transitions before each test transition
- * run.
- * {@link TransitionBuilder#runAfter(Runnable)} run teardown transitions after each test
- * transition.
- * {@link TransitionBuilder#runAfter(Runnable)} run teardown transitions once after all
- * other transition are run.
- * {@link TransitionBuilder#includeJankyRuns()} disables {@link WindowAnimationFrameStatsMonitor}
- * to monitor janky frames. If janky frames are detected, then the test run is skipped. This
- * monitor is enabled by default.
- * {@link TransitionBuilder#skipLayersTrace()} disables {@link LayersTraceMonitor} used to
- * capture Layers trace during a transition. This monitor is enabled by default.
- * {@link TransitionBuilder#skipWindowManagerTrace()} disables {@link WindowManagerTraceMonitor}
- * used to capture WindowManager trace during a transition. This monitor is enabled by
- * default.
- * {@link TransitionBuilder#recordAllRuns()} records the screen contents and saves it to a file.
- * All the runs including setup and teardown transitions are included in the recording. This
- * monitor is used for debugging purposes.
- * {@link TransitionBuilder#recordEachRun()} records the screen contents during test transitions
- * and saves it to a file for each run. This monitor is used for debugging purposes.
- *
- * Example transition to capture WindowManager and Layers trace when opening a test app:
- * {@code
- * TransitionRunner.newBuilder()
- * .withTag("OpenTestAppFast")
- * .runBeforeAll(UiAutomationLib::wakeUp)
- * .runBeforeAll(UiAutomationLib::UnlockDevice)
- * .runBeforeAll(UiAutomationLib::openTestApp)
- * .runBefore(UiAutomationLib::closeTestApp)
- * .run(UiAutomationLib::openTestApp)
- * .runAfterAll(UiAutomationLib::closeTestApp)
- * .repeat(5)
- * .build()
- * .run();
- * }
- * </pre>
- */
-public class TransitionRunner {
- private static final String TAG = "FLICKER";
- private final ScreenRecorder mScreenRecorder;
- private final WindowManagerTraceMonitor mWmTraceMonitor;
- private final LayersTraceMonitor mLayersTraceMonitor;
- private final WindowAnimationFrameStatsMonitor mFrameStatsMonitor;
-
- private final List<ITransitionMonitor> mAllRunsMonitors;
- private final List<ITransitionMonitor> mPerRunMonitors;
- private final List<Runnable> mBeforeAlls;
- private final List<Runnable> mBefores;
- private final List<Runnable> mTransitions;
- private final List<Runnable> mAfters;
- private final List<Runnable> mAfterAlls;
-
- private final int mIterations;
- private final String mTestTag;
-
- @Nullable
- private List<TransitionResult> mResults = null;
-
- private TransitionRunner(TransitionBuilder builder) {
- mScreenRecorder = builder.mScreenRecorder;
- mWmTraceMonitor = builder.mWmTraceMonitor;
- mLayersTraceMonitor = builder.mLayersTraceMonitor;
- mFrameStatsMonitor = builder.mFrameStatsMonitor;
-
- mAllRunsMonitors = builder.mAllRunsMonitors;
- mPerRunMonitors = builder.mPerRunMonitors;
- mBeforeAlls = builder.mBeforeAlls;
- mBefores = builder.mBefores;
- mTransitions = builder.mTransitions;
- mAfters = builder.mAfters;
- mAfterAlls = builder.mAfterAlls;
-
- mIterations = builder.mIterations;
- mTestTag = builder.mTestTag;
- }
-
- public static TransitionBuilder newBuilder() {
- return newBuilder(OUTPUT_DIR.toString());
- }
-
- public static TransitionBuilder newBuilder(String outputDir) {
- return new TransitionBuilder(outputDir);
- }
-
- /**
- * Runs the composed transition and calls monitors at the appropriate stages. If jank monitor
- * is enabled, transitions with jank are skipped.
- *
- * @return itself
- */
- public TransitionRunner run() {
- mResults = new ArrayList<>();
- mAllRunsMonitors.forEach(ITransitionMonitor::start);
- mBeforeAlls.forEach(Runnable::run);
- for (int iteration = 0; iteration < mIterations; iteration++) {
- mBefores.forEach(Runnable::run);
- mPerRunMonitors.forEach(ITransitionMonitor::start);
- mTransitions.forEach(Runnable::run);
- mPerRunMonitors.forEach(ITransitionMonitor::stop);
- mAfters.forEach(Runnable::run);
- if (runJankFree() && mFrameStatsMonitor.jankyFramesDetected()) {
- String msg = String.format("Skipping iteration %d/%d for test %s due to jank. %s",
- iteration, mIterations - 1, mTestTag, mFrameStatsMonitor.toString());
- Log.e(TAG, msg);
- continue;
- }
- mResults.add(saveResult(iteration));
- }
- mAfterAlls.forEach(Runnable::run);
- mAllRunsMonitors.forEach(monitor -> {
- monitor.stop();
- monitor.save(mTestTag);
- });
- return this;
- }
-
- /**
- * Returns a list of transition results.
- *
- * @return list of transition results.
- */
- public List<TransitionResult> getResults() {
- if (mResults == null) {
- throw new IllegalStateException("Results do not exist!");
- }
- return mResults;
- }
-
- /**
- * Deletes all transition results that are not marked for saving.
- *
- * @return list of transition results.
- */
- public void deleteResults() {
- if (mResults == null) {
- return;
- }
- mResults.stream()
- .filter(TransitionResult::canDelete)
- .forEach(TransitionResult::delete);
- mResults = null;
- }
-
- /**
- * Saves monitor results to file.
- *
- * @return object containing paths to test artifacts
- */
- private TransitionResult saveResult(int iteration) {
- Path windowTrace = null;
- Path layerTrace = null;
- Path screenCaptureVideo = null;
-
- if (mPerRunMonitors.contains(mWmTraceMonitor)) {
- windowTrace = mWmTraceMonitor.save(mTestTag, iteration);
- }
- if (mPerRunMonitors.contains(mLayersTraceMonitor)) {
- layerTrace = mLayersTraceMonitor.save(mTestTag, iteration);
- }
- if (mPerRunMonitors.contains(mScreenRecorder)) {
- screenCaptureVideo = mScreenRecorder.save(mTestTag, iteration);
- }
- return new TransitionResult(layerTrace, windowTrace, screenCaptureVideo);
- }
-
- private boolean runJankFree() {
- return mPerRunMonitors.contains(mFrameStatsMonitor);
- }
-
- public String getTestTag() {
- return mTestTag;
- }
-
- /**
- * Stores paths to all test artifacts.
- */
- @VisibleForTesting
- public static class TransitionResult {
- @Nullable
- public final Path layersTrace;
- @Nullable
- public final Path windowManagerTrace;
- @Nullable
- public final Path screenCaptureVideo;
- private boolean flaggedForSaving;
-
- public TransitionResult(@Nullable Path layersTrace, @Nullable Path windowManagerTrace,
- @Nullable Path screenCaptureVideo) {
- this.layersTrace = layersTrace;
- this.windowManagerTrace = windowManagerTrace;
- this.screenCaptureVideo = screenCaptureVideo;
- }
-
- public void flagForSaving() {
- flaggedForSaving = true;
- }
-
- public boolean canDelete() {
- return !flaggedForSaving;
- }
-
- public boolean layersTraceExists() {
- return layersTrace != null && layersTrace.toFile().exists();
- }
-
- public byte[] getLayersTrace() {
- try {
- return Files.toByteArray(this.layersTrace.toFile());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public Path getLayersTracePath() {
- return layersTrace;
- }
-
- public boolean windowManagerTraceExists() {
- return windowManagerTrace != null && windowManagerTrace.toFile().exists();
- }
-
- public byte[] getWindowManagerTrace() {
- try {
- return Files.toByteArray(this.windowManagerTrace.toFile());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public Path getWindowManagerTracePath() {
- return windowManagerTrace;
- }
-
- public boolean screenCaptureVideoExists() {
- return screenCaptureVideo != null && screenCaptureVideo.toFile().exists();
- }
-
- public Path screenCaptureVideoPath() {
- return screenCaptureVideo;
- }
-
- public void delete() {
- if (layersTraceExists()) layersTrace.toFile().delete();
- if (windowManagerTraceExists()) windowManagerTrace.toFile().delete();
- if (screenCaptureVideoExists()) screenCaptureVideo.toFile().delete();
- }
- }
-
- /**
- * Builds a {@link TransitionRunner} instance.
- */
- public static class TransitionBuilder {
- private ScreenRecorder mScreenRecorder;
- private WindowManagerTraceMonitor mWmTraceMonitor;
- private LayersTraceMonitor mLayersTraceMonitor;
- private WindowAnimationFrameStatsMonitor mFrameStatsMonitor;
-
- private List<ITransitionMonitor> mAllRunsMonitors = new LinkedList<>();
- private List<ITransitionMonitor> mPerRunMonitors = new LinkedList<>();
- private List<Runnable> mBeforeAlls = new LinkedList<>();
- private List<Runnable> mBefores = new LinkedList<>();
- private List<Runnable> mTransitions = new LinkedList<>();
- private List<Runnable> mAfters = new LinkedList<>();
- private List<Runnable> mAfterAlls = new LinkedList<>();
-
- private boolean mRunJankFree = true;
- private boolean mCaptureWindowManagerTrace = true;
- private boolean mCaptureLayersTrace = true;
- private boolean mRecordEachRun = false;
- private int mIterations = 1;
- private String mTestTag = "";
-
- private boolean mRecordAllRuns = false;
-
- public TransitionBuilder(String outputDir) {
- mScreenRecorder = new ScreenRecorder();
- mWmTraceMonitor = new WindowManagerTraceMonitor(outputDir);
- mLayersTraceMonitor = new LayersTraceMonitor(outputDir);
- mFrameStatsMonitor = new
- WindowAnimationFrameStatsMonitor(InstrumentationRegistry.getInstrumentation());
- }
-
- public TransitionRunner build() {
- if (mCaptureWindowManagerTrace) {
- mPerRunMonitors.add(mWmTraceMonitor);
- }
-
- if (mCaptureLayersTrace) {
- mPerRunMonitors.add(mLayersTraceMonitor);
- }
-
- if (mRunJankFree) {
- mPerRunMonitors.add(mFrameStatsMonitor);
- }
-
- if (mRecordAllRuns) {
- mAllRunsMonitors.add(mScreenRecorder);
- }
-
- if (mRecordEachRun) {
- mPerRunMonitors.add(mScreenRecorder);
- }
-
- return new TransitionRunner(this);
- }
-
- public TransitionBuilder runBeforeAll(Runnable runnable) {
- mBeforeAlls.add(runnable);
- return this;
- }
-
- public TransitionBuilder runBefore(Runnable runnable) {
- mBefores.add(runnable);
- return this;
- }
-
- public TransitionBuilder run(Runnable runnable) {
- mTransitions.add(runnable);
- return this;
- }
-
- public TransitionBuilder runAfter(Runnable runnable) {
- mAfters.add(runnable);
- return this;
- }
-
- public TransitionBuilder runAfterAll(Runnable runnable) {
- mAfterAlls.add(runnable);
- return this;
- }
-
- public TransitionBuilder repeat(int iterations) {
- mIterations = iterations;
- return this;
- }
-
- public TransitionBuilder skipWindowManagerTrace() {
- mCaptureWindowManagerTrace = false;
- return this;
- }
-
- public TransitionBuilder skipLayersTrace() {
- mCaptureLayersTrace = false;
- return this;
- }
-
- public TransitionBuilder includeJankyRuns() {
- mRunJankFree = false;
- return this;
- }
-
- public TransitionBuilder recordEachRun() {
- if (mRecordAllRuns) {
- throw new IllegalArgumentException("Invalid option with recordAllRuns");
- }
- mRecordEachRun = true;
- return this;
- }
-
- public TransitionBuilder recordAllRuns() {
- if (mRecordEachRun) {
- throw new IllegalArgumentException("Invalid option with recordEachRun");
- }
- mRecordAllRuns = true;
- return this;
- }
-
- public TransitionBuilder withTag(String testTag) {
- if (testTag.contains(" ")) {
- throw new IllegalArgumentException("The test tag can not contain spaces since it "
- + "is a part of the file name");
- }
- mTestTag = testTag;
- return this;
- }
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java
deleted file mode 100644
index 412e72d82e55..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.nano.AppWindowTokenProto;
-import com.android.server.wm.nano.StackProto;
-import com.android.server.wm.nano.TaskProto;
-import com.android.server.wm.nano.WindowManagerTraceFileProto;
-import com.android.server.wm.nano.WindowManagerTraceProto;
-import com.android.server.wm.nano.WindowStateProto;
-import com.android.server.wm.nano.WindowTokenProto;
-
-import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
-
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
-/**
- * Contains a collection of parsed WindowManager trace entries and assertions to apply over
- * a single entry.
- *
- * Each entry is parsed into a list of {@link WindowManagerTrace.Entry} objects.
- */
-public class WindowManagerTrace {
- private static final int DEFAULT_DISPLAY = 0;
- private final List<Entry> mEntries;
- @Nullable
- final private Path mSource;
-
- private WindowManagerTrace(List<Entry> entries, Path source) {
- this.mEntries = entries;
- this.mSource = source;
- }
-
- /**
- * Parses {@code WindowManagerTraceFileProto} from {@code data} and uses the proto to
- * generates a list of trace entries.
- *
- * @param data binary proto data
- * @param source Path to source of data for additional debug information
- */
- public static WindowManagerTrace parseFrom(byte[] data, Path source) {
- List<Entry> entries = new ArrayList<>();
-
- WindowManagerTraceFileProto fileProto;
- try {
- fileProto = WindowManagerTraceFileProto.parseFrom(data);
- } catch (InvalidProtocolBufferNanoException e) {
- throw new RuntimeException(e);
- }
- for (WindowManagerTraceProto entryProto : fileProto.entry) {
- entries.add(new Entry(entryProto));
- }
- return new WindowManagerTrace(entries, source);
- }
-
- public static WindowManagerTrace parseFrom(byte[] data) {
- return parseFrom(data, null);
- }
-
- public List<Entry> getEntries() {
- return mEntries;
- }
-
- public Entry getEntry(long timestamp) {
- Optional<Entry> entry = mEntries.stream()
- .filter(e -> e.getTimestamp() == timestamp)
- .findFirst();
- if (!entry.isPresent()) {
- throw new RuntimeException("Entry does not exist for timestamp " + timestamp);
- }
- return entry.get();
- }
-
- public Optional<Path> getSource() {
- return Optional.ofNullable(mSource);
- }
-
- /**
- * Represents a single WindowManager trace entry.
- */
- public static class Entry implements ITraceEntry {
- private final WindowManagerTraceProto mProto;
-
- public Entry(WindowManagerTraceProto proto) {
- mProto = proto;
- }
-
- private static Result isWindowVisible(String windowTitle,
- WindowTokenProto[] windowTokenProtos) {
- boolean titleFound = false;
- for (WindowTokenProto windowToken : windowTokenProtos) {
- for (WindowStateProto windowState : windowToken.windows) {
- if (windowState.identifier.title.contains(windowTitle)) {
- titleFound = true;
- if (isVisible(windowState)) {
- return new Result(true /* success */,
- windowState.identifier.title + " is visible");
- }
- }
- }
- }
-
- String reason;
- if (!titleFound) {
- reason = windowTitle + " cannot be found";
- } else {
- reason = windowTitle + " is invisible";
- }
- return new Result(false /* success */, reason);
- }
-
- private static boolean isVisible(WindowStateProto windowState) {
- return windowState.windowContainer.visible;
- }
-
- @Override
- public long getTimestamp() {
- return mProto.elapsedRealtimeNanos;
- }
-
- /**
- * Returns window title of the top most visible app window.
- */
- private String getTopVisibleAppWindow() {
- StackProto[] stacks = mProto.windowManagerService.rootWindowContainer
- .displays[DEFAULT_DISPLAY].stacks;
- for (StackProto stack : stacks) {
- for (TaskProto task : stack.tasks) {
- for (AppWindowTokenProto token : task.appWindowTokens) {
- for (WindowStateProto windowState : token.windowToken.windows) {
- if (windowState.windowContainer.visible) {
- return task.appWindowTokens[0].name;
- }
- }
- }
- }
- }
-
- return "";
- }
-
- /**
- * Checks if aboveAppWindow with {@code windowTitle} is visible.
- */
- public Result isAboveAppWindowVisible(String windowTitle) {
- WindowTokenProto[] windowTokenProtos = mProto.windowManagerService
- .rootWindowContainer
- .displays[DEFAULT_DISPLAY].aboveAppWindows;
- Result result = isWindowVisible(windowTitle, windowTokenProtos);
- return new Result(result.success, getTimestamp(), "showsAboveAppWindow", result.reason);
- }
-
- /**
- * Checks if belowAppWindow with {@code windowTitle} is visible.
- */
- public Result isBelowAppWindowVisible(String windowTitle) {
- WindowTokenProto[] windowTokenProtos = mProto.windowManagerService
- .rootWindowContainer
- .displays[DEFAULT_DISPLAY].belowAppWindows;
- Result result = isWindowVisible(windowTitle, windowTokenProtos);
- return new Result(result.success, getTimestamp(), "isBelowAppWindowVisible",
- result.reason);
- }
-
- /**
- * Checks if imeWindow with {@code windowTitle} is visible.
- */
- public Result isImeWindowVisible(String windowTitle) {
- WindowTokenProto[] windowTokenProtos = mProto.windowManagerService
- .rootWindowContainer
- .displays[DEFAULT_DISPLAY].imeWindows;
- Result result = isWindowVisible(windowTitle, windowTokenProtos);
- return new Result(result.success, getTimestamp(), "isImeWindowVisible",
- result.reason);
- }
-
- /**
- * Checks if app window with {@code windowTitle} is on top.
- */
- public Result isVisibleAppWindowOnTop(String windowTitle) {
- String topAppWindow = getTopVisibleAppWindow();
- boolean success = topAppWindow.contains(windowTitle);
- String reason = "wanted=" + windowTitle + " found=" + topAppWindow;
- return new Result(success, getTimestamp(), "isAppWindowOnTop", reason);
- }
-
- /**
- * Checks if app window with {@code windowTitle} is visible.
- */
- public Result isAppWindowVisible(String windowTitle) {
- final String assertionName = "isAppWindowVisible";
- boolean titleFound = false;
- StackProto[] stacks = mProto.windowManagerService.rootWindowContainer
- .displays[DEFAULT_DISPLAY].stacks;
- for (StackProto stack : stacks) {
- for (TaskProto task : stack.tasks) {
- for (AppWindowTokenProto token : task.appWindowTokens) {
- if (token.name.contains(windowTitle)) {
- titleFound = true;
- for (WindowStateProto windowState : token.windowToken.windows) {
- if (windowState.windowContainer.visible) {
- return new Result(true /* success */, getTimestamp(),
- assertionName, "Window " + token.name +
- "is visible");
- }
- }
- }
- }
- }
- }
- String reason;
- if (!titleFound) {
- reason = "Window " + windowTitle + " cannot be found";
- } else {
- reason = "Window " + windowTitle + " is invisible";
- }
- return new Result(false /* success */, getTimestamp(), assertionName, reason);
- }
- }
-} \ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java
deleted file mode 100644
index 3d25fbed5135..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.view.Surface;
-import android.view.WindowManager;
-
-import androidx.test.InstrumentationRegistry;
-
-/**
- * Helper functions to retrieve system window sizes and positions.
- */
-public class WindowUtils {
-
- public static Rect getDisplayBounds() {
- Point display = new Point();
- WindowManager wm =
- (WindowManager) InstrumentationRegistry.getContext().getSystemService(
- Context.WINDOW_SERVICE);
- wm.getDefaultDisplay().getRealSize(display);
- return new Rect(0, 0, display.x, display.y);
- }
-
- private static int getCurrentRotation() {
- WindowManager wm =
- (WindowManager) InstrumentationRegistry.getContext().getSystemService(
- Context.WINDOW_SERVICE);
- return wm.getDefaultDisplay().getRotation();
- }
-
- public static Rect getDisplayBounds(int requestedRotation) {
- Rect displayBounds = getDisplayBounds();
- int currentDisplayRotation = getCurrentRotation();
-
- boolean displayIsRotated = (currentDisplayRotation == Surface.ROTATION_90 ||
- currentDisplayRotation == Surface.ROTATION_270);
-
- boolean requestedDisplayIsRotated = requestedRotation == Surface.ROTATION_90 ||
- requestedRotation == Surface.ROTATION_270;
-
- // if the current orientation changes with the requested rotation,
- // flip height and width of display bounds.
- if (displayIsRotated != requestedDisplayIsRotated) {
- return new Rect(0, 0, displayBounds.height(), displayBounds.width());
- }
-
- return new Rect(0, 0, displayBounds.width(), displayBounds.height());
- }
-
-
- public static Rect getAppPosition(int requestedRotation) {
- Rect displayBounds = getDisplayBounds();
- int currentDisplayRotation = getCurrentRotation();
-
- boolean displayIsRotated = currentDisplayRotation == Surface.ROTATION_90 ||
- currentDisplayRotation == Surface.ROTATION_270;
-
- boolean requestedAppIsRotated = requestedRotation == Surface.ROTATION_90 ||
- requestedRotation == Surface.ROTATION_270;
-
- // display size will change if the display is reflected. Flip height and width of app if the
- // requested rotation is different from the current rotation.
- if (displayIsRotated != requestedAppIsRotated) {
- return new Rect(0, 0, displayBounds.height(), displayBounds.width());
- }
-
- return new Rect(0, 0, displayBounds.width(), displayBounds.height());
- }
-
- public static Rect getStatusBarPosition(int requestedRotation) {
- Resources resources = InstrumentationRegistry.getContext().getResources();
- String resourceName;
- Rect displayBounds = getDisplayBounds();
- int width;
- if (requestedRotation == Surface.ROTATION_0 || requestedRotation == Surface.ROTATION_180) {
- resourceName = "status_bar_height_portrait";
- width = Math.min(displayBounds.width(), displayBounds.height());
- } else {
- resourceName = "status_bar_height_landscape";
- width = Math.max(displayBounds.width(), displayBounds.height());
- }
-
- int resourceId = resources.getIdentifier(resourceName, "dimen", "android");
- int height = resources.getDimensionPixelSize(resourceId);
-
- return new Rect(0, 0, width, height);
- }
-
- public static Rect getNavigationBarPosition(int requestedRotation) {
- Resources resources = InstrumentationRegistry.getContext().getResources();
- Rect displayBounds = getDisplayBounds();
- int displayWidth = Math.min(displayBounds.width(), displayBounds.height());
- int displayHeight = Math.max(displayBounds.width(), displayBounds.height());
- int resourceId;
- if (requestedRotation == Surface.ROTATION_0 || requestedRotation == Surface.ROTATION_180) {
- resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
- int height = resources.getDimensionPixelSize(resourceId);
- return new Rect(0, displayHeight - height, displayWidth, displayHeight);
- } else {
- resourceId = resources.getIdentifier("navigation_bar_width", "dimen", "android");
- int width = resources.getDimensionPixelSize(resourceId);
- // swap display dimensions in landscape or seascape mode
- int temp = displayHeight;
- displayHeight = displayWidth;
- displayWidth = temp;
- if (requestedRotation == Surface.ROTATION_90) {
- return new Rect(0, 0, width, displayHeight);
- } else {
- return new Rect(displayWidth - width, 0, displayWidth, displayHeight);
- }
- }
- }
-
- public static int getNavigationBarHeight() {
- Resources resources = InstrumentationRegistry.getContext().getResources();
- int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
- return resources.getDimensionPixelSize(resourceId);
- }
-
- public static int getDockedStackDividerInset() {
- Resources resources = InstrumentationRegistry.getContext().getResources();
- int resourceId = resources.getIdentifier("docked_stack_divider_insets", "dimen",
- "android");
- return resources.getDimensionPixelSize(resourceId);
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java
deleted file mode 100644
index 064cc2702f39..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.google.common.truth.Truth.assertAbout;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
-
-import com.google.common.truth.FailureMetadata;
-import com.google.common.truth.Subject;
-
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-/**
- * Truth subject for {@link WindowManagerTrace} objects.
- */
-public class WmTraceSubject extends Subject<WmTraceSubject, WindowManagerTrace> {
- // Boiler-plate Subject.Factory for WmTraceSubject
- private static final Subject.Factory<WmTraceSubject, WindowManagerTrace> FACTORY =
- new Subject.Factory<WmTraceSubject, WindowManagerTrace>() {
- @Override
- public WmTraceSubject createSubject(
- FailureMetadata fm, @Nullable WindowManagerTrace target) {
- return new WmTraceSubject(fm, target);
- }
- };
-
- private AssertionsChecker<WindowManagerTrace.Entry> mChecker = new AssertionsChecker<>();
-
- private WmTraceSubject(FailureMetadata fm, @Nullable WindowManagerTrace subject) {
- super(fm, subject);
- }
-
- // User-defined entry point
- public static WmTraceSubject assertThat(@Nullable WindowManagerTrace entry) {
- return assertAbout(FACTORY).that(entry);
- }
-
- // User-defined entry point
- public static WmTraceSubject assertThat(@Nullable TransitionResult result) {
- WindowManagerTrace entries = WindowManagerTrace.parseFrom(result.getWindowManagerTrace(),
- result.getWindowManagerTracePath());
- return assertWithMessage(result.toString()).about(FACTORY).that(entries);
- }
-
- // Static method for getting the subject factory (for use with assertAbout())
- public static Subject.Factory<WmTraceSubject, WindowManagerTrace> entries() {
- return FACTORY;
- }
-
- public void forAllEntries() {
- test();
- }
-
- public void forRange(long startTime, long endTime) {
- mChecker.filterByRange(startTime, endTime);
- test();
- }
-
- public WmTraceSubject then() {
- mChecker.checkChangingAssertions();
- return this;
- }
-
- public void inTheBeginning() {
- if (getSubject().getEntries().isEmpty()) {
- fail("No entries found.");
- }
- mChecker.checkFirstEntry();
- test();
- }
-
- public void atTheEnd() {
- if (getSubject().getEntries().isEmpty()) {
- fail("No entries found.");
- }
- mChecker.checkLastEntry();
- test();
- }
-
- private void test() {
- List<Result> failures = mChecker.test(getSubject().getEntries());
- if (!failures.isEmpty()) {
- Optional<Path> failureTracePath = getSubject().getSource();
- String failureLogs = failures.stream().map(Result::toString)
- .collect(Collectors.joining("\n"));
- String tracePath = "";
- if (failureTracePath.isPresent()) {
- tracePath = "\nWindowManager Trace can be found in: "
- + failureTracePath.get().toAbsolutePath() + "\n";
- }
- fail(tracePath + failureLogs);
- }
- }
-
- public WmTraceSubject showsAboveAppWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isAboveAppWindowVisible(partialWindowTitle),
- "showsAboveAppWindow(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject hidesAboveAppWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isAboveAppWindowVisible(partialWindowTitle).negate(),
- "hidesAboveAppWindow" + "(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject showsBelowAppWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isBelowAppWindowVisible(partialWindowTitle),
- "showsBelowAppWindow(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject hidesBelowAppWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isBelowAppWindowVisible(partialWindowTitle).negate(),
- "hidesBelowAppWindow" + "(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject showsImeWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isImeWindowVisible(partialWindowTitle),
- "showsBelowAppWindow(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject hidesImeWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isImeWindowVisible(partialWindowTitle).negate(),
- "hidesImeWindow" + "(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject showsAppWindowOnTop(String partialWindowTitle) {
- mChecker.add(
- entry -> {
- Result result = entry.isAppWindowVisible(partialWindowTitle);
- if (result.passed()) {
- result = entry.isVisibleAppWindowOnTop(partialWindowTitle);
- }
- return result;
- },
- "showsAppWindowOnTop(" + partialWindowTitle + ")"
- );
- return this;
- }
-
- public WmTraceSubject hidesAppWindowOnTop(String partialWindowTitle) {
- mChecker.add(
- entry -> {
- Result result = entry.isAppWindowVisible(partialWindowTitle).negate();
- if (result.failed()) {
- result = entry.isVisibleAppWindowOnTop(partialWindowTitle).negate();
- }
- return result;
- },
- "hidesAppWindowOnTop(" + partialWindowTitle + ")"
- );
- return this;
- }
-
- public WmTraceSubject showsAppWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isAppWindowVisible(partialWindowTitle),
- "showsAppWindow(" + partialWindowTitle + ")");
- return this;
- }
-
- public WmTraceSubject hidesAppWindow(String partialWindowTitle) {
- mChecker.add(entry -> entry.isAppWindowVisible(partialWindowTitle).negate(),
- "hidesAppWindow(" + partialWindowTitle + ")");
- return this;
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java
deleted file mode 100644
index 6821ff02e371..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.helpers;
-
-import static android.os.SystemClock.sleep;
-import static android.system.helpers.OverviewHelper.isRecentsInLauncher;
-import static android.view.Surface.ROTATION_0;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.os.RemoteException;
-import android.support.test.launcherhelper.LauncherStrategyFactory;
-import android.support.test.uiautomator.By;
-import android.support.test.uiautomator.BySelector;
-import android.support.test.uiautomator.Configurator;
-import android.support.test.uiautomator.UiDevice;
-import android.support.test.uiautomator.UiObject2;
-import android.support.test.uiautomator.Until;
-import android.util.Log;
-import android.util.Rational;
-import android.view.View;
-import android.view.ViewConfiguration;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.android.server.wm.flicker.WindowUtils;
-
-/**
- * Collection of UI Automation helper functions.
- */
-public class AutomationUtils {
- private static final String SYSTEMUI_PACKAGE = "com.android.systemui";
- private static final long FIND_TIMEOUT = 10000;
- private static final long LONG_PRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout() * 2L;
- private static final String TAG = "FLICKER";
-
- public static void wakeUpAndGoToHomeScreen() {
- UiDevice device = UiDevice.getInstance(InstrumentationRegistry
- .getInstrumentation());
- try {
- device.wakeUp();
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
- device.pressHome();
- }
-
- /**
- * Sets {@link android.app.UiAutomation#waitForIdle(long, long)} global timeout to 0 causing
- * the {@link android.app.UiAutomation#waitForIdle(long, long)} function to timeout instantly.
- * This removes some delays when using the UIAutomator library required to create fast UI
- * transitions.
- */
- public static void setFastWait() {
- Configurator.getInstance().setWaitForIdleTimeout(0);
- }
-
- /**
- * Reverts {@link android.app.UiAutomation#waitForIdle(long, long)} to default behavior.
- */
- public static void setDefaultWait() {
- Configurator.getInstance().setWaitForIdleTimeout(10000);
- }
-
- public static boolean isQuickstepEnabled(UiDevice device) {
- return device.findObject(By.res(SYSTEMUI_PACKAGE, "recent_apps")) == null;
- }
-
- public static void openQuickstep(UiDevice device) {
- if (isQuickstepEnabled(device)) {
- int height = device.getDisplayHeight();
- UiObject2 navBar = device.findObject(By.res(SYSTEMUI_PACKAGE, "navigation_bar_frame"));
-
- Rect navBarVisibleBounds;
-
- // TODO(vishnun) investigate why this object cannot be found.
- if (navBar != null) {
- navBarVisibleBounds = navBar.getVisibleBounds();
- } else {
- Log.e(TAG, "Could not find nav bar, infer location");
- navBarVisibleBounds = WindowUtils.getNavigationBarPosition(ROTATION_0);
- }
-
- // Swipe from nav bar to 2/3rd down the screen.
- device.swipe(
- navBarVisibleBounds.centerX(), navBarVisibleBounds.centerY(),
- navBarVisibleBounds.centerX(), height * 2 / 3,
- (navBarVisibleBounds.centerY() - height * 2 / 3) / 100); // 100 px/step
- } else {
- try {
- device.pressRecentApps();
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
- }
- BySelector RECENTS = By.res(SYSTEMUI_PACKAGE, "recents_view");
-
- // use a long timeout to wait until recents populated
- if (device.wait(
- Until.findObject(isRecentsInLauncher()
- ? getLauncherOverviewSelector(device) : RECENTS),
- 10000) == null) {
- fail("Recents didn't appear");
- }
- device.waitForIdle();
- }
-
- public static void clearRecents(UiDevice device) {
- if (isQuickstepEnabled(device)) {
- openQuickstep(device);
-
- for (int i = 0; i < 5; i++) {
- device.swipe(device.getDisplayWidth() / 2,
- device.getDisplayHeight() / 2, device.getDisplayWidth(),
- device.getDisplayHeight() / 2,
- 5);
-
- BySelector clearAllSelector = By.res("com.google.android.apps.nexuslauncher",
- "clear_all_button");
- UiObject2 clearAllButton = device.wait(Until.findObject(clearAllSelector), 100);
- if (clearAllButton != null) {
- clearAllButton.click();
- return;
- }
- }
- }
- }
-
- private static BySelector getLauncherOverviewSelector(UiDevice device) {
- return By.res(device.getLauncherPackageName(), "overview_panel");
- }
-
- private static void longPressRecents(UiDevice device) {
- BySelector recentsSelector = By.res(SYSTEMUI_PACKAGE, "recent_apps");
- UiObject2 recentsButton = device.wait(Until.findObject(recentsSelector), FIND_TIMEOUT);
- assertNotNull("Unable to find recents button", recentsButton);
- recentsButton.click(LONG_PRESS_TIMEOUT);
- }
-
- public static void launchSplitScreen(UiDevice device) {
- String mLauncherPackage = LauncherStrategyFactory.getInstance(device)
- .getLauncherStrategy().getSupportedLauncherPackage();
-
- if (isQuickstepEnabled(device)) {
- // Quickstep enabled
- openQuickstep(device);
-
- BySelector overviewIconSelector = By.res(mLauncherPackage, "icon")
- .clazz(View.class);
- UiObject2 overviewIcon = device.wait(Until.findObject(overviewIconSelector),
- FIND_TIMEOUT);
- assertNotNull("Unable to find app icon in Overview", overviewIcon);
- overviewIcon.click();
-
- BySelector splitscreenButtonSelector = By.text("Split screen");
- UiObject2 splitscreenButton = device.wait(Until.findObject(splitscreenButtonSelector),
- FIND_TIMEOUT);
- assertNotNull("Unable to find Split screen button in Overview", splitscreenButton);
- splitscreenButton.click();
- } else {
- // Classic long press recents
- longPressRecents(device);
- }
- // Wait for animation to complete.
- sleep(2000);
- }
-
- public static void exitSplitScreen(UiDevice device) {
- if (isQuickstepEnabled(device)) {
- // Quickstep enabled
- BySelector dividerSelector = By.res(SYSTEMUI_PACKAGE, "docked_divider_handle");
- UiObject2 divider = device.wait(Until.findObject(dividerSelector), FIND_TIMEOUT);
- assertNotNull("Unable to find Split screen divider", divider);
-
- // Drag the split screen divider to the top of the screen
- divider.drag(new Point(device.getDisplayWidth() / 2, 0), 400);
- } else {
- // Classic long press recents
- longPressRecents(device);
- }
- // Wait for animation to complete.
- sleep(2000);
- }
-
- public static void resizeSplitScreen(UiDevice device, Rational windowHeightRatio) {
- BySelector dividerSelector = By.res(SYSTEMUI_PACKAGE, "docked_divider_handle");
- UiObject2 divider = device.wait(Until.findObject(dividerSelector), FIND_TIMEOUT);
- assertNotNull("Unable to find Split screen divider", divider);
- int destHeight =
- (int) (WindowUtils.getDisplayBounds().height() * windowHeightRatio.floatValue());
- // Drag the split screen divider to so that the ratio of top window height and bottom
- // window height is windowHeightRatio
- device.drag(divider.getVisibleBounds().centerX(), divider.getVisibleBounds().centerY(),
- device.getDisplayWidth() / 2, destHeight, 10);
- //divider.drag(new Point(device.getDisplayWidth() / 2, destHeight), 400)
- divider = device.wait(Until.findObject(dividerSelector), FIND_TIMEOUT);
-
- // Wait for animation to complete.
- sleep(2000);
- }
-
- public static void closePipWindow(UiDevice device) {
- UiObject2 pipWindow = device.findObject(
- By.res(SYSTEMUI_PACKAGE, "background"));
- pipWindow.click();
- UiObject2 exitPipObject = device.findObject(
- By.res(SYSTEMUI_PACKAGE, "dismiss"));
- exitPipObject.click();
- // Wait for animation to complete.
- sleep(2000);
- }
-
- public static void expandPipWindow(UiDevice device) {
- UiObject2 pipWindow = device.findObject(
- By.res(SYSTEMUI_PACKAGE, "background"));
- pipWindow.click();
- pipWindow.click();
- }
-
- public static void stopPackage(Context context, String packageName) {
- runShellCommand("am force-stop " + packageName);
- int packageUid;
- try {
- packageUid = context.getPackageManager().getPackageUid(packageName, /* flags= */0);
- } catch (PackageManager.NameNotFoundException e) {
- return;
- }
- while (targetPackageIsRunning(packageUid)) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- //ignore
- }
- }
- }
-
- private static boolean targetPackageIsRunning(int uid) {
- final String result = runShellCommand(
- String.format("cmd activity get-uid-state %d", uid));
- return !result.contains("(NONEXISTENT)");
- }
-} \ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java
deleted file mode 100644
index 67e0ecc1cde7..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import android.os.Environment;
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-/**
- * Collects test artifacts during a UI transition.
- */
-public interface ITransitionMonitor {
- Path OUTPUT_DIR = Paths.get(Environment.getExternalStorageDirectory().toString(), "flicker");
-
- /**
- * Starts monitor.
- */
- void start();
-
- /**
- * Stops monitor.
- */
- void stop();
-
- /**
- * Saves any monitor artifacts to file adding {@code testTag} and {@code iteration}
- * to the file name.
- *
- * @param testTag suffix added to artifact name
- * @param iteration suffix added to artifact name
- *
- * @return Path to saved artifact
- */
- default Path save(String testTag, int iteration) {
- return save(testTag + "_" + iteration);
- }
-
- /**
- * Saves any monitor artifacts to file adding {@code testTag} to the file name.
- *
- * @param testTag suffix added to artifact name
- *
- * @return Path to saved artifact
- */
- default Path save(String testTag) {
- throw new UnsupportedOperationException("Save not implemented for this monitor");
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java
deleted file mode 100644
index da75b3e86d6b..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import android.os.RemoteException;
-import android.view.IWindowManager;
-import android.view.WindowManagerGlobal;
-
-/**
- * Captures Layers trace from SurfaceFlinger.
- */
-public class LayersTraceMonitor extends TraceMonitor {
- private IWindowManager mWm = WindowManagerGlobal.getWindowManagerService();
-
- public LayersTraceMonitor() {
- this(OUTPUT_DIR.toString());
- }
-
- public LayersTraceMonitor(String outputDir) {
- super(outputDir, "layers_trace.pb");
- }
-
- @Override
- public void start() {
- setEnabled(true);
- }
-
- @Override
- public void stop() {
- setEnabled(false);
- }
-
- @Override
- public boolean isEnabled() throws RemoteException {
- try {
- return mWm.isLayerTracing();
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- private void setEnabled(boolean isEnabled) {
- try {
- mWm.setLayerTracing(isEnabled);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java
deleted file mode 100644
index dce1c2739b15..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
-
-import android.util.Log;
-
-import androidx.annotation.VisibleForTesting;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-/**
- * Captures screen contents and saves it as a mp4 video file.
- */
-public class ScreenRecorder implements ITransitionMonitor {
- @VisibleForTesting
- public static final Path DEFAULT_OUTPUT_PATH = OUTPUT_DIR.resolve("transition.mp4");
- private static final String TAG = "FLICKER";
- private Thread recorderThread;
-
- @VisibleForTesting
- public static Path getPath(String testTag) {
- return OUTPUT_DIR.resolve(testTag + ".mp4");
- }
-
- @Override
- public void start() {
- OUTPUT_DIR.toFile().mkdirs();
- String command = "screenrecord " + DEFAULT_OUTPUT_PATH;
- recorderThread = new Thread(() -> {
- try {
- Runtime.getRuntime().exec(command);
- } catch (IOException e) {
- Log.e(TAG, "Error executing " + command, e);
- }
- });
- recorderThread.start();
- }
-
- @Override
- public void stop() {
- runShellCommand("killall -s 2 screenrecord");
- try {
- recorderThread.join();
- } catch (InterruptedException e) {
- // ignore
- }
- }
-
- @Override
- public Path save(String testTag) {
- try {
- Path targetPath = Files.move(DEFAULT_OUTPUT_PATH, getPath(testTag),
- REPLACE_EXISTING);
- Log.i(TAG, "Video saved to " + targetPath.toString());
- return targetPath;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java
deleted file mode 100644
index 1ba36bba92ef..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import android.os.RemoteException;
-
-import androidx.annotation.VisibleForTesting;
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Locale;
-
-/**
- * Base class for monitors containing common logic to read the trace
- * as a byte array and save the trace to another location.
- */
-public abstract class TraceMonitor implements ITransitionMonitor {
- public static final String TAG = "FLICKER";
- private static final String TRACE_DIR = "/data/misc/wmtrace/";
-
- private Path mOutputDir;
- public String mTraceFileName;
-
- public abstract boolean isEnabled() throws RemoteException;
-
- public TraceMonitor(String outputDir, String traceFileName) {
- mOutputDir = Paths.get(outputDir);
- mTraceFileName = traceFileName;
- }
-
- /**
- * Saves trace file to the external storage directory suffixing the name with the testtag
- * and iteration.
- *
- * Moves the trace file from the default location via a shell command since the test app
- * does not have security privileges to access /data/misc/wmtrace.
- *
- * @param testTag suffix added to trace name used to identify trace
- *
- * @return Path to saved trace file
- */
- @Override
- public Path save(String testTag) {
- OUTPUT_DIR.toFile().mkdirs();
- Path traceFileCopy = getOutputTraceFilePath(testTag);
-
- // Read the input stream fully.
- String copyCommand = String.format(Locale.getDefault(), "mv %s%s %s", TRACE_DIR,
- mTraceFileName, traceFileCopy.toString());
- runShellCommand(copyCommand);
- return traceFileCopy;
- }
-
- @VisibleForTesting
- public Path getOutputTraceFilePath(String testTag) {
- return mOutputDir.resolve(mTraceFileName + "_" + testTag);
- }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java
deleted file mode 100644
index 3f86f0d001d7..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static android.view.FrameStats.UNDEFINED_TIME_NANO;
-
-import android.app.Instrumentation;
-import android.util.Log;
-import android.view.FrameStats;
-
-/**
- * Monitors {@link android.view.WindowAnimationFrameStats} to detect janky frames.
- *
- * Adapted from {@link androidx.test.jank.internal.WindowAnimationFrameStatsMonitorImpl}
- * using the same threshold to determine jank.
- */
-public class WindowAnimationFrameStatsMonitor implements ITransitionMonitor {
-
- private static final String TAG = "FLICKER";
- // Maximum normalized error in frame duration before the frame is considered janky
- private static final double MAX_ERROR = 0.5f;
- // Maximum normalized frame duration before the frame is considered a pause
- private static final double PAUSE_THRESHOLD = 15.0f;
- private Instrumentation mInstrumentation;
- private FrameStats stats;
- private int numJankyFrames;
- private long mLongestFrameNano = 0L;
-
-
- /**
- * Constructs a WindowAnimationFrameStatsMonitor instance.
- */
- public WindowAnimationFrameStatsMonitor(Instrumentation instrumentation) {
- mInstrumentation = instrumentation;
- }
-
- private void analyze() {
- int frameCount = stats.getFrameCount();
- long refreshPeriodNano = stats.getRefreshPeriodNano();
-
- // Skip first frame
- for (int i = 2; i < frameCount; i++) {
- // Handle frames that have not been presented.
- if (stats.getFramePresentedTimeNano(i) == UNDEFINED_TIME_NANO) {
- // The animation must not have completed. Warn and break out of the loop.
- Log.w(TAG, "Skipping fenced frame.");
- break;
- }
- long frameDurationNano = stats.getFramePresentedTimeNano(i) -
- stats.getFramePresentedTimeNano(i - 1);
- double normalized = (double) frameDurationNano / refreshPeriodNano;
- if (normalized < PAUSE_THRESHOLD) {
- if (normalized > 1.0f + MAX_ERROR) {
- numJankyFrames++;
- }
- mLongestFrameNano = Math.max(mLongestFrameNano, frameDurationNano);
- }
- }
- }
-
- @Override
- public void start() {
- // Clear out any previous data
- numJankyFrames = 0;
- mLongestFrameNano = 0;
- mInstrumentation.getUiAutomation().clearWindowAnimationFrameStats();
- }
-
- @Override
- public void stop() {
- stats = mInstrumentation.getUiAutomation().getWindowAnimationFrameStats();
- analyze();
- }
-
- public boolean jankyFramesDetected() {
- return stats.getFrameCount() > 0 && numJankyFrames > 0;
- }
-
- @Override
- public String toString() {
- return stats.toString() +
- " RefreshPeriodNano:" + stats.getRefreshPeriodNano() +
- " NumJankyFrames:" + numJankyFrames +
- " LongestFrameNano:" + mLongestFrameNano;
- }
-} \ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java
deleted file mode 100644
index 11de4aa86343..000000000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import android.os.RemoteException;
-import android.view.IWindowManager;
-import android.view.WindowManagerGlobal;
-
-/**
- * Captures WindowManager trace from WindowManager.
- */
-public class WindowManagerTraceMonitor extends TraceMonitor {
- private IWindowManager mWm = WindowManagerGlobal.getWindowManagerService();
-
- public WindowManagerTraceMonitor() {
- this(OUTPUT_DIR.toString());
- }
-
- public WindowManagerTraceMonitor(String outputDir) {
- super(outputDir, "wm_trace.pb");
- }
-
- @Override
- public void start() {
- try {
- mWm.startWindowTrace();
- } catch (RemoteException e) {
- throw new RuntimeException("Could not start trace", e);
- }
- }
-
- @Override
- public void stop() {
- try {
- mWm.stopWindowTrace();
- } catch (RemoteException e) {
- throw new RuntimeException("Could not stop trace", e);
- }
- }
-
- @Override
- public boolean isEnabled() throws RemoteException{
- return mWm.isWindowTraceEnabled();
- }
-}
diff --git a/tests/FlickerTests/lib/test/AndroidManifest.xml b/tests/FlickerTests/lib/test/AndroidManifest.xml
deleted file mode 100644
index 6451a5710821..000000000000
--- a/tests/FlickerTests/lib/test/AndroidManifest.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright 2018 Google Inc. All Rights Reserved.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.server.wm.flicker">
-
- <uses-sdk android:minSdkVersion="27" android:targetSdkVersion="27"/>
- <!-- Read and write traces from external storage -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- <!-- Capture screen contents -->
- <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
- <!-- Run layers trace -->
- <uses-permission android:name="android.permission.HARDWARE_TEST"/>
- <application android:label="FlickerLibTest">
- <uses-library android:name="android.test.runner"/>
- </application>
-
- <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.server.wm.flicker"
- android:label="WindowManager Flicker Lib Test">
- </instrumentation>
-
-</manifest> \ No newline at end of file
diff --git a/tests/FlickerTests/lib/test/AndroidTest.xml b/tests/FlickerTests/lib/test/AndroidTest.xml
deleted file mode 100644
index e4cc298a2aa8..000000000000
--- a/tests/FlickerTests/lib/test/AndroidTest.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright 2018 Google Inc. All Rights Reserved.
- -->
-<configuration description="Config for WindowManager Flicker Tests">
- <target_preparer class="com.google.android.tradefed.targetprep.GoogleDeviceSetup">
- <!-- keeps the screen on during tests -->
- <option name="screen-always-on" value="on" />
- <!-- prevents the phone from restarting -->
- <option name="force-skip-system-props" value="true" />
- </target_preparer>
- <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
- <option name="cleanup-apks" value="true"/>
- <option name="test-file-name" value="FlickerLibTest.apk"/>
- </target_preparer>
- <test class="com.android.tradefed.testtype.AndroidJUnitTest">
- <option name="package" value="com.android.server.wm.flicker"/>
- <option name="hidden-api-checks" value="false" />
- </test>
-</configuration>
diff --git a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pb b/tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pb
deleted file mode 100644
index 98ee6f3ed269..000000000000
--- a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pb b/tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pb
deleted file mode 100644
index 20572d79d826..000000000000
--- a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pb b/tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pb
deleted file mode 100644
index af4079707c69..000000000000
--- a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pb b/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pb
deleted file mode 100644
index b3f31706f55c..000000000000
--- a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pb b/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pb
deleted file mode 100644
index b3b73ce0518a..000000000000
--- a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java
deleted file mode 100644
index 8e7fe1b4f942..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Contains {@link AssertionsChecker} tests.
- * To run this test: {@code atest FlickerLibTest:AssertionsCheckerTest}
- */
-public class AssertionsCheckerTest {
-
- /**
- * Returns a list of SimpleEntry objects with {@code data} and incremental timestamps starting
- * at 0.
- */
- private static List<SimpleEntry> getTestEntries(int... data) {
- List<SimpleEntry> entries = new ArrayList<>();
- for (int i = 0; i < data.length; i++) {
- entries.add(new SimpleEntry(i, data[i]));
- }
- return entries;
- }
-
- @Test
- public void canCheckAllEntries() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.add(SimpleEntry::isData42, "isData42");
-
- List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
- assertThat(failures).hasSize(5);
- }
-
- @Test
- public void canCheckFirstEntry() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.checkFirstEntry();
- checker.add(SimpleEntry::isData42, "isData42");
-
- List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
- assertThat(failures).hasSize(1);
- assertThat(failures.get(0).timestamp).isEqualTo(0);
- }
-
- @Test
- public void canCheckLastEntry() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.checkLastEntry();
- checker.add(SimpleEntry::isData42, "isData42");
-
- List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
- assertThat(failures).hasSize(1);
- assertThat(failures.get(0).timestamp).isEqualTo(4);
- }
-
- @Test
- public void canCheckRangeOfEntries() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.filterByRange(1, 2);
- checker.add(SimpleEntry::isData42, "isData42");
-
- List<Result> failures = checker.test(getTestEntries(1, 42, 42, 1, 1));
-
- assertThat(failures).hasSize(0);
- }
-
- @Test
- public void emptyRangePasses() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.filterByRange(9, 10);
- checker.add(SimpleEntry::isData42, "isData42");
-
- List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
- assertThat(failures).isEmpty();
- }
-
- @Test
- public void canCheckChangingAssertions() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.add(SimpleEntry::isData42, "isData42");
- checker.add(SimpleEntry::isData0, "isData0");
- checker.checkChangingAssertions();
-
- List<Result> failures = checker.test(getTestEntries(42, 0, 0, 0, 0));
-
- assertThat(failures).isEmpty();
- }
-
- @Test
- public void canCheckChangingAssertions_withNoAssertions() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.checkChangingAssertions();
-
- List<Result> failures = checker.test(getTestEntries(42, 0, 0, 0, 0));
-
- assertThat(failures).isEmpty();
- }
-
- @Test
- public void canCheckChangingAssertions_withSingleAssertion() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.add(SimpleEntry::isData42, "isData42");
- checker.checkChangingAssertions();
-
- List<Result> failures = checker.test(getTestEntries(42, 42, 42, 42, 42));
-
- assertThat(failures).isEmpty();
- }
-
- @Test
- public void canFailCheckChangingAssertions_ifStartingAssertionFails() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.add(SimpleEntry::isData42, "isData42");
- checker.add(SimpleEntry::isData0, "isData0");
- checker.checkChangingAssertions();
-
- List<Result> failures = checker.test(getTestEntries(0, 0, 0, 0, 0));
-
- assertThat(failures).hasSize(1);
- }
-
- @Test
- public void canFailCheckChangingAssertions_ifStartingAssertionAlwaysPasses() {
- AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
- checker.add(SimpleEntry::isData42, "isData42");
- checker.add(SimpleEntry::isData0, "isData0");
- checker.checkChangingAssertions();
-
- List<Result> failures = checker.test(getTestEntries(0, 0, 0, 0, 0));
-
- assertThat(failures).hasSize(1);
- }
-
- static class SimpleEntry implements ITraceEntry {
- long timestamp;
- int data;
-
- SimpleEntry(long timestamp, int data) {
- this.timestamp = timestamp;
- this.data = data;
- }
-
- @Override
- public long getTimestamp() {
- return timestamp;
- }
-
- Result isData42() {
- return new Result(this.data == 42, this.timestamp, "is42", "");
- }
-
- Result isData0() {
- return new Result(this.data == 0, this.timestamp, "is42", "");
- }
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java
deleted file mode 100644
index 7fd178ca6e51..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import org.junit.Test;
-
-/**
- * Contains {@link Assertions} tests.
- * To run this test: {@code atest FlickerLibTest:AssertionsTest}
- */
-public class AssertionsTest {
- @Test
- public void traceEntryAssertionCanNegateResult() {
- Assertions.TraceAssertion<Integer> assertNumEquals42 =
- getIntegerTraceEntryAssertion();
-
- assertThat(assertNumEquals42.apply(1).success).isFalse();
- assertThat(assertNumEquals42.negate().apply(1).success).isTrue();
-
- assertThat(assertNumEquals42.apply(42).success).isTrue();
- assertThat(assertNumEquals42.negate().apply(42).success).isFalse();
- }
-
- @Test
- public void resultCanBeNegated() {
- String reason = "Everything is fine!";
- Result result = new Result(true, 0, "TestAssert", reason);
- Result negatedResult = result.negate();
- assertThat(negatedResult.success).isFalse();
- assertThat(negatedResult.reason).isEqualTo(reason);
- assertThat(negatedResult.assertionName).isEqualTo("!TestAssert");
- }
-
- private Assertions.TraceAssertion<Integer> getIntegerTraceEntryAssertion() {
- return (num) -> {
- if (num == 42) {
- return new Result(true, "Num equals 42");
- }
- return new Result(false, "Num doesn't equal 42, actual:" + num);
- };
- }
-} \ No newline at end of file
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java
deleted file mode 100644
index d06c5d76552b..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.android.server.wm.flicker.LayersTraceSubject.assertThat;
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import static org.junit.Assert.fail;
-
-import android.graphics.Rect;
-
-import org.junit.Test;
-
-import java.nio.file.Paths;
-
-/**
- * Contains {@link LayersTraceSubject} tests.
- * To run this test: {@code atest FlickerLibTest:LayersTraceSubjectTest}
- */
-public class LayersTraceSubjectTest {
- private static final Rect displayRect = new Rect(0, 0, 1440, 2880);
-
- private static LayersTrace readLayerTraceFromFile(String relativePath) {
- try {
- return LayersTrace.parseFrom(readTestFile(relativePath), Paths.get(relativePath));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testCanDetectEmptyRegionFromLayerTrace() {
- LayersTrace layersTraceEntries = readLayerTraceFromFile("layers_trace_emptyregion.pb");
- try {
- assertThat(layersTraceEntries).coversRegion(displayRect).forAllEntries();
- fail("Assertion passed");
- } catch (AssertionError e) {
- assertWithMessage("Contains path to trace")
- .that(e.getMessage()).contains("layers_trace_emptyregion.pb");
- assertWithMessage("Contains timestamp")
- .that(e.getMessage()).contains("0h38m28s8ms");
- assertWithMessage("Contains assertion function")
- .that(e.getMessage()).contains("coversRegion");
- assertWithMessage("Contains debug info")
- .that(e.getMessage()).contains("Region to test: " + displayRect);
- assertWithMessage("Contains debug info")
- .that(e.getMessage()).contains("first empty point: 0, 99");
- }
- }
-
- @Test
- public void testCanDetectIncorrectVisibilityFromLayerTrace() {
- LayersTrace layersTraceEntries = readLayerTraceFromFile(
- "layers_trace_invalid_layer_visibility.pb");
- try {
- assertThat(layersTraceEntries).showsLayer("com.android.server.wm.flicker.testapp")
- .then().hidesLayer("com.android.server.wm.flicker.testapp").forAllEntries();
- fail("Assertion passed");
- } catch (AssertionError e) {
- assertWithMessage("Contains path to trace")
- .that(e.getMessage()).contains("layers_trace_invalid_layer_visibility.pb");
- assertWithMessage("Contains timestamp")
- .that(e.getMessage()).contains("70h13m14s303ms");
- assertWithMessage("Contains assertion function")
- .that(e.getMessage()).contains("!isVisible");
- assertWithMessage("Contains debug info")
- .that(e.getMessage()).contains(
- "com.android.server.wm.flicker.testapp/com.android.server.wm.flicker.testapp"
- + ".SimpleActivity#0 is visible");
- }
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java
deleted file mode 100644
index 7d77126fd7d4..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import static org.junit.Assert.fail;
-
-import android.content.Context;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.view.WindowManager;
-
-import androidx.test.InstrumentationRegistry;
-
-import org.junit.Test;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Contains {@link LayersTrace} tests.
- * To run this test: {@code atest FlickerLibTest:LayersTraceTest}
- */
-public class LayersTraceTest {
- private static LayersTrace readLayerTraceFromFile(String relativePath) {
- try {
- return LayersTrace.parseFrom(readTestFile(relativePath));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private static Rect getDisplayBounds() {
- Point display = new Point();
- WindowManager wm =
- (WindowManager) InstrumentationRegistry.getContext().getSystemService(
- Context.WINDOW_SERVICE);
- wm.getDefaultDisplay().getRealSize(display);
- return new Rect(0, 0, display.x, display.y);
- }
-
- @Test
- public void canParseAllLayers() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- assertThat(trace.getEntries()).isNotEmpty();
- assertThat(trace.getEntries().get(0).getTimestamp()).isEqualTo(2307984557311L);
- assertThat(trace.getEntries().get(trace.getEntries().size() - 1).getTimestamp())
- .isEqualTo(2308521813510L);
- List<LayersTrace.Layer> flattenedLayers = trace.getEntries().get(0).asFlattenedLayers();
- String msg = "Layers:\n" + flattenedLayers.stream().map(layer -> layer.mProto.name)
- .collect(Collectors.joining("\n\t"));
- assertWithMessage(msg).that(flattenedLayers).hasSize(47);
- }
-
- @Test
- public void canParseVisibleLayers() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- assertThat(trace.getEntries()).isNotEmpty();
- assertThat(trace.getEntries().get(0).getTimestamp()).isEqualTo(2307984557311L);
- assertThat(trace.getEntries().get(trace.getEntries().size() - 1).getTimestamp())
- .isEqualTo(2308521813510L);
- List<LayersTrace.Layer> flattenedLayers = trace.getEntries().get(0).asFlattenedLayers();
- List<LayersTrace.Layer> visibleLayers = flattenedLayers.stream()
- .filter(layer -> layer.isVisible() && !layer.isHiddenByParent())
- .collect(Collectors.toList());
-
- String msg = "Visible Layers:\n" + visibleLayers.stream()
- .map(layer -> layer.mProto.name)
- .collect(Collectors.joining("\n\t"));
-
- assertWithMessage(msg).that(visibleLayers).hasSize(9);
- }
-
- @Test
- public void canParseLayerHierarchy() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- assertThat(trace.getEntries()).isNotEmpty();
- assertThat(trace.getEntries().get(0).getTimestamp()).isEqualTo(2307984557311L);
- assertThat(trace.getEntries().get(trace.getEntries().size() - 1).getTimestamp())
- .isEqualTo(2308521813510L);
- List<LayersTrace.Layer> layers = trace.getEntries().get(0).getRootLayers();
- assertThat(layers).hasSize(2);
- assertThat(layers.get(0).mChildren).hasSize(layers.get(0).mProto.children.length);
- assertThat(layers.get(1).mChildren).hasSize(layers.get(1).mProto.children.length);
- }
-
- // b/76099859
- @Test
- public void canDetectOrphanLayers() {
- try {
- readLayerTraceFromFile(
- "layers_trace_orphanlayers.pb");
- fail("Failed to detect orphaned layers.");
- } catch (RuntimeException exception) {
- assertThat(exception.getMessage()).contains(
- "Failed to parse layers trace. Found orphan layers "
- + "with parent layer id:1006 : 49");
- }
- }
-
- // b/75276931
- @Test
- public void canDetectUncoveredRegion() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
- Assertions.Result result = entry.coversRegion(getDisplayBounds());
-
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains("Region to test: Rect(0, 0 - 1440, 2880)");
- assertThat(result.reason).contains("first empty point: 0, 99");
- assertThat(result.reason).contains("visible regions:");
- assertWithMessage("Reason contains list of visible regions")
- .that(result.reason).contains("StatusBar#0Rect(0, 0 - 1440, 98");
- }
-
- // Visible region tests
- @Test
- public void canTestLayerVisibleRegion_layerDoesNotExist() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
- final Rect expectedVisibleRegion = new Rect(0, 0, 1, 1);
- Assertions.Result result = entry.hasVisibleRegion("ImaginaryLayer",
- expectedVisibleRegion);
-
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains("Could not find ImaginaryLayer");
- }
-
- @Test
- public void canTestLayerVisibleRegion_layerDoesNotHaveExpectedVisibleRegion() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- LayersTrace.Entry entry = trace.getEntry(2307993020072L);
-
- final Rect expectedVisibleRegion = new Rect(0, 0, 1, 1);
- Assertions.Result result = entry.hasVisibleRegion("NexusLauncherActivity#2",
- expectedVisibleRegion);
-
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains(
- "Layer com.google.android.apps.nexuslauncher/com.google.android.apps"
- + ".nexuslauncher.NexusLauncherActivity#2 is invisible: activeBuffer=null"
- + " type != ColorLayer flags=1 (FLAG_HIDDEN set) visible region is empty");
- }
-
- @Test
- public void canTestLayerVisibleRegion_layerIsHiddenByParent() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- LayersTrace.Entry entry = trace.getEntry(2308455948035L);
-
- final Rect expectedVisibleRegion = new Rect(0, 0, 1, 1);
- Assertions.Result result = entry.hasVisibleRegion(
- "SurfaceView - com.android.chrome/com.google.android.apps.chrome.Main",
- expectedVisibleRegion);
-
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains(
- "Layer SurfaceView - com.android.chrome/com.google.android.apps.chrome.Main#0 is "
- + "hidden by parent: com.android.chrome/com.google.android.apps.chrome"
- + ".Main#0");
- }
-
- @Test
- public void canTestLayerVisibleRegion_incorrectRegionSize() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
- final Rect expectedVisibleRegion = new Rect(0, 0, 1440, 99);
- Assertions.Result result = entry.hasVisibleRegion(
- "StatusBar",
- expectedVisibleRegion);
-
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains("StatusBar#0 has visible "
- + "region:Rect(0, 0 - 1440, 98) expected:Rect(0, 0 - 1440, 99)");
- }
-
- @Test
- public void canTestLayerVisibleRegion() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_emptyregion.pb");
- LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
- final Rect expectedVisibleRegion = new Rect(0, 0, 1440, 98);
- Assertions.Result result = entry.hasVisibleRegion("StatusBar", expectedVisibleRegion);
-
- assertThat(result.passed()).isTrue();
- }
-
- @Test
- public void canTestLayerVisibleRegion_layerIsNotVisible() {
- LayersTrace trace = readLayerTraceFromFile(
- "layers_trace_invalid_layer_visibility.pb");
- LayersTrace.Entry entry = trace.getEntry(252794268378458L);
-
- Assertions.Result result = entry.isVisible("com.android.server.wm.flicker.testapp");
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains(
- "Layer com.android.server.wm.flicker.testapp/com.android.server.wm.flicker"
- + ".testapp.SimpleActivity#0 is invisible: type != ColorLayer visible "
- + "region is empty");
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java
deleted file mode 100644
index c46175c1a977..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import android.content.Context;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.google.common.io.ByteStreams;
-
-import java.io.InputStream;
-
-/**
- * Helper functions for test file resources.
- */
-class TestFileUtils {
- static byte[] readTestFile(String relativePath) throws Exception {
- Context context = InstrumentationRegistry.getContext();
- InputStream in = context.getResources().getAssets().open("testdata/" + relativePath);
- return ByteStreams.toByteArray(in);
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java
deleted file mode 100644
index 9c5e2059a0e6..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.inOrder;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-import android.os.Environment;
-
-import com.android.server.wm.flicker.TransitionRunner.TransitionBuilder;
-import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
-import com.android.server.wm.flicker.monitor.LayersTraceMonitor;
-import com.android.server.wm.flicker.monitor.ScreenRecorder;
-import com.android.server.wm.flicker.monitor.WindowAnimationFrameStatsMonitor;
-import com.android.server.wm.flicker.monitor.WindowManagerTraceMonitor;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.IOException;
-import java.nio.file.Paths;
-import java.util.List;
-
-/**
- * Contains {@link TransitionRunner} tests.
- * {@code atest FlickerLibTest:TransitionRunnerTest}
- */
-public class TransitionRunnerTest {
- @Mock
- private SimpleUiTransitions mTransitionsMock;
- @Mock
- private ScreenRecorder mScreenRecorderMock;
- @Mock
- private WindowManagerTraceMonitor mWindowManagerTraceMonitorMock;
- @Mock
- private LayersTraceMonitor mLayersTraceMonitorMock;
- @Mock
- private WindowAnimationFrameStatsMonitor mWindowAnimationFrameStatsMonitor;
- @InjectMocks
- private TransitionBuilder mTransitionBuilder;
-
- @Before
- public void init() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void transitionsRunInOrder() {
- TransitionRunner.newBuilder()
- .runBeforeAll(mTransitionsMock::turnOnDevice)
- .runBefore(mTransitionsMock::openApp)
- .run(mTransitionsMock::performMagic)
- .runAfter(mTransitionsMock::closeApp)
- .runAfterAll(mTransitionsMock::cleanUpTracks)
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .build()
- .run();
-
- InOrder orderVerifier = inOrder(mTransitionsMock);
- orderVerifier.verify(mTransitionsMock).turnOnDevice();
- orderVerifier.verify(mTransitionsMock).openApp();
- orderVerifier.verify(mTransitionsMock).performMagic();
- orderVerifier.verify(mTransitionsMock).closeApp();
- orderVerifier.verify(mTransitionsMock).cleanUpTracks();
- }
-
- @Test
- public void canCombineTransitions() {
- TransitionRunner.newBuilder()
- .runBeforeAll(mTransitionsMock::turnOnDevice)
- .runBeforeAll(mTransitionsMock::turnOnDevice)
- .runBefore(mTransitionsMock::openApp)
- .runBefore(mTransitionsMock::openApp)
- .run(mTransitionsMock::performMagic)
- .run(mTransitionsMock::performMagic)
- .runAfter(mTransitionsMock::closeApp)
- .runAfter(mTransitionsMock::closeApp)
- .runAfterAll(mTransitionsMock::cleanUpTracks)
- .runAfterAll(mTransitionsMock::cleanUpTracks)
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .build()
- .run();
-
- final int wantedNumberOfInvocations = 2;
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).turnOnDevice();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).openApp();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).performMagic();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).closeApp();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).cleanUpTracks();
- }
-
- @Test
- public void emptyTransitionPasses() {
- List<TransitionResult> results = TransitionRunner.newBuilder()
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .build()
- .run()
- .getResults();
- assertThat(results).hasSize(1);
- assertThat(results.get(0).layersTraceExists()).isFalse();
- assertThat(results.get(0).windowManagerTraceExists()).isFalse();
- assertThat(results.get(0).screenCaptureVideoExists()).isFalse();
- }
-
- @Test
- public void canRepeatTransitions() {
- final int wantedNumberOfInvocations = 10;
- TransitionRunner.newBuilder()
- .runBeforeAll(mTransitionsMock::turnOnDevice)
- .runBefore(mTransitionsMock::openApp)
- .run(mTransitionsMock::performMagic)
- .runAfter(mTransitionsMock::closeApp)
- .runAfterAll(mTransitionsMock::cleanUpTracks)
- .repeat(wantedNumberOfInvocations)
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .build()
- .run();
- verify(mTransitionsMock).turnOnDevice();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).openApp();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).performMagic();
- verify(mTransitionsMock, times(wantedNumberOfInvocations)).closeApp();
- verify(mTransitionsMock).cleanUpTracks();
- }
-
- private void emptyTask() {
-
- }
-
- @Test
- public void canCaptureWindowManagerTrace() {
- mTransitionBuilder
- .run(this::emptyTask)
- .includeJankyRuns()
- .skipLayersTrace()
- .withTag("mCaptureWmTraceTransitionRunner")
- .build().run();
- InOrder orderVerifier = inOrder(mWindowManagerTraceMonitorMock);
- orderVerifier.verify(mWindowManagerTraceMonitorMock).start();
- orderVerifier.verify(mWindowManagerTraceMonitorMock).stop();
- orderVerifier.verify(mWindowManagerTraceMonitorMock)
- .save("mCaptureWmTraceTransitionRunner", 0);
- verifyNoMoreInteractions(mWindowManagerTraceMonitorMock);
- }
-
- @Test
- public void canCaptureLayersTrace() {
- mTransitionBuilder
- .run(this::emptyTask)
- .includeJankyRuns()
- .skipWindowManagerTrace()
- .withTag("mCaptureLayersTraceTransitionRunner")
- .build().run();
- InOrder orderVerifier = inOrder(mLayersTraceMonitorMock);
- orderVerifier.verify(mLayersTraceMonitorMock).start();
- orderVerifier.verify(mLayersTraceMonitorMock).stop();
- orderVerifier.verify(mLayersTraceMonitorMock)
- .save("mCaptureLayersTraceTransitionRunner", 0);
- verifyNoMoreInteractions(mLayersTraceMonitorMock);
- }
-
- @Test
- public void canRecordEachRun() throws IOException {
- mTransitionBuilder
- .run(this::emptyTask)
- .withTag("mRecordEachRun")
- .recordEachRun()
- .includeJankyRuns()
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .repeat(2)
- .build().run();
- InOrder orderVerifier = inOrder(mScreenRecorderMock);
- orderVerifier.verify(mScreenRecorderMock).start();
- orderVerifier.verify(mScreenRecorderMock).stop();
- orderVerifier.verify(mScreenRecorderMock).save("mRecordEachRun", 0);
- orderVerifier.verify(mScreenRecorderMock).start();
- orderVerifier.verify(mScreenRecorderMock).stop();
- orderVerifier.verify(mScreenRecorderMock).save("mRecordEachRun", 1);
- verifyNoMoreInteractions(mScreenRecorderMock);
- }
-
- @Test
- public void canRecordAllRuns() throws IOException {
- doReturn(Paths.get(Environment.getExternalStorageDirectory().getAbsolutePath(),
- "mRecordAllRuns.mp4")).when(mScreenRecorderMock).save("mRecordAllRuns");
- mTransitionBuilder
- .run(this::emptyTask)
- .recordAllRuns()
- .includeJankyRuns()
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .withTag("mRecordAllRuns")
- .repeat(2)
- .build().run();
- InOrder orderVerifier = inOrder(mScreenRecorderMock);
- orderVerifier.verify(mScreenRecorderMock).start();
- orderVerifier.verify(mScreenRecorderMock).stop();
- orderVerifier.verify(mScreenRecorderMock).save("mRecordAllRuns");
- verifyNoMoreInteractions(mScreenRecorderMock);
- }
-
- @Test
- public void canSkipJankyRuns() {
- doReturn(false).doReturn(true).doReturn(false)
- .when(mWindowAnimationFrameStatsMonitor).jankyFramesDetected();
- List<TransitionResult> results = mTransitionBuilder
- .run(this::emptyTask)
- .skipLayersTrace()
- .skipWindowManagerTrace()
- .repeat(3)
- .build().run().getResults();
- assertThat(results).hasSize(2);
- }
-
- public static class SimpleUiTransitions {
- public void turnOnDevice() {
- }
-
- public void openApp() {
- }
-
- public void performMagic() {
- }
-
- public void closeApp() {
- }
-
- public void cleanUpTracks() {
- }
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java
deleted file mode 100644
index 49278718932c..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Contains {@link WindowManagerTrace} tests.
- * To run this test: {@code atest FlickerLibTest:WindowManagerTraceTest}
- */
-public class WindowManagerTraceTest {
- private WindowManagerTrace mTrace;
-
- private static WindowManagerTrace readWindowManagerTraceFromFile(String relativePath) {
- try {
- return WindowManagerTrace.parseFrom(readTestFile(relativePath));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Before
- public void setup() {
- mTrace = readWindowManagerTraceFromFile("wm_trace_openchrome.pb");
- }
-
- @Test
- public void canParseAllEntries() {
- assertThat(mTrace.getEntries().get(0).getTimestamp()).isEqualTo(241777211939236L);
- assertThat(mTrace.getEntries().get(mTrace.getEntries().size() - 1).getTimestamp()).isEqualTo
- (241779809471942L);
- }
-
- @Test
- public void canDetectAboveAppWindowVisibility() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
- Result result = entry.isAboveAppWindowVisible("NavigationBar");
- assertThat(result.passed()).isTrue();
- }
-
- @Test
- public void canDetectBelowAppWindowVisibility() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
- Result result = entry.isBelowAppWindowVisible("wallpaper");
- assertThat(result.passed()).isTrue();
- }
-
- @Test
- public void canDetectAppWindowVisibility() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
- Result result = entry.isAppWindowVisible("com.google.android.apps.nexuslauncher");
- assertThat(result.passed()).isTrue();
- }
-
- @Test
- public void canFailWithReasonForVisibilityChecks_windowNotFound() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
- Result result = entry.isAboveAppWindowVisible("ImaginaryWindow");
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains("ImaginaryWindow cannot be found");
- }
-
- @Test
- public void canFailWithReasonForVisibilityChecks_windowNotVisible() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
- Result result = entry.isAboveAppWindowVisible("AssistPreviewPanel");
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains("AssistPreviewPanel is invisible");
- }
-
- @Test
- public void canDetectAppZOrder() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241778130296410L);
- Result result = entry.isVisibleAppWindowOnTop("com.google.android.apps.chrome");
- assertThat(result.passed()).isTrue();
- }
-
- @Test
- public void canFailWithReasonForZOrderChecks_windowNotOnTop() {
- WindowManagerTrace.Entry entry = mTrace.getEntry(241778130296410L);
- Result result = entry.isVisibleAppWindowOnTop("com.google.android.apps.nexuslauncher");
- assertThat(result.failed()).isTrue();
- assertThat(result.reason).contains("wanted=com.google.android.apps.nexuslauncher");
- assertThat(result.reason).contains("found=com.android.chrome/"
- + "com.google.android.apps.chrome.Main");
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java
deleted file mode 100644
index d547a188a663..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-import static com.android.server.wm.flicker.WmTraceSubject.assertThat;
-
-import org.junit.Test;
-
-/**
- * Contains {@link WmTraceSubject} tests.
- * To run this test: {@code atest FlickerLibTest:WmTraceSubjectTest}
- */
-public class WmTraceSubjectTest {
- private static WindowManagerTrace readWmTraceFromFile(String relativePath) {
- try {
- return WindowManagerTrace.parseFrom(readTestFile(relativePath));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testCanTransitionInAppWindow() {
- WindowManagerTrace trace = readWmTraceFromFile("wm_trace_openchrome2.pb");
-
- assertThat(trace).showsAppWindowOnTop("com.google.android.apps.nexuslauncher/"
- + ".NexusLauncherActivity").forRange(174684850717208L, 174685957511016L);
- assertThat(trace).showsAppWindowOnTop(
- "com.google.android.apps.nexuslauncher/.NexusLauncherActivity")
- .then()
- .showsAppWindowOnTop("com.android.chrome")
- .forAllEntries();
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java
deleted file mode 100644
index dbd6761a05b0..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto.MAGIC_NUMBER_H;
-import static android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto.MAGIC_NUMBER_L;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto;
-
-import com.google.common.io.Files;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-
-/**
- * Contains {@link LayersTraceMonitor} tests.
- * To run this test: {@code atest FlickerLibTest:LayersTraceMonitorTest}
- */
-public class LayersTraceMonitorTest {
- private LayersTraceMonitor mLayersTraceMonitor;
-
- @Before
- public void setup() {
- mLayersTraceMonitor = new LayersTraceMonitor();
- }
-
- @After
- public void teardown() {
- mLayersTraceMonitor.stop();
- mLayersTraceMonitor.getOutputTraceFilePath("captureLayersTrace").toFile().delete();
- }
-
- @Test
- public void canStartLayersTrace() throws Exception {
- mLayersTraceMonitor.start();
- assertThat(mLayersTraceMonitor.isEnabled()).isTrue();
- }
-
- @Test
- public void canStopLayersTrace() throws Exception {
- mLayersTraceMonitor.start();
- assertThat(mLayersTraceMonitor.isEnabled()).isTrue();
- mLayersTraceMonitor.stop();
- assertThat(mLayersTraceMonitor.isEnabled()).isFalse();
- }
-
- @Test
- public void captureLayersTrace() throws Exception {
- mLayersTraceMonitor.start();
- mLayersTraceMonitor.stop();
- File testFile = mLayersTraceMonitor.save("captureLayersTrace").toFile();
- assertThat(testFile.exists()).isTrue();
- byte[] trace = Files.toByteArray(testFile);
- assertThat(trace.length).isGreaterThan(0);
- LayersTraceFileProto mLayerTraceFileProto = LayersTraceFileProto.parseFrom(trace);
- assertThat(mLayerTraceFileProto.magicNumber).isEqualTo(
- (long) MAGIC_NUMBER_H << 32 | MAGIC_NUMBER_L);
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java
deleted file mode 100644
index e73eecc348f0..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static android.os.SystemClock.sleep;
-
-import static com.android.server.wm.flicker.monitor.ScreenRecorder.DEFAULT_OUTPUT_PATH;
-import static com.android.server.wm.flicker.monitor.ScreenRecorder.getPath;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * Contains {@link ScreenRecorder} tests.
- * To run this test: {@code atest FlickerLibTest:ScreenRecorderTest}
- */
-public class ScreenRecorderTest {
- private static final String TEST_VIDEO_FILENAME = "test.mp4";
- private ScreenRecorder mScreenRecorder;
-
- @Before
- public void setup() {
- mScreenRecorder = new ScreenRecorder();
- }
-
- @After
- public void teardown() {
- DEFAULT_OUTPUT_PATH.toFile().delete();
- getPath(TEST_VIDEO_FILENAME).toFile().delete();
- }
-
- @Test
- public void videoIsRecorded() {
- mScreenRecorder.start();
- sleep(100);
- mScreenRecorder.stop();
- File file = DEFAULT_OUTPUT_PATH.toFile();
- assertThat(file.exists()).isTrue();
- }
-
- @Test
- public void videoCanBeSaved() {
- mScreenRecorder.start();
- sleep(100);
- mScreenRecorder.stop();
- mScreenRecorder.save(TEST_VIDEO_FILENAME);
- File file = getPath(TEST_VIDEO_FILENAME).toFile();
- assertThat(file.exists()).isTrue();
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java
deleted file mode 100644
index f31238477e95..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static com.android.server.wm.flicker.helpers.AutomationUtils.wakeUpAndGoToHomeScreen;
-
-import androidx.test.InstrumentationRegistry;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * Contains {@link WindowAnimationFrameStatsMonitor} tests.
- * To run this test: {@code atest FlickerLibTest:WindowAnimationFrameStatsMonitorTest}
- */
-public class WindowAnimationFrameStatsMonitorTest {
- private WindowAnimationFrameStatsMonitor mWindowAnimationFrameStatsMonitor;
-
- @Before
- public void setup() {
- mWindowAnimationFrameStatsMonitor = new WindowAnimationFrameStatsMonitor(
- InstrumentationRegistry.getInstrumentation());
- wakeUpAndGoToHomeScreen();
- }
-
- // TODO(vishnun)
- @Ignore("Disabled until app-helper libraries are available.")
- @Test
- public void captureWindowAnimationFrameStats() throws Exception {
- mWindowAnimationFrameStatsMonitor.start();
- //AppHelperWrapper.getInstance().getHelper(CHROME).open();
- //AppHelperWrapper.getInstance().getHelper(CHROME).exit();
- mWindowAnimationFrameStatsMonitor.stop();
- }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java
deleted file mode 100644
index 56284d7d516a..000000000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
-
-import static com.android.server.wm.nano.WindowManagerTraceFileProto.MAGIC_NUMBER_H;
-import static com.android.server.wm.nano.WindowManagerTraceFileProto.MAGIC_NUMBER_L;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.nano.WindowManagerTraceFileProto;
-
-import com.google.common.io.Files;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-
-/**
- * Contains {@link WindowManagerTraceMonitor} tests.
- * To run this test: {@code atest FlickerLibTest:WindowManagerTraceMonitorTest}
- */
-public class WindowManagerTraceMonitorTest {
- private WindowManagerTraceMonitor mWindowManagerTraceMonitor;
-
- @Before
- public void setup() {
- mWindowManagerTraceMonitor = new WindowManagerTraceMonitor();
- }
-
- @After
- public void teardown() {
- mWindowManagerTraceMonitor.stop();
- mWindowManagerTraceMonitor.getOutputTraceFilePath("captureWindowTrace").toFile().delete();
- }
-
- @Test
- public void canStartWindowTrace() throws Exception {
- mWindowManagerTraceMonitor.start();
- assertThat(mWindowManagerTraceMonitor.isEnabled()).isTrue();
- }
-
- @Test
- public void canStopWindowTrace() throws Exception {
- mWindowManagerTraceMonitor.start();
- assertThat(mWindowManagerTraceMonitor.isEnabled()).isTrue();
- mWindowManagerTraceMonitor.stop();
- assertThat(mWindowManagerTraceMonitor.isEnabled()).isFalse();
- }
-
- @Test
- public void captureWindowTrace() throws Exception {
- mWindowManagerTraceMonitor.start();
- mWindowManagerTraceMonitor.stop();
- File testFile = mWindowManagerTraceMonitor.save("captureWindowTrace").toFile();
- assertThat(testFile.exists()).isTrue();
- byte[] trace = Files.toByteArray(testFile);
- assertThat(trace.length).isGreaterThan(0);
- WindowManagerTraceFileProto mWindowTraceFileProto = WindowManagerTraceFileProto.parseFrom(
- trace);
- assertThat(mWindowTraceFileProto.magicNumber).isEqualTo(
- (long) MAGIC_NUMBER_H << 32 | MAGIC_NUMBER_L);
- }
-}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java
index b6860cbd8d96..aa591d919cbe 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java
@@ -29,11 +29,15 @@ import android.util.Log;
import android.view.Surface;
import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@@ -44,18 +48,19 @@ import java.util.Collection;
* Cycle through supported app rotations.
* To run this test: {@code atest FlickerTest:ChangeAppRotationTest}
*/
-@RunWith(Parameterized.class)
@LargeTest
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ChangeAppRotationTest extends FlickerTestBase {
- private int beginRotation;
- private int endRotation;
+ private int mBeginRotation;
+ private int mEndRotation;
public ChangeAppRotationTest(String beginRotationName, String endRotationName,
int beginRotation, int endRotation) {
- this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+ this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
- this.beginRotation = beginRotation;
- this.endRotation = endRotation;
+ this.mBeginRotation = beginRotation;
+ this.mEndRotation = endRotation;
}
@Parameters(name = "{0}-{1}")
@@ -77,15 +82,19 @@ public class ChangeAppRotationTest extends FlickerTestBase {
@Before
public void runTransition() {
super.runTransition(
- changeAppRotation(testApp, uiDevice, beginRotation, endRotation).build());
+ changeAppRotation(mTestApp, mUiDevice, mBeginRotation, mEndRotation).build());
}
+ @FlakyTest(bugId = 140855415)
+ @Ignore("Waiting bug feedback")
@Test
public void checkVisibility_navBarWindowIsAlwaysVisible() {
checkResults(result -> assertThat(result)
.showsAboveAppWindow(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
}
+ @FlakyTest(bugId = 140855415)
+ @Ignore("Waiting bug feedback")
@Test
public void checkVisibility_statusBarWindowIsAlwaysVisible() {
checkResults(result -> assertThat(result)
@@ -94,8 +103,8 @@ public class ChangeAppRotationTest extends FlickerTestBase {
@Test
public void checkPosition_navBarLayerRotatesAndScales() {
- Rect startingPos = getNavigationBarPosition(beginRotation);
- Rect endingPos = getNavigationBarPosition(endRotation);
+ Rect startingPos = getNavigationBarPosition(mBeginRotation);
+ Rect endingPos = getNavigationBarPosition(mEndRotation);
checkResults(result -> {
LayersTraceSubject.assertThat(result)
.hasVisibleRegion(NAVIGATION_BAR_WINDOW_TITLE, startingPos)
@@ -108,22 +117,22 @@ public class ChangeAppRotationTest extends FlickerTestBase {
@Test
public void checkPosition_appLayerRotates() {
- Rect startingPos = getAppPosition(beginRotation);
- Rect endingPos = getAppPosition(endRotation);
+ Rect startingPos = getAppPosition(mBeginRotation);
+ Rect endingPos = getAppPosition(mEndRotation);
Log.e(TAG, "startingPos=" + startingPos + " endingPos=" + endingPos);
checkResults(result -> {
LayersTraceSubject.assertThat(result)
- .hasVisibleRegion(testApp.getPackage(), startingPos).inTheBeginning();
+ .hasVisibleRegion(mTestApp.getPackage(), startingPos).inTheBeginning();
LayersTraceSubject.assertThat(result)
- .hasVisibleRegion(testApp.getPackage(), endingPos).atTheEnd();
+ .hasVisibleRegion(mTestApp.getPackage(), endingPos).atTheEnd();
}
);
}
@Test
public void checkPosition_statusBarLayerScales() {
- Rect startingPos = getStatusBarPosition(beginRotation);
- Rect endingPos = getStatusBarPosition(endRotation);
+ Rect startingPos = getStatusBarPosition(mBeginRotation);
+ Rect endingPos = getStatusBarPosition(mEndRotation);
checkResults(result -> {
LayersTraceSubject.assertThat(result)
.hasVisibleRegion(STATUS_BAR_WINDOW_TITLE, startingPos)
@@ -134,12 +143,16 @@ public class ChangeAppRotationTest extends FlickerTestBase {
);
}
+ @FlakyTest(bugId = 140855415)
+ @Ignore("Waiting bug feedback")
@Test
public void checkVisibility_navBarLayerIsAlwaysVisible() {
checkResults(result -> LayersTraceSubject.assertThat(result)
.showsLayer(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
}
+ @FlakyTest(bugId = 140855415)
+ @Ignore("Waiting bug feedback")
@Test
public void checkVisibility_statusBarLayerIsAlwaysVisible() {
checkResults(result -> LayersTraceSubject.assertThat(result)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java
index 6590b86f1499..9deb97726542 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java
@@ -26,8 +26,10 @@ import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test IME window closing back to app window transitions.
@@ -35,6 +37,7 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CloseImeWindowToAppTest extends FlickerTestBase {
private static final String IME_WINDOW_TITLE = "InputMethod";
@@ -44,7 +47,7 @@ public class CloseImeWindowToAppTest extends FlickerTestBase {
@Before
public void runTransition() {
- super.runTransition(editTextLoseFocusToApp(uiDevice)
+ super.runTransition(editTextLoseFocusToApp(mUiDevice)
.includeJankyRuns().build());
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java
index 4771b02000c0..cce5a2a7cc0d 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java
@@ -26,8 +26,10 @@ import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test IME window closing to home transitions.
@@ -35,6 +37,7 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CloseImeWindowToHomeTest extends FlickerTestBase {
private static final String IME_WINDOW_TITLE = "InputMethod";
@@ -44,7 +47,7 @@ public class CloseImeWindowToHomeTest extends FlickerTestBase {
@Before
public void runTransition() {
- super.runTransition(editTextLoseFocusToHome(uiDevice)
+ super.runTransition(editTextLoseFocusToHome(mUiDevice)
.includeJankyRuns().build());
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java
index 5cf2c1cd6827..1d44ea490f25 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java
@@ -67,7 +67,7 @@ class CommonTransitions {
device.setOrientationNatural();
}
// Wait for animation to complete
- sleep(3000);
+ sleep(1000);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
@@ -216,10 +216,10 @@ class CommonTransitions {
static TransitionBuilder resizeSplitScreen(IAppHelper testAppTop, IAppHelper testAppBottom,
UiDevice device, Rational startRatio, Rational stopRatio) {
- String testTag = "resizeSplitScreen_" + testAppTop.getLauncherName() + "_" +
- testAppBottom.getLauncherName() + "_" +
- startRatio.toString().replace("/", ":") + "_to_" +
- stopRatio.toString().replace("/", ":");
+ String testTag = "resizeSplitScreen_" + testAppTop.getLauncherName() + "_"
+ + testAppBottom.getLauncherName() + "_"
+ + startRatio.toString().replace("/", ":") + "_to_"
+ + stopRatio.toString().replace("/", ":");
return TransitionRunner.newBuilder()
.withTag(testTag)
.runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
@@ -231,7 +231,7 @@ class CommonTransitions {
.runBefore(() -> launchSplitScreen(device))
.runBefore(() -> {
UiObject2 snapshot = device.findObject(
- By.res("com.google.android.apps.nexuslauncher", "snapshot"));
+ By.res(device.getLauncherPackageName(), "snapshot"));
snapshot.click();
})
.runBefore(() -> AutomationUtils.resizeSplitScreen(device, startRatio))
@@ -316,4 +316,4 @@ class CommonTransitions {
.runAfterAll(testApp::exit)
.repeat(ITERATIONS);
}
-} \ No newline at end of file
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java
index 61cca0d6b53f..9836655bc013 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java
@@ -22,17 +22,22 @@ import android.util.Rational;
import android.view.Surface;
import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
+import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Tests to help debug individual transitions, capture video recordings and create test cases.
*/
+@LargeTest
@Ignore("Used for debugging transitions used in FlickerTests.")
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DebugTest {
private IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java b/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java
index 8c9d6b4dc7a0..6e8e0c3c76c5 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java
@@ -16,20 +16,23 @@
package com.android.server.wm.flicker;
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
import static com.android.server.wm.flicker.helpers.AutomationUtils.setDefaultWait;
import static com.google.common.truth.Truth.assertWithMessage;
+import android.os.Bundle;
import android.platform.helpers.IAppHelper;
+import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiDevice;
import android.util.Log;
-import androidx.test.InstrumentationRegistry;
-
import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
import org.junit.After;
import org.junit.AfterClass;
+import org.junit.Before;
import java.util.HashMap;
import java.util.List;
@@ -51,10 +54,16 @@ public class FlickerTestBase {
static final String DOCKED_STACK_DIVIDER = "DockedStackDivider";
private static HashMap<String, List<TransitionResult>> transitionResults =
new HashMap<>();
- IAppHelper testApp;
- UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
- private List<TransitionResult> results;
- private TransitionResult lastResult = null;
+ IAppHelper mTestApp;
+ UiDevice mUiDevice;
+ private List<TransitionResult> mResults;
+ private TransitionResult mLastResult = null;
+
+ @Before
+ public void setUp() {
+ InstrumentationRegistry.registerInstance(getInstrumentation(), new Bundle());
+ mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+ }
/**
* Teardown any system settings and clean up test artifacts from the file system.
@@ -91,14 +100,14 @@ public class FlickerTestBase {
*/
void runTransition(TransitionRunner transition) {
if (transitionResults.containsKey(transition.getTestTag())) {
- results = transitionResults.get(transition.getTestTag());
+ mResults = transitionResults.get(transition.getTestTag());
return;
}
- results = transition.run().getResults();
+ mResults = transition.run().getResults();
/* Fail if we don't have any results due to jank */
assertWithMessage("No results to test because all transition runs were invalid because "
- + "of Jank").that(results).isNotEmpty();
- transitionResults.put(transition.getTestTag(), results);
+ + "of Jank").that(mResults).isNotEmpty();
+ transitionResults.put(transition.getTestTag(), mResults);
}
/**
@@ -106,11 +115,11 @@ public class FlickerTestBase {
*/
void checkResults(Consumer<TransitionResult> assertion) {
- for (TransitionResult result : results) {
- lastResult = result;
+ for (TransitionResult result : mResults) {
+ mLastResult = result;
assertion.accept(result);
}
- lastResult = null;
+ mLastResult = null;
}
/**
@@ -119,8 +128,8 @@ public class FlickerTestBase {
*/
@After
public void markArtifactsForSaving() {
- if (lastResult != null) {
- lastResult.flagForSaving();
+ if (mLastResult != null) {
+ mLastResult.flagForSaving();
}
}
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java
index 7818c4e4ba50..8d99054d907e 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java
@@ -21,12 +21,16 @@ import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
import static com.android.server.wm.flicker.WmTraceSubject.assertThat;
import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test cold launch app from launcher.
@@ -34,16 +38,17 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OpenAppColdTest extends FlickerTestBase {
public OpenAppColdTest() {
- this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+ this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
}
@Before
public void runTransition() {
- super.runTransition(getOpenAppCold(testApp, uiDevice).build());
+ super.runTransition(getOpenAppCold(mTestApp, mUiDevice).build());
}
@Test
@@ -61,9 +66,9 @@ public class OpenAppColdTest extends FlickerTestBase {
@Test
public void checkVisibility_wallpaperWindowBecomesInvisible() {
checkResults(result -> assertThat(result)
- .showsBelowAppWindow("wallpaper")
+ .showsBelowAppWindow("Wallpaper")
.then()
- .hidesBelowAppWindow("wallpaper")
+ .hidesBelowAppWindow("Wallpaper")
.forAllEntries());
}
@@ -71,13 +76,15 @@ public class OpenAppColdTest extends FlickerTestBase {
public void checkZOrder_appWindowReplacesLauncherAsTopWindow() {
checkResults(result -> assertThat(result)
.showsAppWindowOnTop(
- "com.google.android.apps.nexuslauncher/.NexusLauncherActivity")
+ "com.android.launcher3/.Launcher")
.then()
- .showsAppWindowOnTop(testApp.getPackage())
+ .showsAppWindowOnTop(mTestApp.getPackage())
.forAllEntries());
}
@Test
+ @FlakyTest(bugId = 141235985)
+ @Ignore("Waiting bug feedback")
public void checkCoveredRegion_noUncoveredRegions() {
checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
getDisplayBounds()).forAllEntries());
@@ -98,9 +105,9 @@ public class OpenAppColdTest extends FlickerTestBase {
@Test
public void checkVisibility_wallpaperLayerBecomesInvisible() {
checkResults(result -> LayersTraceSubject.assertThat(result)
- .showsLayer("wallpaper")
+ .showsLayer("Wallpaper")
.then()
- .hidesLayer("wallpaper")
+ .hidesLayer("Wallpaper")
.forAllEntries());
}
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java
index 63018ec1d9e7..f8b7938901a8 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java
@@ -24,8 +24,10 @@ import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test open app to split screen.
@@ -33,16 +35,17 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OpenAppToSplitScreenTest extends FlickerTestBase {
public OpenAppToSplitScreenTest() {
- this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+ this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
}
@Before
public void runTransition() {
- super.runTransition(appToSplitScreen(testApp, uiDevice).includeJankyRuns().build());
+ super.runTransition(appToSplitScreen(mTestApp, mUiDevice).includeJankyRuns().build());
}
@Test
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java
index 1aba93056c89..e8702c2dfa9f 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java
@@ -21,12 +21,16 @@ import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
import static com.android.server.wm.flicker.WmTraceSubject.assertThat;
import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test warm launch app.
@@ -34,16 +38,17 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OpenAppWarmTest extends FlickerTestBase {
public OpenAppWarmTest() {
- this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+ this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
}
@Before
public void runTransition() {
- super.runTransition(openAppWarm(testApp, uiDevice).build());
+ super.runTransition(openAppWarm(mTestApp, mUiDevice).includeJankyRuns().build());
}
@Test
@@ -61,9 +66,9 @@ public class OpenAppWarmTest extends FlickerTestBase {
@Test
public void checkVisibility_wallpaperBecomesInvisible() {
checkResults(result -> assertThat(result)
- .showsBelowAppWindow("wallpaper")
+ .showsBelowAppWindow("Wallpaper")
.then()
- .hidesBelowAppWindow("wallpaper")
+ .hidesBelowAppWindow("Wallpaper")
.forAllEntries());
}
@@ -71,12 +76,14 @@ public class OpenAppWarmTest extends FlickerTestBase {
public void checkZOrder_appWindowReplacesLauncherAsTopWindow() {
checkResults(result -> assertThat(result)
.showsAppWindowOnTop(
- "com.google.android.apps.nexuslauncher/.NexusLauncherActivity")
+ "com.android.launcher3/.Launcher")
.then()
- .showsAppWindowOnTop(testApp.getPackage())
+ .showsAppWindowOnTop(mTestApp.getPackage())
.forAllEntries());
}
+ @FlakyTest(bugId = 141235985)
+ @Ignore("Waiting bug feedback")
@Test
public void checkCoveredRegion_noUncoveredRegions() {
checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
@@ -98,9 +105,9 @@ public class OpenAppWarmTest extends FlickerTestBase {
@Test
public void checkVisibility_wallpaperLayerBecomesInvisible() {
checkResults(result -> LayersTraceSubject.assertThat(result)
- .showsLayer("wallpaper")
+ .showsLayer("Wallpaper")
.then()
- .hidesLayer("wallpaper")
+ .hidesLayer("Wallpaper")
.forAllEntries());
}
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java
index a81fa8e6d123..9f5cfcedd38f 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java
@@ -23,8 +23,10 @@ import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test IME window opening transitions.
@@ -32,13 +34,14 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OpenImeWindowTest extends FlickerTestBase {
private static final String IME_WINDOW_TITLE = "InputMethod";
@Before
public void runTransition() {
- super.runTransition(editTextSetFocus(uiDevice)
+ super.runTransition(editTextSetFocus(mUiDevice)
.includeJankyRuns().build());
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java
index 50dba81e53b7..1031baf7ec04 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java
@@ -28,12 +28,16 @@ import android.platform.helpers.IAppHelper;
import android.util.Rational;
import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test split screen resizing window transitions.
@@ -41,10 +45,13 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@FlakyTest(bugId = 140856143)
+@Ignore("Waiting bug feedback")
public class ResizeSplitScreenTest extends FlickerTestBase {
public ResizeSplitScreenTest() {
- this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+ this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
}
@@ -53,7 +60,7 @@ public class ResizeSplitScreenTest extends FlickerTestBase {
IAppHelper bottomApp = new StandardAppHelper(InstrumentationRegistry
.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "ImeApp");
- super.runTransition(resizeSplitScreen(testApp, bottomApp, uiDevice, new Rational(1, 3),
+ super.runTransition(resizeSplitScreen(mTestApp, bottomApp, mUiDevice, new Rational(1, 3),
new Rational(2, 3)).includeJankyRuns().build());
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java
index 117ac5a8fadf..ae55a75d7e67 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java
@@ -33,8 +33,10 @@ import androidx.test.InstrumentationRegistry;
import androidx.test.filters.LargeTest;
import org.junit.Before;
+import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@@ -47,6 +49,7 @@ import java.util.Collection;
*/
@LargeTest
@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SeamlessAppRotationTest extends FlickerTestBase {
private int mBeginRotation;
private int mEndRotation;
@@ -105,7 +108,7 @@ public class SeamlessAppRotationTest extends FlickerTestBase {
super.runTransition(
changeAppRotation(mIntent, intentId, InstrumentationRegistry.getContext(),
- uiDevice, mBeginRotation, mEndRotation).repeat(5).build());
+ mUiDevice, mBeginRotation, mEndRotation).repeat(5).build());
}
@Test
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java
index 1d30df9750b2..85a14941a7fd 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java
@@ -25,8 +25,11 @@ import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
/**
* Test open app to split screen.
@@ -34,16 +37,19 @@ import org.junit.runner.RunWith;
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@FlakyTest(bugId = 140856143)
+@Ignore("Waiting bug feedback")
public class SplitScreenToLauncherTest extends FlickerTestBase {
public SplitScreenToLauncherTest() {
- this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+ this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
"com.android.server.wm.flicker.testapp", "SimpleApp");
}
@Before
public void runTransition() {
- super.runTransition(splitScreenToLauncher(testApp, uiDevice).includeJankyRuns().build());
+ super.runTransition(splitScreenToLauncher(mTestApp, mUiDevice).includeJankyRuns().build());
}
@Test
@@ -62,13 +68,12 @@ public class SplitScreenToLauncherTest extends FlickerTestBase {
.forAllEntries());
}
- @FlakyTest(bugId = 79686616)
@Test
public void checkVisibility_appLayerBecomesInVisible() {
checkResults(result -> LayersTraceSubject.assertThat(result)
- .showsLayer(testApp.getPackage())
+ .showsLayer(mTestApp.getPackage())
.then()
- .hidesLayer(testApp.getPackage())
+ .hidesLayer(mTestApp.getPackage())
.forAllEntries());
}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java b/tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java
deleted file mode 100644
index 79a0220e0e87..000000000000
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.wm.flicker;
-
-import android.app.Instrumentation;
-import android.platform.helpers.AbstractStandardAppHelper;
-
-/**
- * Class to take advantage of {@code IAppHelper} interface so the same test can be run against
- * first party and third party apps.
- */
-public class StandardAppHelper extends AbstractStandardAppHelper {
- private final String mPackageName;
- private final String mLauncherName;
-
- public StandardAppHelper(Instrumentation instr, String packageName, String launcherName) {
- super(instr);
- mPackageName = packageName;
- mLauncherName = launcherName;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getPackage() {
- return mPackageName;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getLauncherName() {
- return mLauncherName;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void dismissInitialDialogs() {
-
- }
-}
diff --git a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java
index 3a0c1c9382fe..5cf81cb90fbc 100644
--- a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java
+++ b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java
@@ -17,7 +17,6 @@
package com.android.server.wm.flicker.testapp;
import static android.os.SystemClock.sleep;
-import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
import static com.android.server.wm.flicker.testapp.ActivityOptions.EXTRA_STARVE_UI_THREAD;
@@ -39,8 +38,8 @@ public class SeamlessRotationActivity extends Activity {
super.onCreate(savedInstanceState);
enableSeamlessRotation();
setContentView(R.layout.activity_simple);
- boolean starveUiThread = getIntent().getExtras() != null &&
- getIntent().getExtras().getBoolean(EXTRA_STARVE_UI_THREAD);
+ boolean starveUiThread = getIntent().getExtras() != null
+ && getIntent().getExtras().getBoolean(EXTRA_STARVE_UI_THREAD);
if (starveUiThread) {
starveUiThread();
}
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index f2f258a737e3..9e21db76be84 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -504,6 +504,8 @@ public class ConnectivityServiceTest {
// Waits for the NetworkAgent to be registered, which includes the creation of the
// NetworkMonitor.
waitForIdle(TIMEOUT_MS);
+ HandlerUtilsKt.waitForIdle(mCsHandlerThread, TIMEOUT_MS);
+ HandlerUtilsKt.waitForIdle(ConnectivityThread.get(), TIMEOUT_MS);
}
@Override
@@ -4315,16 +4317,16 @@ public class ConnectivityServiceTest {
assertFalse(mCm.isNetworkSupported(TYPE_NONE));
assertThrows(IllegalArgumentException.class,
- () -> { mCm.networkCapabilitiesForType(TYPE_NONE); });
+ () -> mCm.networkCapabilitiesForType(TYPE_NONE));
Class<UnsupportedOperationException> unsupported = UnsupportedOperationException.class;
- assertThrows(unsupported, () -> { mCm.startUsingNetworkFeature(TYPE_WIFI, ""); });
- assertThrows(unsupported, () -> { mCm.stopUsingNetworkFeature(TYPE_WIFI, ""); });
+ assertThrows(unsupported, () -> mCm.startUsingNetworkFeature(TYPE_WIFI, ""));
+ assertThrows(unsupported, () -> mCm.stopUsingNetworkFeature(TYPE_WIFI, ""));
// TODO: let test context have configuration application target sdk version
// and test that pre-M requesting for TYPE_NONE sends back APN_REQUEST_FAILED
- assertThrows(unsupported, () -> { mCm.startUsingNetworkFeature(TYPE_NONE, ""); });
- assertThrows(unsupported, () -> { mCm.stopUsingNetworkFeature(TYPE_NONE, ""); });
- assertThrows(unsupported, () -> { mCm.requestRouteToHostAddress(TYPE_NONE, null); });
+ assertThrows(unsupported, () -> mCm.startUsingNetworkFeature(TYPE_NONE, ""));
+ assertThrows(unsupported, () -> mCm.stopUsingNetworkFeature(TYPE_NONE, ""));
+ assertThrows(unsupported, () -> mCm.requestRouteToHostAddress(TYPE_NONE, null));
}
@Test
diff --git a/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt b/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt
index 5c921612df45..cb2950802c5d 100644
--- a/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt
@@ -20,6 +20,7 @@ import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.ImportDeclaration
import com.github.javaparser.ast.expr.BinaryExpr
import com.github.javaparser.ast.expr.Expression
+import com.github.javaparser.ast.expr.MethodCallExpr
import com.github.javaparser.ast.expr.StringLiteralExpr
object CodeUtils {
@@ -27,8 +28,9 @@ object CodeUtils {
* Returns a stable hash of a string.
* We reimplement String::hashCode() for readability reasons.
*/
- fun hash(str: String, level: LogLevel): Int {
- return (level.name + str).map { c -> c.toInt() }.reduce { h, c -> h * 31 + c }
+ fun hash(position: String, messageString: String, logLevel: LogLevel, logGroup: LogGroup): Int {
+ return (position + messageString + logLevel.name + logGroup.name)
+ .map { c -> c.toInt() }.reduce { h, c -> h * 31 + c }
}
fun isWildcardStaticImported(code: CompilationUnit, className: String): Boolean {
@@ -71,4 +73,11 @@ object CodeUtils {
"or concatenation of string literals.", expr)
}
}
+
+ fun getPositionString(call: MethodCallExpr, fileName: String): String {
+ return when {
+ call.range.isPresent -> "$fileName:${call.range.get().begin.line}"
+ else -> fileName
+ }
+ }
}
diff --git a/tools/protologtool/src/com/android/protolog/tool/Constants.kt b/tools/protologtool/src/com/android/protolog/tool/Constants.kt
index 83b3c00ebc28..aa3e00f2f4db 100644
--- a/tools/protologtool/src/com/android/protolog/tool/Constants.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/Constants.kt
@@ -19,6 +19,6 @@ package com.android.protolog.tool
object Constants {
const val NAME = "protologtool"
const val VERSION = "1.0.0"
- const val IS_LOG_TO_ANY_METHOD = "isLogToAny"
+ const val IS_ENABLED_METHOD = "isEnabled"
const val ENUM_VALUES_METHOD = "values"
}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt b/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
index 9678ec3a02ba..53834a69ef9f 100644
--- a/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
@@ -49,14 +49,14 @@ object ProtoLogTool {
val file = File(path)
val text = file.readText()
val code = StaticJavaParser.parse(text)
+ val pack = if (code.packageDeclaration.isPresent) code.packageDeclaration
+ .get().nameAsString else ""
+ val newPath = pack.replace('.', '/') + '/' + file.name
val outSrc = when {
containsProtoLogText(text, command.protoLogClassNameArg) ->
- transformer.processClass(text, code)
+ transformer.processClass(text, newPath, code)
else -> text
}
- val pack = if (code.packageDeclaration.isPresent) code.packageDeclaration
- .get().nameAsString else ""
- val newPath = pack.replace('.', '/') + '/' + file.name
outJar.putNextEntry(ZipEntry(newPath))
outJar.write(outSrc.toByteArray())
outJar.closeEntry()
@@ -76,7 +76,11 @@ object ProtoLogTool {
val file = File(path)
val text = file.readText()
if (containsProtoLogText(text, command.protoLogClassNameArg)) {
- builder.processClass(StaticJavaParser.parse(text))
+ val code = StaticJavaParser.parse(text)
+ val pack = if (code.packageDeclaration.isPresent) code.packageDeclaration
+ .get().nameAsString else ""
+ val newPath = pack.replace('.', '/') + '/' + file.name
+ builder.processClass(code, newPath)
}
}
val out = FileOutputStream(command.viewerConfigJsonArg)
diff --git a/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt b/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt
index c3920780b22a..3f38bc01fc7c 100644
--- a/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt
@@ -16,7 +16,7 @@
package com.android.protolog.tool
-import com.android.protolog.tool.Constants.IS_LOG_TO_ANY_METHOD
+import com.android.protolog.tool.Constants.IS_ENABLED_METHOD
import com.android.server.protolog.common.LogDataType
import com.github.javaparser.StaticJavaParser
import com.github.javaparser.ast.CompilationUnit
@@ -73,7 +73,8 @@ class SourceTransformer(
}
val ifStmt: IfStmt
if (group.enabled) {
- val hash = CodeUtils.hash(messageString, level)
+ val position = CodeUtils.getPositionString(call, fileName)
+ val hash = CodeUtils.hash(position, messageString, level, group)
val newCall = call.clone()
if (!group.textEnabled) {
// Remove message string if text logging is not enabled by default.
@@ -90,12 +91,12 @@ class SourceTransformer(
// Out: ProtoLog.e(GROUP, 1234, 0, null, arg)
newCall.arguments.add(2, IntegerLiteralExpr(typeMask))
// Replace call to a stub method with an actual implementation.
- // Out: com.android.server.wm.ProtoLogImpl.e(GROUP, 1234, null, arg)
+ // Out: com.android.server.protolog.ProtoLogImpl.e(GROUP, 1234, null, arg)
newCall.setScope(protoLogImplClassNode)
- // Create a call to GROUP.isLogAny()
- // Out: GROUP.isLogAny()
- val isLogAnyExpr = MethodCallExpr(newCall.arguments[0].clone(),
- SimpleName(IS_LOG_TO_ANY_METHOD))
+ // Create a call to ProtoLogImpl.isEnabled(GROUP)
+ // Out: com.android.server.protolog.ProtoLogImpl.isEnabled(GROUP)
+ val isLogEnabled = MethodCallExpr(protoLogImplClassNode, IS_ENABLED_METHOD,
+ NodeList<Expression>(newCall.arguments[0].clone()))
if (argTypes.size != call.arguments.size - 2) {
throw InvalidProtoLogCallException(
"Number of arguments does not mach format string", call)
@@ -120,11 +121,11 @@ class SourceTransformer(
}
blockStmt.addStatement(ExpressionStmt(newCall))
// Create an IF-statement with the previously created condition.
- // Out: if (GROUP.isLogAny()) {
+ // Out: if (com.android.server.protolog.ProtoLogImpl.isEnabled(GROUP)) {
// long protoLogParam0 = arg;
- // com.android.server.wm.ProtoLogImpl.e(GROUP, 1234, 0, null, protoLogParam0);
+ // com.android.server.protolog.ProtoLogImpl.e(GROUP, 1234, 0, null, protoLogParam0);
// }
- ifStmt = IfStmt(isLogAnyExpr, blockStmt, null)
+ ifStmt = IfStmt(isLogEnabled, blockStmt, null)
} else {
// Surround with if (false).
val newCall = parentStmt.clone()
@@ -212,12 +213,15 @@ class SourceTransformer(
StaticJavaParser.parseExpression<FieldAccessExpr>(protoLogImplClassName)
private var processedCode: MutableList<String> = mutableListOf()
private var offsets: IntArray = IntArray(0)
+ private var fileName: String = ""
fun processClass(
code: String,
+ path: String,
compilationUnit: CompilationUnit =
StaticJavaParser.parse(code)
): String {
+ fileName = path
processedCode = code.split('\n').toMutableList()
offsets = IntArray(processedCode.size)
LexicalPreservingPrinter.setup(compilationUnit)
diff --git a/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt b/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt
index a75b5c9bbe4b..4c4179768b7f 100644
--- a/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt
@@ -32,24 +32,28 @@ class ViewerConfigBuilder(
group: LogGroup
) {
if (group.enabled) {
- val key = CodeUtils.hash(messageString, level)
+ val position = CodeUtils.getPositionString(call, fileName)
+ val key = CodeUtils.hash(position, messageString, level, group)
if (statements.containsKey(key)) {
- if (statements[key] != Triple(messageString, level, group)) {
+ if (statements[key] != LogCall(messageString, level, group, position)) {
throw HashCollisionException(
"Please modify the log message \"$messageString\" " +
"or \"${statements[key]}\" - their hashes are equal.")
}
} else {
groups.add(group)
- statements[key] = Triple(messageString, level, group)
+ statements[key] = LogCall(messageString, level, group, position)
+ call.range.isPresent
}
}
}
- private val statements: MutableMap<Int, Triple<String, LogLevel, LogGroup>> = mutableMapOf()
+ private val statements: MutableMap<Int, LogCall> = mutableMapOf()
private val groups: MutableSet<LogGroup> = mutableSetOf()
+ private var fileName: String = ""
- fun processClass(unit: CompilationUnit) {
+ fun processClass(unit: CompilationUnit, fileName: String) {
+ this.fileName = fileName
protoLogCallVisitor.process(unit, this)
}
@@ -66,11 +70,13 @@ class ViewerConfigBuilder(
writer.name(key.toString())
writer.beginObject()
writer.name("message")
- writer.value(value.first)
+ writer.value(value.messageString)
writer.name("level")
- writer.value(value.second.name)
+ writer.value(value.logLevel.name)
writer.name("group")
- writer.value(value.third.name)
+ writer.value(value.logGroup.name)
+ writer.name("at")
+ writer.value(value.position)
writer.endObject()
}
writer.endObject()
@@ -88,4 +94,11 @@ class ViewerConfigBuilder(
stringWriter.buffer.append('\n')
return stringWriter.toString()
}
+
+ data class LogCall(
+ val messageString: String,
+ val logLevel: LogLevel,
+ val logGroup: LogGroup,
+ val position: String
+ )
}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt b/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt
index 337ed995891c..0acbc9074857 100644
--- a/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt
+++ b/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt
@@ -27,17 +27,32 @@ import org.junit.Test
class CodeUtilsTest {
@Test
fun hash() {
- assertEquals(-1704685243, CodeUtils.hash("test", LogLevel.DEBUG))
+ assertEquals(-1259556708, CodeUtils.hash("Test.java:50", "test",
+ LogLevel.DEBUG, LogGroup("test", true, true, "TAG")))
+ }
+
+ @Test
+ fun hash_changeLocation() {
+ assertEquals(15793504, CodeUtils.hash("Test.java:10", "test2",
+ LogLevel.DEBUG, LogGroup("test", true, true, "TAG")))
}
@Test
fun hash_changeLevel() {
- assertEquals(-1176900998, CodeUtils.hash("test", LogLevel.ERROR))
+ assertEquals(-731772463, CodeUtils.hash("Test.java:50", "test",
+ LogLevel.ERROR, LogGroup("test", true, true, "TAG")))
}
@Test
fun hash_changeMessage() {
- assertEquals(-1305634931, CodeUtils.hash("test2", LogLevel.DEBUG))
+ assertEquals(-2026343204, CodeUtils.hash("Test.java:50", "test2",
+ LogLevel.DEBUG, LogGroup("test", true, true, "TAG")))
+ }
+
+ @Test
+ fun hash_changeGroup() {
+ assertEquals(1607870166, CodeUtils.hash("Test.java:50", "test2",
+ LogLevel.DEBUG, LogGroup("test2", true, true, "TAG")))
}
@Test
diff --git a/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt b/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt
index d6e4a36dc3da..f221fbd216b9 100644
--- a/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt
+++ b/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt
@@ -78,7 +78,7 @@ class SourceTransformerTest {
class Test {
void test() {
- if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); }
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1922613844, 9, "test %d %f", protoLogParam0, protoLogParam1); }
}
}
""".trimIndent()
@@ -88,7 +88,7 @@ class SourceTransformerTest {
class Test {
void test() {
- if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, -986393606, 9, "test %d %f " + "abc %s\n test", protoLogParam0, protoLogParam1, protoLogParam2);
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, 805272208, 9, "test %d %f " + "abc %s\n test", protoLogParam0, protoLogParam1, protoLogParam2);
}
}
@@ -100,8 +100,8 @@ class SourceTransformerTest {
class Test {
void test() {
- if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); } /* ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); */ if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); }
- if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); }
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1922613844, 9, "test %d %f", protoLogParam0, protoLogParam1); } /* ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); */ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1922613844, 9, "test %d %f", protoLogParam0, protoLogParam1); }
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, -154595499, 9, "test %d %f", protoLogParam0, protoLogParam1); }
}
}
""".trimIndent()
@@ -111,7 +111,7 @@ class SourceTransformerTest {
class Test {
void test() {
- if (TEST_GROUP.isLogToAny()) { org.example.ProtoLogImpl.w(TEST_GROUP, 1282022424, 0, "test", (Object[]) null); }
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { org.example.ProtoLogImpl.w(TEST_GROUP, 1913810354, 0, "test", (Object[]) null); }
}
}
""".trimIndent()
@@ -121,7 +121,7 @@ class SourceTransformerTest {
class Test {
void test() {
- if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, null, protoLogParam0, protoLogParam1); }
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1922613844, 9, null, protoLogParam0, protoLogParam1); }
}
}
""".trimIndent()
@@ -131,7 +131,7 @@ class SourceTransformerTest {
class Test {
void test() {
- if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, -986393606, 9, null, protoLogParam0, protoLogParam1, protoLogParam2);
+ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, 805272208, 9, null, protoLogParam0, protoLogParam1, protoLogParam2);
}
}
@@ -160,10 +160,13 @@ class SourceTransformerTest {
}
""".trimIndent()
/* ktlint-enable max-line-length */
+
+ private const val PATH = "com.example.Test.java"
}
private val processor: ProtoLogCallProcessor = Mockito.mock(ProtoLogCallProcessor::class.java)
- private val sourceJarWriter = SourceTransformer("org.example.ProtoLogImpl", processor)
+ private val implPath = "org.example.ProtoLogImpl"
+ private val sourceJarWriter = SourceTransformer(implPath, processor)
private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
@@ -181,13 +184,13 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE, code)
+ val out = sourceJarWriter.processClass(TEST_CODE, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
assertEquals(1, ifStmts.size)
val ifStmt = ifStmts[0]
- assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
+ assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
ifStmt.condition.toString())
assertFalse(ifStmt.elseStmt.isPresent)
assertEquals(3, ifStmt.thenStmt.childNodes.size)
@@ -196,7 +199,7 @@ class SourceTransformerTest {
assertEquals("w", methodCall.name.asString())
assertEquals(6, methodCall.arguments.size)
assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
- assertEquals("835524026", methodCall.arguments[1].toString())
+ assertEquals("1922613844", methodCall.arguments[1].toString())
assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
assertEquals("\"test %d %f\"", methodCall.arguments[3].toString())
assertEquals("protoLogParam0", methodCall.arguments[4].toString())
@@ -223,13 +226,13 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE_MULTICALLS, code)
+ val out = sourceJarWriter.processClass(TEST_CODE_MULTICALLS, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
assertEquals(3, ifStmts.size)
val ifStmt = ifStmts[1]
- assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
+ assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
ifStmt.condition.toString())
assertFalse(ifStmt.elseStmt.isPresent)
assertEquals(3, ifStmt.thenStmt.childNodes.size)
@@ -238,7 +241,7 @@ class SourceTransformerTest {
assertEquals("w", methodCall.name.asString())
assertEquals(6, methodCall.arguments.size)
assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
- assertEquals("835524026", methodCall.arguments[1].toString())
+ assertEquals("1922613844", methodCall.arguments[1].toString())
assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
assertEquals("\"test %d %f\"", methodCall.arguments[3].toString())
assertEquals("protoLogParam0", methodCall.arguments[4].toString())
@@ -261,13 +264,13 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, code)
+ val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
assertEquals(1, ifStmts.size)
val ifStmt = ifStmts[0]
- assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
+ assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
ifStmt.condition.toString())
assertFalse(ifStmt.elseStmt.isPresent)
assertEquals(4, ifStmt.thenStmt.childNodes.size)
@@ -276,7 +279,7 @@ class SourceTransformerTest {
assertEquals("w", methodCall.name.asString())
assertEquals(7, methodCall.arguments.size)
assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
- assertEquals("-986393606", methodCall.arguments[1].toString())
+ assertEquals("805272208", methodCall.arguments[1].toString())
assertEquals(0b001001.toString(), methodCall.arguments[2].toString())
assertEquals("protoLogParam0", methodCall.arguments[4].toString())
assertEquals("protoLogParam1", methodCall.arguments[5].toString())
@@ -298,13 +301,13 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE_NO_PARAMS, code)
+ val out = sourceJarWriter.processClass(TEST_CODE_NO_PARAMS, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
assertEquals(1, ifStmts.size)
val ifStmt = ifStmts[0]
- assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
+ assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
ifStmt.condition.toString())
assertFalse(ifStmt.elseStmt.isPresent)
assertEquals(1, ifStmt.thenStmt.childNodes.size)
@@ -313,7 +316,7 @@ class SourceTransformerTest {
assertEquals("w", methodCall.name.asString())
assertEquals(5, methodCall.arguments.size)
assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
- assertEquals("1282022424", methodCall.arguments[1].toString())
+ assertEquals("1913810354", methodCall.arguments[1].toString())
assertEquals(0.toString(), methodCall.arguments[2].toString())
assertEquals(TRANSFORMED_CODE_NO_PARAMS, out)
}
@@ -332,13 +335,13 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE, code)
+ val out = sourceJarWriter.processClass(TEST_CODE, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
assertEquals(1, ifStmts.size)
val ifStmt = ifStmts[0]
- assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
+ assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
ifStmt.condition.toString())
assertFalse(ifStmt.elseStmt.isPresent)
assertEquals(3, ifStmt.thenStmt.childNodes.size)
@@ -347,7 +350,7 @@ class SourceTransformerTest {
assertEquals("w", methodCall.name.asString())
assertEquals(6, methodCall.arguments.size)
assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
- assertEquals("835524026", methodCall.arguments[1].toString())
+ assertEquals("1922613844", methodCall.arguments[1].toString())
assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
assertEquals("null", methodCall.arguments[3].toString())
assertEquals("protoLogParam0", methodCall.arguments[4].toString())
@@ -370,13 +373,13 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, code)
+ val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
assertEquals(1, ifStmts.size)
val ifStmt = ifStmts[0]
- assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
+ assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
ifStmt.condition.toString())
assertFalse(ifStmt.elseStmt.isPresent)
assertEquals(4, ifStmt.thenStmt.childNodes.size)
@@ -385,7 +388,7 @@ class SourceTransformerTest {
assertEquals("w", methodCall.name.asString())
assertEquals(7, methodCall.arguments.size)
assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
- assertEquals("-986393606", methodCall.arguments[1].toString())
+ assertEquals("805272208", methodCall.arguments[1].toString())
assertEquals(0b001001.toString(), methodCall.arguments[2].toString())
assertEquals("null", methodCall.arguments[3].toString())
assertEquals("protoLogParam0", methodCall.arguments[4].toString())
@@ -408,7 +411,7 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE, code)
+ val out = sourceJarWriter.processClass(TEST_CODE, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
@@ -433,7 +436,7 @@ class SourceTransformerTest {
invocation.arguments[0] as CompilationUnit
}
- val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, code)
+ val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, PATH, code)
code = StaticJavaParser.parse(out)
val ifStmts = code.findAll(IfStmt::class.java)
diff --git a/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt b/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt
index f435d4065256..d3f8c767e8b1 100644
--- a/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt
+++ b/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt
@@ -31,6 +31,10 @@ class ViewerConfigBuilderTest {
private val TEST1 = ViewerConfigParser.ConfigEntry("test1", LogLevel.INFO.name, TAG1)
private val TEST2 = ViewerConfigParser.ConfigEntry("test2", LogLevel.DEBUG.name, TAG2)
private val TEST3 = ViewerConfigParser.ConfigEntry("test3", LogLevel.ERROR.name, TAG2)
+ private val GROUP1 = LogGroup("TEST_GROUP", true, true, TAG1)
+ private val GROUP2 = LogGroup("DEBUG_GROUP", true, true, TAG2)
+ private val GROUP3 = LogGroup("DEBUG_GROUP", true, true, TAG2)
+ private const val PATH = "/tmp/test.java"
}
private val processor: ProtoLogCallProcessor = Mockito.mock(ProtoLogCallProcessor::class.java)
@@ -50,25 +54,25 @@ class ViewerConfigBuilderTest {
val visitor = invocation.arguments[1] as ProtoLogCallVisitor
visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
- LogGroup("TEST_GROUP", true, true, TAG1))
+ GROUP1)
visitor.processCall(MethodCallExpr(), TEST2.messageString, LogLevel.DEBUG,
- LogGroup("DEBUG_GROUP", true, true, TAG2))
+ GROUP2)
visitor.processCall(MethodCallExpr(), TEST3.messageString, LogLevel.ERROR,
- LogGroup("DEBUG_GROUP", true, true, TAG2))
+ GROUP3)
invocation.arguments[0] as CompilationUnit
}
- configBuilder.processClass(dummyCompilationUnit)
+ configBuilder.processClass(dummyCompilationUnit, PATH)
val parsedConfig = parseConfig(configBuilder.build())
assertEquals(3, parsedConfig.size)
- assertEquals(TEST1, parsedConfig[CodeUtils.hash(TEST1.messageString,
- LogLevel.INFO)])
- assertEquals(TEST2, parsedConfig[CodeUtils.hash(TEST2.messageString,
- LogLevel.DEBUG)])
- assertEquals(TEST3, parsedConfig[CodeUtils.hash(TEST3.messageString,
- LogLevel.ERROR)])
+ assertEquals(TEST1, parsedConfig[CodeUtils.hash(PATH,
+ TEST1.messageString, LogLevel.INFO, GROUP1)])
+ assertEquals(TEST2, parsedConfig[CodeUtils.hash(PATH, TEST2.messageString,
+ LogLevel.DEBUG, GROUP2)])
+ assertEquals(TEST3, parsedConfig[CodeUtils.hash(PATH, TEST3.messageString,
+ LogLevel.ERROR, GROUP3)])
}
@Test
@@ -78,20 +82,21 @@ class ViewerConfigBuilderTest {
val visitor = invocation.arguments[1] as ProtoLogCallVisitor
visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
- LogGroup("TEST_GROUP", true, true, TAG1))
+ GROUP1)
visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
- LogGroup("TEST_GROUP", true, true, TAG1))
+ GROUP1)
visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
- LogGroup("TEST_GROUP", true, true, TAG1))
+ GROUP1)
invocation.arguments[0] as CompilationUnit
}
- configBuilder.processClass(dummyCompilationUnit)
+ configBuilder.processClass(dummyCompilationUnit, PATH)
val parsedConfig = parseConfig(configBuilder.build())
assertEquals(1, parsedConfig.size)
- assertEquals(TEST1, parsedConfig[CodeUtils.hash(TEST1.messageString, LogLevel.INFO)])
+ assertEquals(TEST1, parsedConfig[CodeUtils.hash(PATH, TEST1.messageString,
+ LogLevel.INFO, GROUP1)])
}
@Test
@@ -101,7 +106,7 @@ class ViewerConfigBuilderTest {
val visitor = invocation.arguments[1] as ProtoLogCallVisitor
visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
- LogGroup("TEST_GROUP", true, true, TAG1))
+ GROUP1)
visitor.processCall(MethodCallExpr(), TEST2.messageString, LogLevel.DEBUG,
LogGroup("DEBUG_GROUP", false, true, TAG2))
visitor.processCall(MethodCallExpr(), TEST3.messageString, LogLevel.ERROR,
@@ -110,11 +115,13 @@ class ViewerConfigBuilderTest {
invocation.arguments[0] as CompilationUnit
}
- configBuilder.processClass(dummyCompilationUnit)
+ configBuilder.processClass(dummyCompilationUnit, PATH)
val parsedConfig = parseConfig(configBuilder.build())
assertEquals(2, parsedConfig.size)
- assertEquals(TEST1, parsedConfig[CodeUtils.hash(TEST1.messageString, LogLevel.INFO)])
- assertEquals(TEST3, parsedConfig[CodeUtils.hash(TEST3.messageString, LogLevel.ERROR)])
+ assertEquals(TEST1, parsedConfig[CodeUtils.hash(PATH, TEST1.messageString,
+ LogLevel.INFO, GROUP1)])
+ assertEquals(TEST3, parsedConfig[CodeUtils.hash(PATH, TEST3.messageString,
+ LogLevel.ERROR, LogGroup("DEBUG_GROUP", true, false, TAG2))])
}
}
diff --git a/tools/validatekeymaps/Main.cpp b/tools/validatekeymaps/Main.cpp
index 56a242f1daaf..5ac9dfd2a557 100644
--- a/tools/validatekeymaps/Main.cpp
+++ b/tools/validatekeymaps/Main.cpp
@@ -137,7 +137,6 @@ static bool validateFile(const char* filename) {
}
}
- log("No errors.\n\n");
return true;
}