From 26743a54cad2aec2262f161bc8cc3e55ff20bc62 Mon Sep 17 00:00:00 2001 From: Krzysztof KosiƄski Date: Thu, 11 Jul 2024 08:28:29 +0000 Subject: Delete code for legacy VR services. These services were last present on the Pixel 3. Bug: 234559097 Test: presubmit Flag: EXEMPT dead code removal Change-Id: I7bac2eeeb77bea8c048fcbe5f9ed872a039edc9c --- cmds/atrace/Android.bp | 1 - cmds/atrace/atrace.cpp | 21 - libs/gui/Android.bp | 2 - libs/ui/include/ui/BufferHubDefs.h | 184 -- libs/vr/.clang-format | 5 - libs/vr/Android.bp | 14 - libs/vr/CPPLINT.cfg | 2 - libs/vr/OWNERS | 4 - libs/vr/libbroadcastring/Android.bp | 43 - libs/vr/libbroadcastring/broadcast_ring_test.cc | 866 ------- .../include/libbroadcastring/broadcast_ring.h | 692 ------ libs/vr/libbufferhub/Android.bp | 83 - libs/vr/libbufferhub/buffer_hub-test.cpp | 906 ------- libs/vr/libbufferhub/buffer_hub_base.cpp | 216 -- libs/vr/libbufferhub/buffer_hub_rpc.cpp | 9 - libs/vr/libbufferhub/consumer_buffer.cpp | 201 -- .../include/private/dvr/buffer_hub_base.h | 169 -- .../include/private/dvr/buffer_hub_defs.h | 164 -- .../include/private/dvr/bufferhub_rpc.h | 377 --- .../include/private/dvr/consumer_buffer.h | 73 - .../libbufferhub/include/private/dvr/ion_buffer.h | 100 - .../include/private/dvr/native_handle_wrapper.h | 102 - .../include/private/dvr/producer_buffer.h | 103 - libs/vr/libbufferhub/ion_buffer.cpp | 240 -- libs/vr/libbufferhub/producer_buffer.cpp | 296 --- libs/vr/libdvr/Android.bp | 35 - libs/vr/libdvr/include/CPPLINT.cfg | 1 - libs/vr/libdvr/include/dvr/dvr_api.h | 503 ---- libs/vr/libdvr/include/dvr/dvr_api_entries.h | 200 -- libs/vr/libdvr/include/dvr/dvr_buffer.h | 58 - libs/vr/libdvr/include/dvr/dvr_buffer_queue.h | 263 -- libs/vr/libdvr/include/dvr/dvr_config.h | 34 - .../vr/libdvr/include/dvr/dvr_configuration_data.h | 24 - libs/vr/libdvr/include/dvr/dvr_deleter.h | 82 - libs/vr/libdvr/include/dvr/dvr_display_manager.h | 133 -- libs/vr/libdvr/include/dvr/dvr_display_types.h | 65 - .../include/dvr/dvr_hardware_composer_client.h | 199 -- .../include/dvr/dvr_hardware_composer_types.h | 59 - libs/vr/libdvr/include/dvr/dvr_performance.h | 26 - libs/vr/libdvr/include/dvr/dvr_pose.h | 154 -- libs/vr/libdvr/include/dvr/dvr_shared_buffers.h | 102 - libs/vr/libdvr/include/dvr/dvr_surface.h | 113 - libs/vr/libdvr/include/dvr/dvr_tracking.h | 185 -- libs/vr/libdvr/include/dvr/dvr_tracking_types.h | 104 - libs/vr/libdvr/include/dvr/dvr_vsync.h | 32 - libs/vr/libdvrcommon/Android.bp | 87 - .../libdvrcommon/include/private/dvr/benchmark.h | 86 - .../vr/libdvrcommon/include/private/dvr/clock_ns.h | 84 - libs/vr/libdvrcommon/include/private/dvr/debug.h | 37 - libs/vr/libdvrcommon/include/private/dvr/eigen.h | 57 - .../include/private/dvr/field_of_view.h | 95 - .../libdvrcommon/include/private/dvr/log_helpers.h | 64 - .../include/private/dvr/matrix_helpers.h | 26 - libs/vr/libdvrcommon/include/private/dvr/numeric.h | 175 -- libs/vr/libdvrcommon/include/private/dvr/ortho.h | 31 - libs/vr/libdvrcommon/include/private/dvr/pose.h | 118 - libs/vr/libdvrcommon/include/private/dvr/range.h | 43 - .../libdvrcommon/include/private/dvr/ring_buffer.h | 99 - .../include/private/dvr/test/test_macros.h | 124 - libs/vr/libdvrcommon/include/private/dvr/types.h | 51 - libs/vr/libdvrcommon/tests/numeric_test.cpp | 67 - libs/vr/libdvrcommon/tests/pose_test.cpp | 154 -- libs/vr/libpdx/Android.bp | 85 - libs/vr/libpdx/client.cpp | 290 --- libs/vr/libpdx/client_tests.cpp | 567 ----- libs/vr/libpdx/encoder_performance_test.cpp | 515 ---- libs/vr/libpdx/fuzz/Android.bp | 68 - libs/vr/libpdx/fuzz/helpers.h | 294 --- libs/vr/libpdx/fuzz/message_fuzzer.cpp | 175 -- libs/vr/libpdx/fuzz/serialization_fuzzer.cpp | 288 --- libs/vr/libpdx/fuzz/service_dispatcher_fuzzer.cpp | 74 - libs/vr/libpdx/mock_tests.cpp | 18 - libs/vr/libpdx/private/pdx/channel_handle.h | 123 - libs/vr/libpdx/private/pdx/channel_parcelable.h | 31 - libs/vr/libpdx/private/pdx/client.h | 302 --- libs/vr/libpdx/private/pdx/client_channel.h | 76 - .../vr/libpdx/private/pdx/client_channel_factory.h | 21 - libs/vr/libpdx/private/pdx/file_handle.h | 141 -- libs/vr/libpdx/private/pdx/message_reader.h | 38 - libs/vr/libpdx/private/pdx/message_writer.h | 40 - libs/vr/libpdx/private/pdx/mock_client_channel.h | 59 - .../private/pdx/mock_client_channel_factory.h | 19 - libs/vr/libpdx/private/pdx/mock_message_reader.h | 27 - libs/vr/libpdx/private/pdx/mock_message_writer.h | 35 - libs/vr/libpdx/private/pdx/mock_service_endpoint.h | 75 - libs/vr/libpdx/private/pdx/rpc/argument_encoder.h | 184 -- libs/vr/libpdx/private/pdx/rpc/array_wrapper.h | 111 - libs/vr/libpdx/private/pdx/rpc/buffer_wrapper.h | 177 -- libs/vr/libpdx/private/pdx/rpc/copy_cv_reference.h | 43 - .../pdx/rpc/default_initialization_allocator.h | 47 - libs/vr/libpdx/private/pdx/rpc/encoding.h | 616 ----- libs/vr/libpdx/private/pdx/rpc/enumeration.h | 65 - libs/vr/libpdx/private/pdx/rpc/find_replace.h | 45 - libs/vr/libpdx/private/pdx/rpc/function_traits.h | 61 - libs/vr/libpdx/private/pdx/rpc/macros.h | 148 -- libs/vr/libpdx/private/pdx/rpc/message_buffer.h | 22 - libs/vr/libpdx/private/pdx/rpc/payload.h | 158 -- libs/vr/libpdx/private/pdx/rpc/pointer_wrapper.h | 38 - libs/vr/libpdx/private/pdx/rpc/remote_method.h | 473 ---- .../vr/libpdx/private/pdx/rpc/remote_method_type.h | 73 - libs/vr/libpdx/private/pdx/rpc/sequence.h | 56 - libs/vr/libpdx/private/pdx/rpc/serializable.h | 150 -- libs/vr/libpdx/private/pdx/rpc/serialization.h | 2000 ---------------- libs/vr/libpdx/private/pdx/rpc/string_wrapper.h | 129 - .../libpdx/private/pdx/rpc/thread_local_buffer.h | 134 -- libs/vr/libpdx/private/pdx/rpc/type_operators.h | 195 -- libs/vr/libpdx/private/pdx/rpc/variant.h | 760 ------ libs/vr/libpdx/private/pdx/service.h | 759 ------ libs/vr/libpdx/private/pdx/service_dispatcher.h | 107 - libs/vr/libpdx/private/pdx/service_endpoint.h | 148 -- libs/vr/libpdx/private/pdx/status.h | 183 -- libs/vr/libpdx/private/pdx/trace.h | 82 - libs/vr/libpdx/private/pdx/utility.h | 369 --- libs/vr/libpdx/serialization_tests.cpp | 2505 -------------------- libs/vr/libpdx/service.cpp | 675 ------ libs/vr/libpdx/service_dispatcher.cpp | 192 -- libs/vr/libpdx/service_tests.cpp | 809 ------- libs/vr/libpdx/status.cpp | 15 - libs/vr/libpdx/status_tests.cpp | 127 - libs/vr/libpdx/thread_local_buffer_tests.cpp | 117 - libs/vr/libpdx/variant_tests.cpp | 1153 --------- libs/vr/libpdx_default_transport/Android.bp | 88 - .../vr/libpdx_default_transport/pdx_benchmarks.cpp | 1090 --------- libs/vr/libpdx_default_transport/pdx_tool.cpp | 244 -- .../pdx/default_transport/service_utility.h | 92 - .../pdx/default_transport/channel_manager.h | 17 - .../pdx/default_transport/channel_parcelable.h | 17 - .../pdx/default_transport/client_channel.h | 17 - .../pdx/default_transport/client_channel_factory.h | 17 - .../pdx/default_transport/service_endpoint.h | 16 - .../uds/pdx/default_transport/channel_manager.h | 17 - .../uds/pdx/default_transport/channel_parcelable.h | 17 - .../uds/pdx/default_transport/client_channel.h | 17 - .../pdx/default_transport/client_channel_factory.h | 17 - .../uds/pdx/default_transport/service_endpoint.h | 16 - libs/vr/libpdx_uds/Android.bp | 67 - libs/vr/libpdx_uds/channel_event_set.cpp | 150 -- libs/vr/libpdx_uds/channel_manager.cpp | 52 - libs/vr/libpdx_uds/channel_parcelable.cpp | 125 - libs/vr/libpdx_uds/client_channel.cpp | 321 --- libs/vr/libpdx_uds/client_channel_factory.cpp | 173 -- libs/vr/libpdx_uds/client_channel_tests.cpp | 163 -- libs/vr/libpdx_uds/ipc_helper.cpp | 543 ----- libs/vr/libpdx_uds/ipc_helper_tests.cpp | 365 --- libs/vr/libpdx_uds/private/uds/channel_event_set.h | 84 - libs/vr/libpdx_uds/private/uds/channel_manager.h | 38 - .../vr/libpdx_uds/private/uds/channel_parcelable.h | 35 - libs/vr/libpdx_uds/private/uds/client_channel.h | 98 - .../private/uds/client_channel_factory.h | 36 - libs/vr/libpdx_uds/private/uds/ipc_helper.h | 222 -- libs/vr/libpdx_uds/private/uds/service_endpoint.h | 168 -- libs/vr/libpdx_uds/remote_method_tests.cpp | 951 -------- libs/vr/libpdx_uds/service_endpoint.cpp | 789 ------ libs/vr/libpdx_uds/service_framework_tests.cpp | 718 ------ libs/vr/libperformance/Android.bp | 51 - libs/vr/libperformance/include/CPPLINT.cfg | 1 - .../include/dvr/performance_client_api.h | 73 - .../include/private/dvr/performance_client.h | 40 - .../include/private/dvr/performance_rpc.h | 40 - libs/vr/libperformance/performance_client.cpp | 148 -- libs/vr/libperformance/performance_rpc.cpp | 9 - libs/vr/libvr_manager/Android.bp | 37 - .../include/private/dvr/trusted_uids.h | 33 - libs/vr/libvr_manager/trusted_uids.cpp | 51 - libs/vr/libvr_manager/vr_manager.cpp | 141 -- libs/vr/public.libraries-google.txt | 1 - services/surfaceflinger/surfaceflinger.rc | 3 - services/vr/.clang-format | 5 - services/vr/Android.bp | 13 - services/vr/bufferhubd/Android.bp | 74 - services/vr/bufferhubd/buffer_hub.cpp | 349 --- services/vr/bufferhubd/bufferhubd.cpp | 53 - services/vr/bufferhubd/bufferhubd.rc | 5 - services/vr/bufferhubd/consumer_channel.cpp | 179 -- services/vr/bufferhubd/consumer_queue_channel.cpp | 166 -- .../vr/bufferhubd/include/private/dvr/buffer_hub.h | 158 -- .../include/private/dvr/consumer_channel.h | 54 - .../include/private/dvr/consumer_queue_channel.h | 82 - .../include/private/dvr/producer_channel.h | 126 - .../include/private/dvr/producer_queue_channel.h | 94 - services/vr/bufferhubd/producer_channel.cpp | 673 ------ services/vr/bufferhubd/producer_queue_channel.cpp | 397 ---- services/vr/performanced/Android.bp | 63 - services/vr/performanced/CPPLINT.cfg | 1 - services/vr/performanced/cpu_set.cpp | 290 --- services/vr/performanced/cpu_set.h | 108 - services/vr/performanced/directory_reader.h | 56 - services/vr/performanced/main.cpp | 76 - services/vr/performanced/performance_service.cpp | 461 ---- services/vr/performanced/performance_service.h | 90 - .../vr/performanced/performance_service_tests.cpp | 529 ----- services/vr/performanced/performanced.rc | 5 - services/vr/performanced/stdio_filebuf.h | 219 -- services/vr/performanced/task.cpp | 166 -- services/vr/performanced/task.h | 83 - services/vr/performanced/unique_file.h | 20 - services/vr/virtual_touchpad/Android.bp | 140 -- .../virtual_touchpad/DvrVirtualTouchpadClient.cpp | 50 - services/vr/virtual_touchpad/EvdevInjector.cpp | 339 --- services/vr/virtual_touchpad/EvdevInjector.h | 148 -- .../vr/virtual_touchpad/VirtualTouchpadClient.cpp | 87 - .../vr/virtual_touchpad/VirtualTouchpadEvdev.cpp | 218 -- .../vr/virtual_touchpad/VirtualTouchpadEvdev.h | 68 - .../vr/virtual_touchpad/VirtualTouchpadService.cpp | 145 -- .../vr/virtual_touchpad/VirtualTouchpadService.h | 47 - .../aidl/android/dvr/IVirtualTouchpadService.aidl | 48 - .../virtual_touchpad/idc/vr-virtual-touchpad-0.idc | 26 - .../virtual_touchpad/idc/vr-virtual-touchpad-1.idc | 31 - .../vr/virtual_touchpad/include/VirtualTouchpad.h | 88 - .../include/VirtualTouchpadClient.h | 29 - .../include/dvr/virtual_touchpad_client.h | 79 - services/vr/virtual_touchpad/main.cpp | 33 - .../tests/VirtualTouchpad_test.cpp | 320 --- services/vr/virtual_touchpad/virtual_touchpad.rc | 5 - 214 files changed, 38834 deletions(-) delete mode 100644 libs/ui/include/ui/BufferHubDefs.h delete mode 100644 libs/vr/.clang-format delete mode 100644 libs/vr/Android.bp delete mode 100644 libs/vr/CPPLINT.cfg delete mode 100644 libs/vr/OWNERS delete mode 100644 libs/vr/libbroadcastring/Android.bp delete mode 100644 libs/vr/libbroadcastring/broadcast_ring_test.cc delete mode 100644 libs/vr/libbroadcastring/include/libbroadcastring/broadcast_ring.h delete mode 100644 libs/vr/libbufferhub/Android.bp delete mode 100644 libs/vr/libbufferhub/buffer_hub-test.cpp delete mode 100644 libs/vr/libbufferhub/buffer_hub_base.cpp delete mode 100644 libs/vr/libbufferhub/buffer_hub_rpc.cpp delete mode 100644 libs/vr/libbufferhub/consumer_buffer.cpp delete mode 100644 libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h delete mode 100644 libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h delete mode 100644 libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h delete mode 100644 libs/vr/libbufferhub/include/private/dvr/consumer_buffer.h delete mode 100644 libs/vr/libbufferhub/include/private/dvr/ion_buffer.h delete mode 100644 libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h delete mode 100644 libs/vr/libbufferhub/include/private/dvr/producer_buffer.h delete mode 100644 libs/vr/libbufferhub/ion_buffer.cpp delete mode 100644 libs/vr/libbufferhub/producer_buffer.cpp delete mode 100644 libs/vr/libdvr/Android.bp delete mode 100644 libs/vr/libdvr/include/CPPLINT.cfg delete mode 100644 libs/vr/libdvr/include/dvr/dvr_api.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_api_entries.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_buffer.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_buffer_queue.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_config.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_configuration_data.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_deleter.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_display_manager.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_display_types.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_hardware_composer_client.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_hardware_composer_types.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_performance.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_pose.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_shared_buffers.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_surface.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_tracking.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_tracking_types.h delete mode 100644 libs/vr/libdvr/include/dvr/dvr_vsync.h delete mode 100644 libs/vr/libdvrcommon/Android.bp delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/benchmark.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/clock_ns.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/debug.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/eigen.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/field_of_view.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/log_helpers.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/matrix_helpers.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/numeric.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/ortho.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/pose.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/range.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/ring_buffer.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/test/test_macros.h delete mode 100644 libs/vr/libdvrcommon/include/private/dvr/types.h delete mode 100644 libs/vr/libdvrcommon/tests/numeric_test.cpp delete mode 100644 libs/vr/libdvrcommon/tests/pose_test.cpp delete mode 100644 libs/vr/libpdx/Android.bp delete mode 100644 libs/vr/libpdx/client.cpp delete mode 100644 libs/vr/libpdx/client_tests.cpp delete mode 100644 libs/vr/libpdx/encoder_performance_test.cpp delete mode 100644 libs/vr/libpdx/fuzz/Android.bp delete mode 100644 libs/vr/libpdx/fuzz/helpers.h delete mode 100644 libs/vr/libpdx/fuzz/message_fuzzer.cpp delete mode 100644 libs/vr/libpdx/fuzz/serialization_fuzzer.cpp delete mode 100644 libs/vr/libpdx/fuzz/service_dispatcher_fuzzer.cpp delete mode 100644 libs/vr/libpdx/mock_tests.cpp delete mode 100644 libs/vr/libpdx/private/pdx/channel_handle.h delete mode 100644 libs/vr/libpdx/private/pdx/channel_parcelable.h delete mode 100644 libs/vr/libpdx/private/pdx/client.h delete mode 100644 libs/vr/libpdx/private/pdx/client_channel.h delete mode 100644 libs/vr/libpdx/private/pdx/client_channel_factory.h delete mode 100644 libs/vr/libpdx/private/pdx/file_handle.h delete mode 100644 libs/vr/libpdx/private/pdx/message_reader.h delete mode 100644 libs/vr/libpdx/private/pdx/message_writer.h delete mode 100644 libs/vr/libpdx/private/pdx/mock_client_channel.h delete mode 100644 libs/vr/libpdx/private/pdx/mock_client_channel_factory.h delete mode 100644 libs/vr/libpdx/private/pdx/mock_message_reader.h delete mode 100644 libs/vr/libpdx/private/pdx/mock_message_writer.h delete mode 100644 libs/vr/libpdx/private/pdx/mock_service_endpoint.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/argument_encoder.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/array_wrapper.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/buffer_wrapper.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/copy_cv_reference.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/default_initialization_allocator.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/encoding.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/enumeration.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/find_replace.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/function_traits.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/macros.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/message_buffer.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/payload.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/pointer_wrapper.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/remote_method.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/remote_method_type.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/sequence.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/serializable.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/serialization.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/string_wrapper.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/thread_local_buffer.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/type_operators.h delete mode 100644 libs/vr/libpdx/private/pdx/rpc/variant.h delete mode 100644 libs/vr/libpdx/private/pdx/service.h delete mode 100644 libs/vr/libpdx/private/pdx/service_dispatcher.h delete mode 100644 libs/vr/libpdx/private/pdx/service_endpoint.h delete mode 100644 libs/vr/libpdx/private/pdx/status.h delete mode 100644 libs/vr/libpdx/private/pdx/trace.h delete mode 100644 libs/vr/libpdx/private/pdx/utility.h delete mode 100644 libs/vr/libpdx/serialization_tests.cpp delete mode 100644 libs/vr/libpdx/service.cpp delete mode 100644 libs/vr/libpdx/service_dispatcher.cpp delete mode 100644 libs/vr/libpdx/service_tests.cpp delete mode 100644 libs/vr/libpdx/status.cpp delete mode 100644 libs/vr/libpdx/status_tests.cpp delete mode 100644 libs/vr/libpdx/thread_local_buffer_tests.cpp delete mode 100644 libs/vr/libpdx/variant_tests.cpp delete mode 100644 libs/vr/libpdx_default_transport/Android.bp delete mode 100644 libs/vr/libpdx_default_transport/pdx_benchmarks.cpp delete mode 100644 libs/vr/libpdx_default_transport/pdx_tool.cpp delete mode 100644 libs/vr/libpdx_default_transport/private/pdx/default_transport/service_utility.h delete mode 100644 libs/vr/libpdx_default_transport/private/servicefs/pdx/default_transport/channel_manager.h delete mode 100644 libs/vr/libpdx_default_transport/private/servicefs/pdx/default_transport/channel_parcelable.h delete mode 100644 libs/vr/libpdx_default_transport/private/servicefs/pdx/default_transport/client_channel.h delete mode 100644 libs/vr/libpdx_default_transport/private/servicefs/pdx/default_transport/client_channel_factory.h delete mode 100644 libs/vr/libpdx_default_transport/private/servicefs/pdx/default_transport/service_endpoint.h delete mode 100644 libs/vr/libpdx_default_transport/private/uds/pdx/default_transport/channel_manager.h delete mode 100644 libs/vr/libpdx_default_transport/private/uds/pdx/default_transport/channel_parcelable.h delete mode 100644 libs/vr/libpdx_default_transport/private/uds/pdx/default_transport/client_channel.h delete mode 100644 libs/vr/libpdx_default_transport/private/uds/pdx/default_transport/client_channel_factory.h delete mode 100644 libs/vr/libpdx_default_transport/private/uds/pdx/default_transport/service_endpoint.h delete mode 100644 libs/vr/libpdx_uds/Android.bp delete mode 100644 libs/vr/libpdx_uds/channel_event_set.cpp delete mode 100644 libs/vr/libpdx_uds/channel_manager.cpp delete mode 100644 libs/vr/libpdx_uds/channel_parcelable.cpp delete mode 100644 libs/vr/libpdx_uds/client_channel.cpp delete mode 100644 libs/vr/libpdx_uds/client_channel_factory.cpp delete mode 100644 libs/vr/libpdx_uds/client_channel_tests.cpp delete mode 100644 libs/vr/libpdx_uds/ipc_helper.cpp delete mode 100644 libs/vr/libpdx_uds/ipc_helper_tests.cpp delete mode 100644 libs/vr/libpdx_uds/private/uds/channel_event_set.h delete mode 100644 libs/vr/libpdx_uds/private/uds/channel_manager.h delete mode 100644 libs/vr/libpdx_uds/private/uds/channel_parcelable.h delete mode 100644 libs/vr/libpdx_uds/private/uds/client_channel.h delete mode 100644 libs/vr/libpdx_uds/private/uds/client_channel_factory.h delete mode 100644 libs/vr/libpdx_uds/private/uds/ipc_helper.h delete mode 100644 libs/vr/libpdx_uds/private/uds/service_endpoint.h delete mode 100644 libs/vr/libpdx_uds/remote_method_tests.cpp delete mode 100644 libs/vr/libpdx_uds/service_endpoint.cpp delete mode 100644 libs/vr/libpdx_uds/service_framework_tests.cpp delete mode 100644 libs/vr/libperformance/Android.bp delete mode 100644 libs/vr/libperformance/include/CPPLINT.cfg delete mode 100644 libs/vr/libperformance/include/dvr/performance_client_api.h delete mode 100644 libs/vr/libperformance/include/private/dvr/performance_client.h delete mode 100644 libs/vr/libperformance/include/private/dvr/performance_rpc.h delete mode 100644 libs/vr/libperformance/performance_client.cpp delete mode 100644 libs/vr/libperformance/performance_rpc.cpp delete mode 100644 libs/vr/libvr_manager/Android.bp delete mode 100644 libs/vr/libvr_manager/include/private/dvr/trusted_uids.h delete mode 100644 libs/vr/libvr_manager/trusted_uids.cpp delete mode 100644 libs/vr/libvr_manager/vr_manager.cpp delete mode 100644 libs/vr/public.libraries-google.txt delete mode 100644 services/vr/.clang-format delete mode 100644 services/vr/Android.bp delete mode 100644 services/vr/bufferhubd/Android.bp delete mode 100644 services/vr/bufferhubd/buffer_hub.cpp delete mode 100644 services/vr/bufferhubd/bufferhubd.cpp delete mode 100644 services/vr/bufferhubd/bufferhubd.rc delete mode 100644 services/vr/bufferhubd/consumer_channel.cpp delete mode 100644 services/vr/bufferhubd/consumer_queue_channel.cpp delete mode 100644 services/vr/bufferhubd/include/private/dvr/buffer_hub.h delete mode 100644 services/vr/bufferhubd/include/private/dvr/consumer_channel.h delete mode 100644 services/vr/bufferhubd/include/private/dvr/consumer_queue_channel.h delete mode 100644 services/vr/bufferhubd/include/private/dvr/producer_channel.h delete mode 100644 services/vr/bufferhubd/include/private/dvr/producer_queue_channel.h delete mode 100644 services/vr/bufferhubd/producer_channel.cpp delete mode 100644 services/vr/bufferhubd/producer_queue_channel.cpp delete mode 100644 services/vr/performanced/Android.bp delete mode 100644 services/vr/performanced/CPPLINT.cfg delete mode 100644 services/vr/performanced/cpu_set.cpp delete mode 100644 services/vr/performanced/cpu_set.h delete mode 100644 services/vr/performanced/directory_reader.h delete mode 100644 services/vr/performanced/main.cpp delete mode 100644 services/vr/performanced/performance_service.cpp delete mode 100644 services/vr/performanced/performance_service.h delete mode 100644 services/vr/performanced/performance_service_tests.cpp delete mode 100644 services/vr/performanced/performanced.rc delete mode 100644 services/vr/performanced/stdio_filebuf.h delete mode 100644 services/vr/performanced/task.cpp delete mode 100644 services/vr/performanced/task.h delete mode 100644 services/vr/performanced/unique_file.h delete mode 100644 services/vr/virtual_touchpad/Android.bp delete mode 100644 services/vr/virtual_touchpad/DvrVirtualTouchpadClient.cpp delete mode 100644 services/vr/virtual_touchpad/EvdevInjector.cpp delete mode 100644 services/vr/virtual_touchpad/EvdevInjector.h delete mode 100644 services/vr/virtual_touchpad/VirtualTouchpadClient.cpp delete mode 100644 services/vr/virtual_touchpad/VirtualTouchpadEvdev.cpp delete mode 100644 services/vr/virtual_touchpad/VirtualTouchpadEvdev.h delete mode 100644 services/vr/virtual_touchpad/VirtualTouchpadService.cpp delete mode 100644 services/vr/virtual_touchpad/VirtualTouchpadService.h delete mode 100644 services/vr/virtual_touchpad/aidl/android/dvr/IVirtualTouchpadService.aidl delete mode 100644 services/vr/virtual_touchpad/idc/vr-virtual-touchpad-0.idc delete mode 100644 services/vr/virtual_touchpad/idc/vr-virtual-touchpad-1.idc delete mode 100644 services/vr/virtual_touchpad/include/VirtualTouchpad.h delete mode 100644 services/vr/virtual_touchpad/include/VirtualTouchpadClient.h delete mode 100644 services/vr/virtual_touchpad/include/dvr/virtual_touchpad_client.h delete mode 100644 services/vr/virtual_touchpad/main.cpp delete mode 100644 services/vr/virtual_touchpad/tests/VirtualTouchpad_test.cpp delete mode 100644 services/vr/virtual_touchpad/virtual_touchpad.rc diff --git a/cmds/atrace/Android.bp b/cmds/atrace/Android.bp index 1c4e63e323..bc69b35aaa 100644 --- a/cmds/atrace/Android.bp +++ b/cmds/atrace/Android.bp @@ -33,7 +33,6 @@ cc_binary { "libcutils", "libz", "libbase", - "libpdx_default_transport", "android.hardware.atrace@1.0", ], diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp index 4160a72e83..888dc4ec0d 100644 --- a/cmds/atrace/atrace.cpp +++ b/cmds/atrace/atrace.cpp @@ -41,7 +41,6 @@ #include #include -#include #include #include #include @@ -53,7 +52,6 @@ #include using namespace android; -using pdx::default_transport::ServiceUtility; using hardware::hidl_vec; using hardware::hidl_string; using hardware::Return; @@ -72,7 +70,6 @@ const char* k_tracePreferSdkProperty = "debug.atrace.prefer_sdk"; const char* k_traceAppsNumberProperty = "debug.atrace.app_number"; const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d"; const char* k_coreServiceCategory = "core_services"; -const char* k_pdxServiceCategory = "pdx"; const char* k_coreServicesProp = "ro.atrace.core.services"; const char* kVendorCategoriesPath = "/vendor/etc/atrace/atrace_categories.txt"; @@ -131,7 +128,6 @@ static const TracingCategory k_categories[] = { { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } }, { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } }, { k_coreServiceCategory, "Core services", 0, { } }, - { k_pdxServiceCategory, "PDX services", 0, { } }, { "sched", "CPU Scheduling", 0, { { REQ, "events/sched/sched_switch/enable" }, { REQ, "events/sched/sched_wakeup/enable" }, @@ -299,7 +295,6 @@ static const char* g_debugAppCmdLine = ""; static const char* g_outputFile = nullptr; /* Global state */ -static bool g_tracePdx = false; static bool g_traceAborted = false; static bool g_categoryEnables[arraysize(k_categories)] = {}; static std::string g_traceFolder; @@ -456,10 +451,6 @@ static bool isCategorySupported(const TracingCategory& category) return !android::base::GetProperty(k_coreServicesProp, "").empty(); } - if (strcmp(category.name, k_pdxServiceCategory) == 0) { - return true; - } - bool ok = category.tags != 0; for (int i = 0; i < MAX_SYS_FILES; i++) { const char* path = category.sysfiles[i].path; @@ -818,11 +809,6 @@ static bool setUpUserspaceTracing() if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) { coreServicesTagEnabled = g_categoryEnables[i]; } - - // Set whether to poke PDX services in this session. - if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) { - g_tracePdx = g_categoryEnables[i]; - } } std::string packageList(g_debugAppCmdLine); @@ -834,9 +820,6 @@ static bool setUpUserspaceTracing() } ok &= setAppCmdlineProperty(&packageList[0]); ok &= setTagsProperty(tags); - if (g_tracePdx) { - ok &= ServiceUtility::PokeServices(); - } return ok; } @@ -845,10 +828,6 @@ static void cleanUpUserspaceTracing() { setTagsProperty(0); clearAppProperties(); - - if (g_tracePdx) { - ServiceUtility::PokeServices(); - } } diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index b693e44ee4..7dcbbc04bf 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -309,9 +309,7 @@ cc_library_shared { header_libs: [ "jni_headers", - "libdvr_headers", "libgui_aidl_headers", - "libpdx_headers", ], afdo: true, diff --git a/libs/ui/include/ui/BufferHubDefs.h b/libs/ui/include/ui/BufferHubDefs.h deleted file mode 100644 index 10f274f569..0000000000 --- a/libs/ui/include/ui/BufferHubDefs.h +++ /dev/null @@ -1,184 +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. - */ - -#ifndef ANDROID_BUFFER_HUB_DEFS_H_ -#define ANDROID_BUFFER_HUB_DEFS_H_ - -#include - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpacked" -// TODO(b/118893702): remove dependency once DvrNativeBufferMetadata moved out of libdvr -#include -#pragma clang diagnostic pop - -namespace android { - -namespace BufferHubDefs { - -// Single buffer clients (up to 16) ownership signal. -// 32-bit atomic unsigned int. -// Each client takes 2 bits. The first bit locates in the first 16 bits of -// bufferState; the second bit locates in the last 16 bits of bufferState. -// Client states: -// Gained state 11. Exclusive write state. -// Posted state 10. -// Acquired state 01. Shared read state. -// Released state 00. -// -// MSB LSB -// | | -// v v -// [C15|...|C1|C0|C15| ... |C1|C0] - -// Maximum number of clients a buffer can have. -static constexpr int kMaxNumberOfClients = 16; - -// Definition of bit masks. -// MSB LSB -// | kHighBitsMask | kLowbitsMask | -// v v v -// [b31| ... |b16|b15| ... |b0] - -// The location of lower 16 bits in the 32-bit buffer state. -static constexpr uint32_t kLowbitsMask = (1U << kMaxNumberOfClients) - 1U; - -// The location of higher 16 bits in the 32-bit buffer state. -static constexpr uint32_t kHighBitsMask = ~kLowbitsMask; - -// The client bit mask of the first client. -static constexpr uint32_t kFirstClientBitMask = (1U << kMaxNumberOfClients) + 1U; - -// Returns true if any of the client is in gained state. -static inline bool isAnyClientGained(uint32_t state) { - uint32_t highBits = state >> kMaxNumberOfClients; - uint32_t lowBits = state & kLowbitsMask; - return highBits == lowBits && lowBits != 0U; -} - -// Returns true if the input client is in gained state. -static inline bool isClientGained(uint32_t state, uint32_t client_bit_mask) { - return state == client_bit_mask; -} - -// Returns true if any of the client is in posted state. -static inline bool isAnyClientPosted(uint32_t state) { - uint32_t highBits = state >> kMaxNumberOfClients; - uint32_t lowBits = state & kLowbitsMask; - uint32_t postedOrAcquired = highBits ^ lowBits; - return postedOrAcquired & highBits; -} - -// Returns true if the input client is in posted state. -static inline bool isClientPosted(uint32_t state, uint32_t client_bit_mask) { - uint32_t clientBits = state & client_bit_mask; - if (clientBits == 0U) return false; - uint32_t lowBits = clientBits & kLowbitsMask; - return lowBits == 0U; -} - -// Return true if any of the client is in acquired state. -static inline bool isAnyClientAcquired(uint32_t state) { - uint32_t highBits = state >> kMaxNumberOfClients; - uint32_t lowBits = state & kLowbitsMask; - uint32_t postedOrAcquired = highBits ^ lowBits; - return postedOrAcquired & lowBits; -} - -// Return true if the input client is in acquired state. -static inline bool isClientAcquired(uint32_t state, uint32_t client_bit_mask) { - uint32_t clientBits = state & client_bit_mask; - if (clientBits == 0U) return false; - uint32_t highBits = clientBits & kHighBitsMask; - return highBits == 0U; -} - -// Returns true if the input client is in released state. -static inline bool isClientReleased(uint32_t state, uint32_t client_bit_mask) { - return (state & client_bit_mask) == 0U; -} - -// Returns the next available buffer client's client_state_masks. -// @params union_bits. Union of all existing clients' client_state_masks. -static inline uint32_t findNextAvailableClientStateMask(uint32_t union_bits) { - uint32_t lowUnion = union_bits & kLowbitsMask; - if (lowUnion == kLowbitsMask) return 0U; - uint32_t incremented = lowUnion + 1U; - uint32_t difference = incremented ^ lowUnion; - uint32_t newLowBit = (difference + 1U) >> 1; - return newLowBit + (newLowBit << kMaxNumberOfClients); -} - -struct __attribute__((aligned(8))) MetadataHeader { - // Internal data format, which can be updated as long as the size, padding and field alignment - // of the struct is consistent within the same ABI. As this part is subject for future updates, - // it's not stable cross Android version, so don't have it visible from outside of the Android - // platform (include Apps and vendor HAL). - - // Every client takes up one bit from the higher 32 bits and one bit from the lower 32 bits in - // bufferState. - std::atomic bufferState; - - // Every client takes up one bit in fenceState. Only the lower 32 bits are valid. The upper 32 - // bits are there for easier manipulation, but the value should be ignored. - std::atomic fenceState; - - // Every client takes up one bit from the higher 32 bits and one bit from the lower 32 bits in - // activeClientsBitMask. - std::atomic activeClientsBitMask; - - // Explicit padding 4 bytes. - uint32_t padding; - - // The index of the buffer queue where the buffer belongs to. - uint64_t queueIndex; - - // Public data format, which should be updated with caution. See more details in dvr_api.h - DvrNativeBufferMetadata metadata; -}; - -static_assert(sizeof(MetadataHeader) == 128, "Unexpected MetadataHeader size"); -static constexpr size_t kMetadataHeaderSize = sizeof(MetadataHeader); - -/** - * android.frameworks.bufferhub@1.0::BufferTraits.bufferInfo is an opaque handle. See - * https://cs.corp.google.com/android/frameworks/hardware/interfaces/bufferhub/1.0/types.hal for - * more details about android.frameworks.bufferhub@1.0::BufferTraits. - * - * This definition could be changed, but implementation of BufferHubService::buildBufferInfo - * (frameworks/native/services/bufferhub), VtsHalBufferHubV1_0TargetTest - * (frameworks/hardware/interfaces/bufferhub) and BufferHubBuffer::readBufferTraits (libui) will - * also need to be updated. - * - * It's definition should follow the following format: - * { - * NumFds = 2, - * NumInts = 3, - * data[0] = Ashmem fd for BufferHubMetadata, - * data[1] = event fd, - * data[2] = buffer id, - * data[3] = client state bit mask, - * data[4] = user metadata size, - * } - */ -static constexpr int kBufferInfoNumFds = 2; -static constexpr int kBufferInfoNumInts = 3; - -} // namespace BufferHubDefs - -} // namespace android - -#endif // ANDROID_BUFFER_HUB_DEFS_H_ diff --git a/libs/vr/.clang-format b/libs/vr/.clang-format deleted file mode 100644 index 04d7970bbe..0000000000 --- a/libs/vr/.clang-format +++ /dev/null @@ -1,5 +0,0 @@ -BasedOnStyle: Google -DerivePointerAlignment: false -PointerAlignment: Left -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false diff --git a/libs/vr/Android.bp b/libs/vr/Android.bp deleted file mode 100644 index b308895faf..0000000000 --- a/libs/vr/Android.bp +++ /dev/null @@ -1,14 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - // SPDX-license-identifier-BSD - // legacy_notice - default_applicable_licenses: ["frameworks_native_license"], -} - -subdirs = [ - "*", -] diff --git a/libs/vr/CPPLINT.cfg b/libs/vr/CPPLINT.cfg deleted file mode 100644 index 87fb641c28..0000000000 --- a/libs/vr/CPPLINT.cfg +++ /dev/null @@ -1,2 +0,0 @@ -set noparent -filter=-build/include_order,-legal/copyright,-build/include,-build/c++11,+build/include_alpha diff --git a/libs/vr/OWNERS b/libs/vr/OWNERS deleted file mode 100644 index 098c80e557..0000000000 --- a/libs/vr/OWNERS +++ /dev/null @@ -1,4 +0,0 @@ -hendrikw@google.com -jwcai@google.com -steventhomas@google.com -patplunkett@google.com diff --git a/libs/vr/libbroadcastring/Android.bp b/libs/vr/libbroadcastring/Android.bp deleted file mode 100644 index e72ca74ba7..0000000000 --- a/libs/vr/libbroadcastring/Android.bp +++ /dev/null @@ -1,43 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_library_static { - name: "libbroadcastring", - - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - ], - export_include_dirs: ["include"], - shared_libs: [ - "libbase", - ], - export_shared_lib_headers: [ - "libbase", - ], -} - -cc_test { - name: "broadcast_ring_tests", - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - ], - srcs: [ - "broadcast_ring_test.cc", - ], - static_libs: [ - "libbroadcastring", - ], - shared_libs: [ - "libbase", - ], -} diff --git a/libs/vr/libbroadcastring/broadcast_ring_test.cc b/libs/vr/libbroadcastring/broadcast_ring_test.cc deleted file mode 100644 index dfdd4ef0db..0000000000 --- a/libs/vr/libbroadcastring/broadcast_ring_test.cc +++ /dev/null @@ -1,866 +0,0 @@ -#include "libbroadcastring/broadcast_ring.h" - -#include -#include -#include // NOLINT -#include - -#include - -namespace android { -namespace dvr { -namespace { - -template -struct alignas(8) Aligned { - char v[N]; -}; - -template -struct alignas(8) Sized { - Sized() { Clear(); } - explicit Sized(char c) { Fill(c); } - char v[sizeof(Aligned)]; - void Clear() { memset(v, 0, sizeof(v)); } - void Fill(char c) { memset(v, c, sizeof(v)); } - static Sized Pattern(uint8_t c) { - Sized sized; - for (size_t i = 0; i < sizeof(v); ++i) { - sized.v[i] = static_cast(c + i); - } - return sized; - } - bool operator==(const Sized& right) const { - static_assert(sizeof(*this) == sizeof(v), "Size mismatch"); - return !memcmp(v, right.v, sizeof(v)); - } - template - SmallerSized Truncate() const { - SmallerSized val; - static_assert(sizeof(val.v) <= sizeof(v), "Cannot truncate to larger size"); - memcpy(val.v, v, sizeof(val.v)); - return val; - } -}; - -char FillChar(int val) { return static_cast(val); } - -struct FakeMmap { - explicit FakeMmap(size_t size) : size(size), data(new char[size]) {} - size_t size; - std::unique_ptr data; - void* mmap() { return static_cast(data.get()); } -}; - -template -FakeMmap CreateRing(Ring* ring, uint32_t count) { - FakeMmap mmap(Ring::MemorySize(count)); - *ring = Ring::Create(mmap.mmap(), mmap.size, count); - return mmap; -} - -template -struct Traits { - using Record = RecordType; - static constexpr bool kUseStaticRecordSize = StaticSize; - static constexpr uint32_t kStaticRecordCount = StaticCount; - static constexpr uint32_t kMaxReservedRecords = MaxReserved; - static constexpr uint32_t kMinAvailableRecords = MinAvailable; - static constexpr uint32_t kMinRecordCount = MaxReserved + MinAvailable; -}; - -template -struct TraitsDynamic - : public Traits { - using Ring = BroadcastRing; - static uint32_t MinCount() { return MaxReserved + MinAvailable; } -}; - -template -struct TraitsStatic - : public Traits { - using Ring = BroadcastRing; - static uint32_t MinCount() { return StaticCount; } -}; - -using Dynamic_8_NxM = TraitsDynamic>; -using Dynamic_16_NxM = TraitsDynamic>; -using Dynamic_32_NxM = TraitsDynamic>; -using Dynamic_32_32xM = TraitsDynamic, true>; -using Dynamic_16_NxM_1plus0 = TraitsDynamic, false, 1, 0>; -using Dynamic_16_NxM_1plus1 = TraitsDynamic, false, 1, 1>; -using Dynamic_16_NxM_5plus11 = TraitsDynamic, false, 5, 11>; -using Dynamic_256_NxM_1plus0 = TraitsDynamic, false, 1, 0>; - -using Static_8_8x1 = TraitsStatic, 1>; -using Static_8_8x16 = TraitsStatic, 16>; -using Static_16_16x8 = TraitsStatic, 8>; -using Static_16_16x16 = TraitsStatic, 16>; -using Static_16_16x32 = TraitsStatic, 32>; -using Static_32_Nx8 = TraitsStatic, 8, false>; - -using TraitsList = ::testing::Types; - -} // namespace - -template -class BroadcastRingTest : public ::testing::Test {}; - -TYPED_TEST_CASE(BroadcastRingTest, TraitsList); - -TYPED_TEST(BroadcastRingTest, Geometry) { - using Record = typename TypeParam::Record; - using Ring = typename TypeParam::Ring; - Ring ring; - auto mmap = CreateRing(&ring, Ring::Traits::MinCount()); - EXPECT_EQ(Ring::Traits::MinCount(), ring.record_count()); - EXPECT_EQ(sizeof(Record), ring.record_size()); -} - -TYPED_TEST(BroadcastRingTest, PutGet) { - using Record = typename TypeParam::Record; - using Ring = typename TypeParam::Ring; - Ring ring; - auto mmap = CreateRing(&ring, Ring::Traits::MinCount()); - const uint32_t oldest_sequence_at_start = ring.GetOldestSequence(); - const uint32_t next_sequence_at_start = ring.GetNextSequence(); - { - uint32_t sequence = oldest_sequence_at_start; - Record record; - EXPECT_FALSE(ring.Get(&sequence, &record)); - EXPECT_EQ(oldest_sequence_at_start, sequence); - EXPECT_EQ(Record(), record); - } - const Record original_record(0x1a); - ring.Put(original_record); - { - uint32_t sequence = next_sequence_at_start; - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(next_sequence_at_start, sequence); - EXPECT_EQ(original_record, record); - } - { - uint32_t sequence = next_sequence_at_start + 1; - Record record; - EXPECT_FALSE(ring.Get(&sequence, &record)); - EXPECT_EQ(next_sequence_at_start + 1, sequence); - EXPECT_EQ(Record(), record); - } -} - -TYPED_TEST(BroadcastRingTest, FillOnce) { - using Record = typename TypeParam::Record; - using Ring = typename TypeParam::Ring; - Ring ring; - auto mmap = CreateRing(&ring, Ring::Traits::MinCount()); - const uint32_t next_sequence_at_start = ring.GetNextSequence(); - for (uint32_t i = 0; i < ring.record_count(); ++i) - ring.Put(Record(FillChar(i))); - for (uint32_t i = 0; i < ring.record_count(); ++i) { - const uint32_t expected_sequence = next_sequence_at_start + i; - const Record expected_record(FillChar(i)); - { - uint32_t sequence = ring.GetOldestSequence() + i; - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(expected_sequence, sequence); - EXPECT_EQ(expected_record, record); - } - } - { - uint32_t sequence = ring.GetOldestSequence() + ring.record_count(); - Record record; - EXPECT_FALSE(ring.Get(&sequence, &record)); - } -} - -TYPED_TEST(BroadcastRingTest, FillTwice) { - using Record = typename TypeParam::Record; - using Ring = typename TypeParam::Ring; - Ring ring; - auto mmap = CreateRing(&ring, Ring::Traits::MinCount()); - const uint32_t next_sequence_at_start = ring.GetNextSequence(); - for (uint32_t i = 0; i < 2 * ring.record_count(); ++i) { - const Record newest_record(FillChar(i)); - ring.Put(newest_record); - - const uint32_t newest_sequence = next_sequence_at_start + i; - const uint32_t records_available = std::min(i + 1, ring.record_count()); - const uint32_t oldest_sequence = newest_sequence - records_available + 1; - EXPECT_EQ(newest_sequence, ring.GetNewestSequence()); - EXPECT_EQ(oldest_sequence, ring.GetOldestSequence()); - EXPECT_EQ(newest_sequence + 1, ring.GetNextSequence()); - - for (uint32_t j = 0; j < records_available; ++j) { - const uint32_t sequence_jth_newest = newest_sequence - j; - const Record record_jth_newest(FillChar(i - j)); - - { - uint32_t sequence = sequence_jth_newest; - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(sequence_jth_newest, sequence); - EXPECT_EQ(record_jth_newest, record); - } - - { - uint32_t sequence = sequence_jth_newest; - Record record; - EXPECT_TRUE(ring.GetNewest(&sequence, &record)); - EXPECT_EQ(newest_sequence, sequence); - EXPECT_EQ(newest_record, record); - } - } - - const Record oldest_record( - FillChar(i + (oldest_sequence - newest_sequence))); - const uint32_t sequence_0th_overwritten = oldest_sequence - 1; - const uint32_t sequence_0th_future = newest_sequence + 1; - const uint32_t sequence_1st_future = newest_sequence + 2; - - { - uint32_t sequence = sequence_0th_overwritten; - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(oldest_sequence, sequence); - EXPECT_EQ(oldest_record, record); - } - - { - uint32_t sequence = sequence_0th_overwritten; - Record record; - EXPECT_TRUE(ring.GetNewest(&sequence, &record)); - EXPECT_EQ(newest_sequence, sequence); - EXPECT_EQ(newest_record, record); - } - - { - uint32_t sequence = sequence_0th_future; - Record record; - EXPECT_FALSE(ring.Get(&sequence, &record)); - EXPECT_EQ(sequence_0th_future, sequence); - EXPECT_EQ(Record(), record); - } - - { - uint32_t sequence = sequence_0th_future; - Record record; - EXPECT_FALSE(ring.GetNewest(&sequence, &record)); - EXPECT_EQ(sequence_0th_future, sequence); - EXPECT_EQ(Record(), record); - } - - { - uint32_t sequence = sequence_1st_future; - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(oldest_sequence, sequence); - EXPECT_EQ(oldest_record, record); - } - - { - uint32_t sequence = sequence_1st_future; - Record record; - EXPECT_TRUE(ring.GetNewest(&sequence, &record)); - EXPECT_EQ(newest_sequence, sequence); - EXPECT_EQ(newest_record, record); - } - } -} - -TYPED_TEST(BroadcastRingTest, Import) { - using Record = typename TypeParam::Record; - using Ring = typename TypeParam::Ring; - Ring ring; - auto mmap = CreateRing(&ring, Ring::Traits::MinCount()); - - const uint32_t sequence_0 = ring.GetNextSequence(); - const uint32_t sequence_1 = ring.GetNextSequence() + 1; - const Record record_0 = Record::Pattern(0x00); - const Record record_1 = Record::Pattern(0x80); - ring.Put(record_0); - ring.Put(record_1); - - { - Ring imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = Ring::Import(mmap.mmap(), mmap.size); - EXPECT_TRUE(import_ok); - EXPECT_EQ(ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(ring.record_count(), imported_ring.record_count()); - - if (ring.record_count() != 1) { - uint32_t sequence = sequence_0; - Record imported_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &imported_record)); - EXPECT_EQ(sequence_0, sequence); - EXPECT_EQ(record_0, imported_record); - } - - { - uint32_t sequence = sequence_1; - Record imported_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &imported_record)); - EXPECT_EQ(sequence_1, sequence); - EXPECT_EQ(record_1, imported_record); - } - } -} - -TEST(BroadcastRingTest, ShouldFailImportIfStaticSizeMismatch) { - using OriginalRing = typename Static_16_16x16::Ring; - using RecordSizeMismatchRing = typename Static_8_8x16::Ring; - using RecordCountMismatchRing = typename Static_16_16x8::Ring; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, OriginalRing::Traits::MinCount()); - - { - using ImportedRing = RecordSizeMismatchRing; - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_FALSE(import_ok); - auto mmap_imported = - CreateRing(&imported_ring, ImportedRing::Traits::MinCount()); - EXPECT_NE(original_ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(original_ring.record_count(), imported_ring.record_count()); - } - - { - using ImportedRing = RecordCountMismatchRing; - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_FALSE(import_ok); - auto mmap_imported = - CreateRing(&imported_ring, ImportedRing::Traits::MinCount()); - EXPECT_EQ(original_ring.record_size(), imported_ring.record_size()); - EXPECT_NE(original_ring.record_count(), imported_ring.record_count()); - } -} - -TEST(BroadcastRingTest, ShouldFailImportIfDynamicSizeGrows) { - using OriginalRing = typename Dynamic_8_NxM::Ring; - using RecordSizeGrowsRing = typename Dynamic_16_NxM::Ring; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, OriginalRing::Traits::MinCount()); - - { - using ImportedRing = RecordSizeGrowsRing; - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_FALSE(import_ok); - auto mmap_imported = - CreateRing(&imported_ring, ImportedRing::Traits::MinCount()); - EXPECT_LT(original_ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(original_ring.record_count(), imported_ring.record_count()); - } -} - -TEST(BroadcastRingTest, ShouldFailImportIfCountTooSmall) { - using OriginalRing = typename Dynamic_16_NxM_1plus0::Ring; - using MinCountRing = typename Dynamic_16_NxM_1plus1::Ring; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, OriginalRing::Traits::MinCount()); - - { - using ImportedRing = MinCountRing; - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_FALSE(import_ok); - auto mmap_imported = - CreateRing(&imported_ring, ImportedRing::Traits::MinCount()); - EXPECT_EQ(original_ring.record_size(), imported_ring.record_size()); - EXPECT_LT(original_ring.record_count(), imported_ring.record_count()); - } -} - -TEST(BroadcastRingTest, ShouldFailImportIfMmapTooSmall) { - using OriginalRing = typename Dynamic_16_NxM::Ring; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, OriginalRing::Traits::MinCount()); - - { - using ImportedRing = OriginalRing; - ImportedRing imported_ring; - bool import_ok; - const size_t kMinSize = - ImportedRing::MemorySize(original_ring.record_count()); - std::tie(imported_ring, import_ok) = ImportedRing::Import(mmap.mmap(), 0); - EXPECT_FALSE(import_ok); - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), kMinSize - 1); - EXPECT_FALSE(import_ok); - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), kMinSize); - EXPECT_TRUE(import_ok); - EXPECT_EQ(original_ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(original_ring.record_count(), imported_ring.record_count()); - } -} - -TEST(BroadcastRingTest, ShouldImportIfDynamicSizeShrinks) { - using OriginalRing = typename Dynamic_16_NxM::Ring; - using RecordSizeShrinksRing = typename Dynamic_8_NxM::Ring; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, OriginalRing::Traits::MinCount()); - - using OriginalRecord = typename OriginalRing::Record; - const uint32_t original_sequence_0 = original_ring.GetNextSequence(); - const uint32_t original_sequence_1 = original_ring.GetNextSequence() + 1; - const OriginalRecord original_record_0 = OriginalRecord::Pattern(0x00); - const OriginalRecord original_record_1 = OriginalRecord::Pattern(0x80); - original_ring.Put(original_record_0); - original_ring.Put(original_record_1); - - { - using ImportedRing = RecordSizeShrinksRing; - using ImportedRecord = typename ImportedRing::Record; - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_TRUE(import_ok); - EXPECT_EQ(original_ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(original_ring.record_count(), imported_ring.record_count()); - EXPECT_GT(sizeof(OriginalRecord), sizeof(ImportedRecord)); - - { - uint32_t sequence = original_sequence_0; - ImportedRecord shrunk_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &shrunk_record)); - EXPECT_EQ(original_sequence_0, sequence); - EXPECT_EQ(original_record_0.Truncate(), shrunk_record); - } - - { - uint32_t sequence = original_sequence_1; - ImportedRecord shrunk_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &shrunk_record)); - EXPECT_EQ(original_sequence_1, sequence); - EXPECT_EQ(original_record_1.Truncate(), shrunk_record); - } - } -} - -TEST(BroadcastRingTest, ShouldImportIfCompatibleDynamicToStatic) { - using OriginalRing = typename Dynamic_16_NxM::Ring; - using ImportedRing = typename Static_16_16x16::Ring; - using OriginalRecord = typename OriginalRing::Record; - using ImportedRecord = typename ImportedRing::Record; - using StaticRing = ImportedRing; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, StaticRing::Traits::MinCount()); - - const uint32_t original_sequence_0 = original_ring.GetNextSequence(); - const uint32_t original_sequence_1 = original_ring.GetNextSequence() + 1; - const OriginalRecord original_record_0 = OriginalRecord::Pattern(0x00); - const OriginalRecord original_record_1 = OriginalRecord::Pattern(0x80); - original_ring.Put(original_record_0); - original_ring.Put(original_record_1); - - { - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_TRUE(import_ok); - EXPECT_EQ(original_ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(original_ring.record_count(), imported_ring.record_count()); - - { - uint32_t sequence = original_sequence_0; - ImportedRecord imported_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &imported_record)); - EXPECT_EQ(original_sequence_0, sequence); - EXPECT_EQ(original_record_0, imported_record); - } - - { - uint32_t sequence = original_sequence_1; - ImportedRecord imported_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &imported_record)); - EXPECT_EQ(original_sequence_1, sequence); - EXPECT_EQ(original_record_1, imported_record); - } - } -} - -TEST(BroadcastRingTest, ShouldImportIfCompatibleStaticToDynamic) { - using OriginalRing = typename Static_16_16x16::Ring; - using ImportedRing = typename Dynamic_16_NxM::Ring; - using OriginalRecord = typename OriginalRing::Record; - using ImportedRecord = typename ImportedRing::Record; - using StaticRing = OriginalRing; - - OriginalRing original_ring; - auto mmap = CreateRing(&original_ring, StaticRing::Traits::MinCount()); - - const uint32_t original_sequence_0 = original_ring.GetNextSequence(); - const uint32_t original_sequence_1 = original_ring.GetNextSequence() + 1; - const OriginalRecord original_record_0 = OriginalRecord::Pattern(0x00); - const OriginalRecord original_record_1 = OriginalRecord::Pattern(0x80); - original_ring.Put(original_record_0); - original_ring.Put(original_record_1); - - { - ImportedRing imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = - ImportedRing::Import(mmap.mmap(), mmap.size); - EXPECT_TRUE(import_ok); - EXPECT_EQ(original_ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(original_ring.record_count(), imported_ring.record_count()); - - { - uint32_t sequence = original_sequence_0; - ImportedRecord imported_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &imported_record)); - EXPECT_EQ(original_sequence_0, sequence); - EXPECT_EQ(original_record_0, imported_record); - } - - { - uint32_t sequence = original_sequence_1; - ImportedRecord imported_record; - EXPECT_TRUE(imported_ring.Get(&sequence, &imported_record)); - EXPECT_EQ(original_sequence_1, sequence); - EXPECT_EQ(original_record_1, imported_record); - } - } -} - -TEST(BroadcastRingTest, ShouldImportIfReadonlyMmap) { - using Ring = Dynamic_32_NxM::Ring; - using Record = Ring::Record; - - uint32_t record_count = Ring::Traits::MinCount(); - size_t ring_size = Ring::MemorySize(record_count); - - size_t page_size = sysconf(_SC_PAGESIZE); - size_t mmap_size = (ring_size + (page_size - 1)) & ~(page_size - 1); - ASSERT_GE(mmap_size, ring_size); - - void* mmap_base = mmap(nullptr, mmap_size, PROT_READ | PROT_WRITE, - MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); - ASSERT_NE(MAP_FAILED, mmap_base); - - Ring ring = Ring::Create(mmap_base, mmap_size, record_count); - for (uint32_t i = 0; i < record_count; ++i) ring.Put(Record(FillChar(i))); - - ASSERT_EQ(0, mprotect(mmap_base, mmap_size, PROT_READ)); - - { - Ring imported_ring; - bool import_ok; - std::tie(imported_ring, import_ok) = Ring::Import(mmap_base, mmap_size); - EXPECT_TRUE(import_ok); - EXPECT_EQ(ring.record_size(), imported_ring.record_size()); - EXPECT_EQ(ring.record_count(), imported_ring.record_count()); - - uint32_t oldest_sequence = imported_ring.GetOldestSequence(); - for (uint32_t i = 0; i < record_count; ++i) { - uint32_t sequence = oldest_sequence + i; - Record record; - EXPECT_TRUE(imported_ring.Get(&sequence, &record)); - EXPECT_EQ(Record(FillChar(i)), record); - } - } - - ASSERT_EQ(0, munmap(mmap_base, mmap_size)); -} - -TEST(BroadcastRingTest, ShouldDieIfPutReadonlyMmap) { - using Ring = Dynamic_32_NxM::Ring; - using Record = Ring::Record; - - uint32_t record_count = Ring::Traits::MinCount(); - size_t ring_size = Ring::MemorySize(record_count); - - size_t page_size = sysconf(_SC_PAGESIZE); - size_t mmap_size = (ring_size + (page_size - 1)) & ~(page_size - 1); - ASSERT_GE(mmap_size, ring_size); - - void* mmap_base = mmap(nullptr, mmap_size, PROT_READ | PROT_WRITE, - MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); - ASSERT_NE(MAP_FAILED, mmap_base); - - Ring ring = Ring::Create(mmap_base, mmap_size, record_count); - for (uint32_t i = 0; i < record_count; ++i) ring.Put(Record(FillChar(i))); - - ASSERT_EQ(0, mprotect(mmap_base, mmap_size, PROT_READ)); - - EXPECT_DEATH_IF_SUPPORTED({ ring.Put(Record(7)); }, ""); - - ASSERT_EQ(0, munmap(mmap_base, mmap_size)); -} - -TEST(BroadcastRingTest, ShouldDieIfCreationMmapTooSmall) { - using Ring = Dynamic_32_NxM::Ring; - using Record = Ring::Record; - - uint32_t record_count = Ring::Traits::MinCount(); - size_t ring_size = Ring::MemorySize(record_count); - FakeMmap mmap(ring_size); - - EXPECT_DEATH_IF_SUPPORTED({ - Ring ring = Ring::Create(mmap.mmap(), ring_size - 1, record_count); - }, ""); - - Ring ring = Ring::Create(mmap.mmap(), ring_size, record_count); - - ring.Put(Record(3)); - - { - uint32_t sequence = ring.GetNewestSequence(); - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(Record(3), record); - } -} - -TEST(BroadcastRingTest, ShouldDieIfCreationMmapMisaligned) { - using Ring = Static_8_8x1::Ring; - using Record = Ring::Record; - - constexpr int kAlign = Ring::mmap_alignment(); - constexpr int kMisalign = kAlign / 2; - size_t ring_size = Ring::MemorySize(); - std::unique_ptr buf(new char[ring_size + kMisalign]); - - EXPECT_DEATH_IF_SUPPORTED( - { Ring ring = Ring::Create(buf.get() + kMisalign, ring_size); }, ""); - - Ring ring = Ring::Create(buf.get(), ring_size); - - ring.Put(Record(3)); - - { - uint32_t sequence = ring.GetNewestSequence(); - Record record; - EXPECT_TRUE(ring.Get(&sequence, &record)); - EXPECT_EQ(Record(3), record); - } -} - -template -std::unique_ptr CopyTask(std::atomic* quit, void* in_base, - size_t in_size, void* out_base, - size_t out_size) { - return std::unique_ptr( - new std::thread([quit, in_base, in_size, out_base, out_size]() { - using Record = typename Ring::Record; - - bool import_ok; - Ring in_ring; - Ring out_ring; - std::tie(in_ring, import_ok) = Ring::Import(in_base, in_size); - ASSERT_TRUE(import_ok); - std::tie(out_ring, import_ok) = Ring::Import(out_base, out_size); - ASSERT_TRUE(import_ok); - - uint32_t sequence = in_ring.GetOldestSequence(); - while (!std::atomic_load_explicit(quit, std::memory_order_relaxed)) { - Record record; - if (in_ring.Get(&sequence, &record)) { - out_ring.Put(record); - sequence++; - } - } - })); -} - -TEST(BroadcastRingTest, ThreadedCopySingle) { - using Ring = Dynamic_32_NxM::Ring; - using Record = Ring::Record; - Ring in_ring; - auto in_mmap = CreateRing(&in_ring, Ring::Traits::MinCount()); - - Ring out_ring; - auto out_mmap = CreateRing(&out_ring, Ring::Traits::MinCount()); - - std::atomic quit(false); - std::unique_ptr copy_task = CopyTask( - &quit, out_mmap.mmap(), out_mmap.size, in_mmap.mmap(), in_mmap.size); - - const Record out_record(0x1c); - out_ring.Put(out_record); - - uint32_t in_sequence = in_ring.GetOldestSequence(); - Record in_record; - while (!in_ring.Get(&in_sequence, &in_record)) { - // Do nothing. - } - - EXPECT_EQ(out_record, in_record); - std::atomic_store_explicit(&quit, true, std::memory_order_relaxed); - copy_task->join(); -} - -TEST(BroadcastRingTest, ThreadedCopyLossless) { - using Ring = Dynamic_32_NxM::Ring; - using Record = Ring::Record; - Ring in_ring; - auto in_mmap = CreateRing(&in_ring, Ring::Traits::MinCount()); - - Ring out_ring; - auto out_mmap = CreateRing(&out_ring, Ring::Traits::MinCount()); - - std::atomic quit(false); - std::unique_ptr copy_task = CopyTask( - &quit, out_mmap.mmap(), out_mmap.size, in_mmap.mmap(), in_mmap.size); - - constexpr uint32_t kRecordsToProcess = 10000; - uint32_t out_records = 0; - uint32_t in_records = 0; - uint32_t in_sequence = in_ring.GetNextSequence(); - while (out_records < kRecordsToProcess || in_records < kRecordsToProcess) { - if (out_records < kRecordsToProcess && - out_records - in_records < out_ring.record_count()) { - const Record out_record(FillChar(out_records)); - out_ring.Put(out_record); - out_records++; - } - - Record in_record; - while (in_ring.Get(&in_sequence, &in_record)) { - EXPECT_EQ(Record(FillChar(in_records)), in_record); - in_records++; - in_sequence++; - } - } - - EXPECT_EQ(kRecordsToProcess, out_records); - EXPECT_EQ(kRecordsToProcess, in_records); - - std::atomic_store_explicit(&quit, true, std::memory_order_relaxed); - copy_task->join(); -} - -TEST(BroadcastRingTest, ThreadedCopyLossy) { - using Ring = Dynamic_32_NxM::Ring; - using Record = Ring::Record; - Ring in_ring; - auto in_mmap = CreateRing(&in_ring, Ring::Traits::MinCount()); - - Ring out_ring; - auto out_mmap = CreateRing(&out_ring, Ring::Traits::MinCount()); - - std::atomic quit(false); - std::unique_ptr copy_task = CopyTask( - &quit, out_mmap.mmap(), out_mmap.size, in_mmap.mmap(), in_mmap.size); - - constexpr uint32_t kRecordsToProcess = 100000; - uint32_t out_records = 0; - uint32_t in_records = 0; - uint32_t in_sequence = in_ring.GetNextSequence(); - while (out_records < kRecordsToProcess) { - const Record out_record(FillChar(out_records)); - out_ring.Put(out_record); - out_records++; - - Record in_record; - if (in_ring.GetNewest(&in_sequence, &in_record)) { - EXPECT_EQ(Record(in_record.v[0]), in_record); - in_records++; - in_sequence++; - } - } - - EXPECT_EQ(kRecordsToProcess, out_records); - EXPECT_GE(kRecordsToProcess, in_records); - - std::atomic_store_explicit(&quit, true, std::memory_order_relaxed); - copy_task->join(); -} - -template -std::unique_ptr CheckFillTask(std::atomic* quit, - void* in_base, size_t in_size) { - return std::unique_ptr( - new std::thread([quit, in_base, in_size]() { - using Record = typename Ring::Record; - - bool import_ok; - Ring in_ring; - std::tie(in_ring, import_ok) = Ring::Import(in_base, in_size); - ASSERT_TRUE(import_ok); - - uint32_t sequence = in_ring.GetOldestSequence(); - while (!std::atomic_load_explicit(quit, std::memory_order_relaxed)) { - Record record; - if (in_ring.Get(&sequence, &record)) { - ASSERT_EQ(Record(record.v[0]), record); - sequence++; - } - } - })); -} - -template -void ThreadedOverwriteTorture() { - using Record = typename Ring::Record; - - // Maximize overwrites by having few records. - const int kMinRecordCount = 1; - const int kMaxRecordCount = 4; - - for (int count = kMinRecordCount; count <= kMaxRecordCount; count *= 2) { - Ring out_ring; - auto out_mmap = CreateRing(&out_ring, count); - - std::atomic quit(false); - std::unique_ptr check_task = - CheckFillTask(&quit, out_mmap.mmap(), out_mmap.size); - - constexpr int kIterations = 10000; - for (int i = 0; i < kIterations; ++i) { - const Record record(FillChar(i)); - out_ring.Put(record); - } - - std::atomic_store_explicit(&quit, true, std::memory_order_relaxed); - check_task->join(); - } -} - -TEST(BroadcastRingTest, ThreadedOverwriteTortureSmall) { - ThreadedOverwriteTorture(); -} - -TEST(BroadcastRingTest, ThreadedOverwriteTortureLarge) { - ThreadedOverwriteTorture(); -} - -} // namespace dvr -} // namespace android diff --git a/libs/vr/libbroadcastring/include/libbroadcastring/broadcast_ring.h b/libs/vr/libbroadcastring/include/libbroadcastring/broadcast_ring.h deleted file mode 100644 index f2e5034879..0000000000 --- a/libs/vr/libbroadcastring/include/libbroadcastring/broadcast_ring.h +++ /dev/null @@ -1,692 +0,0 @@ -#ifndef ANDROID_DVR_BROADCAST_RING_H_ -#define ANDROID_DVR_BROADCAST_RING_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "android-base/logging.h" - -#if ATOMIC_LONG_LOCK_FREE != 2 || ATOMIC_INT_LOCK_FREE != 2 -#error "This file requires lock free atomic uint32_t and long" -#endif - -namespace android { -namespace dvr { - -struct DefaultRingTraits { - // Set this to false to allow compatibly expanding the record size. - static constexpr bool kUseStaticRecordSize = false; - - // Set this to a nonzero value to fix the number of records in the ring. - static constexpr uint32_t kStaticRecordCount = 0; - - // Set this to the max number of records that can be written simultaneously. - static constexpr uint32_t kMaxReservedRecords = 1; - - // Set this to the min number of records that must be readable. - static constexpr uint32_t kMinAvailableRecords = 1; -}; - -// Nonblocking ring suitable for concurrent single-writer, multi-reader access. -// -// Readers never block the writer and thus this is a nondeterministically lossy -// transport in the absence of external synchronization. Don't use this as a -// transport when deterministic behavior is required. -// -// Readers may have a read-only mapping; each reader's state is a single local -// sequence number. -// -// The implementation takes care to avoid data races on record access. -// Inconsistent data can only be returned if at least 2^32 records are written -// during the read-side critical section. -// -// In addition, both readers and the writer are careful to avoid accesses -// outside the bounds of the mmap area passed in during initialization even if -// there is a misbehaving or malicious task with write access to the mmap area. -// -// When dynamic record size is enabled, readers use the record size in the ring -// header when indexing the ring, so that it is possible to extend the record -// type without breaking the read-side ABI. -// -// Avoid calling Put() in a tight loop; there should be significantly more time -// between successive puts than it takes to read one record from memory to -// ensure Get() completes quickly. This requirement should not be difficult to -// achieve for most practical uses; 4kB puts at 10,000Hz is well below the -// scaling limit on current mobile chips. -// -// Example Writer Usage: -// -// using Record = MyRecordType; -// using Ring = BroadcastRing; -// -// uint32_t record_count = kMyDesiredCount; -// uint32_t ring_size = Ring::MemorySize(record_count); -// -// size_t page_size = sysconf(_SC_PAGESIZE); -// uint32_t mmap_size = (ring_size + (page_size - 1)) & ~(page_size - 1); -// -// // Allocate & map via your preferred mechanism, e.g. -// int fd = open("/dev/shm/ring_test", O_CREAT|O_RDWR|O_CLOEXEC, 0600); -// CHECK(fd >= 0); -// CHECK(!ftruncate(fd, ring_size)); -// void *mmap_base = mmap(nullptr, mmap_size, PROT_READ|PROT_WRITE, -// MAP_SHARED, fd, 0); -// CHECK(mmap_base != MAP_FAILED); -// close(fd); -// -// Ring ring = Ring::Create(mmap_base, mmap_size, record_count); -// -// while (!done) -// ring.Put(BuildNextRecordBlocking()); -// -// CHECK(!munmap(mmap_base, mmap_size)); -// -// Example Reader Usage: -// -// using Record = MyRecordType; -// using Ring = BroadcastRing; -// -// // Map via your preferred mechanism, e.g. -// int fd = open("/dev/shm/ring_test", O_RDONLY|O_CLOEXEC); -// CHECK(fd >= 0); -// struct stat st; -// CHECK(!fstat(fd, &st)); -// size_t mmap_size = st.st_size; -// void *mmap_base = mmap(nullptr, mmap_size, PROT_READ, -// MAP_SHARED, fd, 0); -// CHECK(mmap_base != MAP_FAILED); -// close(fd); -// -// Ring ring; -// bool import_ok; -// std::tie(ring, import_ok) = Ring::Import(mmap_base, mmap_size); -// CHECK(import_ok); -// -// uint32_t sequence; -// -// // Choose starting point (using "0" is unpredictable but not dangerous) -// sequence = ring.GetOldestSequence(); // The oldest available -// sequence = ring.GetNewestSequence(); // The newest available -// sequence = ring.GetNextSequence(); // The next one produced -// -// while (!done) { -// Record record; -// -// if (you_want_to_process_all_available_records) { -// while (ring.Get(&sequence, &record)) { -// ProcessRecord(sequence, record); -// sequence++; -// } -// } else if (you_want_to_skip_to_the_newest_record) { -// if (ring.GetNewest(&sequence, &record)) { -// ProcessRecord(sequence, record); -// sequence++; -// } -// } -// -// DoSomethingExpensiveOrBlocking(); -// } -// -// CHECK(!munmap(mmap_base, mmap_size)); -// -template -class BroadcastRing { - public: - using Record = RecordType; - struct Traits : public BaseTraits { - // Must have enough space for writers, plus enough space for readers. - static constexpr int kMinRecordCount = - BaseTraits::kMaxReservedRecords + BaseTraits::kMinAvailableRecords; - - // Count of zero means dynamic, non-zero means static. - static constexpr bool kUseStaticRecordCount = - (BaseTraits::kStaticRecordCount != 0); - - // If both record size and count are static then the overall size is too. - static constexpr bool kIsStaticSize = - BaseTraits::kUseStaticRecordSize && kUseStaticRecordCount; - }; - - static constexpr bool IsPowerOfTwo(uint32_t size) { - return (size & (size - 1)) == 0; - } - - // Sanity check the options provided in Traits. - static_assert(Traits::kMinRecordCount >= 1, "Min record count too small"); - static_assert(!Traits::kUseStaticRecordCount || - Traits::kStaticRecordCount >= Traits::kMinRecordCount, - "Static record count is too small"); - static_assert(!Traits::kStaticRecordCount || - IsPowerOfTwo(Traits::kStaticRecordCount), - "Static record count is not a power of two"); - static_assert(std::is_standard_layout::value, - "Record type must be standard layout"); - - BroadcastRing() {} - - // Creates a new ring at |mmap| with |record_count| records. - // - // There must be at least |MemorySize(record_count)| bytes of space already - // allocated at |mmap|. The ring does not take ownership. - static BroadcastRing Create(void* mmap, size_t mmap_size, - uint32_t record_count) { - BroadcastRing ring(mmap); - CHECK(ring.ValidateGeometry(mmap_size, sizeof(Record), record_count)); - ring.InitializeHeader(sizeof(Record), record_count); - return ring; - } - - // Creates a new ring at |mmap|. - // - // There must be at least |MemorySize()| bytes of space already allocated at - // |mmap|. The ring does not take ownership. - static BroadcastRing Create(void* mmap, size_t mmap_size) { - return Create(mmap, mmap_size, - Traits::kUseStaticRecordCount - ? Traits::kStaticRecordCount - : BroadcastRing::GetRecordCount(mmap_size)); - } - - // Imports an existing ring at |mmap|. - // - // Import may fail if the ring parameters in the mmap header are not sensible. - // In this case the returned boolean is false; make sure to check this value. - static std::tuple Import(void* mmap, size_t mmap_size) { - BroadcastRing ring(mmap); - uint32_t record_size = 0; - uint32_t record_count = 0; - if (mmap_size >= sizeof(Header)) { - record_size = std::atomic_load_explicit(&ring.header_mmap()->record_size, - std::memory_order_relaxed); - record_count = std::atomic_load_explicit( - &ring.header_mmap()->record_count, std::memory_order_relaxed); - } - bool ok = ring.ValidateGeometry(mmap_size, record_size, record_count); - return std::make_tuple(ring, ok); - } - - ~BroadcastRing() {} - - // Calculates the space necessary for a ring of size |record_count|. - // - // Use this function for dynamically sized rings. - static constexpr size_t MemorySize(uint32_t record_count) { - return sizeof(Header) + sizeof(Record) * record_count; - } - - // Calculates the space necessary for a statically sized ring. - // - // Use this function for statically sized rings. - static constexpr size_t MemorySize() { - static_assert( - Traits::kUseStaticRecordCount, - "Wrong MemorySize() function called for dynamic record count"); - return MemorySize(Traits::kStaticRecordCount); - } - - static uint32_t NextPowerOf2(uint32_t n) { - if (n == 0) - return 0; - n -= 1; - n |= n >> 16; - n |= n >> 8; - n |= n >> 4; - n |= n >> 2; - n |= n >> 1; - return n + 1; - } - - // Gets the biggest power of 2 record count that can fit into this mmap. - // - // The header size has been taken into account. - static uint32_t GetRecordCount(size_t mmap_size) { - if (mmap_size <= sizeof(Header)) { - return 0; - } - uint32_t count = - static_cast((mmap_size - sizeof(Header)) / sizeof(Record)); - return IsPowerOfTwo(count) ? count : (NextPowerOf2(count) / 2); - } - - // Writes a record to the ring. - // - // The oldest record is overwritten unless the ring is not already full. - void Put(const Record& record) { - const int kRecordCount = 1; - Reserve(kRecordCount); - Geometry geometry = GetGeometry(); - PutRecordInternal(&record, record_mmap_writer(geometry.tail_index)); - Publish(kRecordCount); - } - - // Gets sequence number of the oldest currently available record. - uint32_t GetOldestSequence() const { - return std::atomic_load_explicit(&header_mmap()->head, - std::memory_order_relaxed); - } - - // Gets sequence number of the first future record. - // - // If the returned value is passed to Get() and there is no concurrent Put(), - // Get() will return false. - uint32_t GetNextSequence() const { - return std::atomic_load_explicit(&header_mmap()->tail, - std::memory_order_relaxed); - } - - // Gets sequence number of the newest currently available record. - uint32_t GetNewestSequence() const { return GetNextSequence() - 1; } - - // Copies the oldest available record with sequence at least |*sequence| to - // |record|. - // - // Returns false if there is no recent enough record available. - // - // Updates |*sequence| with the sequence number of the record returned. To get - // the following record, increment this number by one. - // - // This function synchronizes with two other operations: - // - // (1) Load-Acquire of |tail| - // - // Together with the store-release in Publish(), this load-acquire - // ensures each store to a record in PutRecordInternal() happens-before - // any corresponding load in GetRecordInternal(). - // - // i.e. the stores for the records with sequence numbers < |tail| have - // completed from our perspective - // - // (2) Acquire Fence between record access & final load of |head| - // - // Together with the release fence in Reserve(), this ensures that if - // GetRecordInternal() loads a value stored in some execution of - // PutRecordInternal(), then the store of |head| in the Reserve() that - // preceeded it happens-before our final load of |head|. - // - // i.e. if we read a record with sequence number >= |final_head| then - // no later store to that record has completed from our perspective - bool Get(uint32_t* sequence /*inout*/, Record* record /*out*/) const { - for (;;) { - uint32_t tail = std::atomic_load_explicit(&header_mmap()->tail, - std::memory_order_acquire); - uint32_t head = std::atomic_load_explicit(&header_mmap()->head, - std::memory_order_relaxed); - - if (tail - head > record_count()) - continue; // Concurrent modification; re-try. - - if (*sequence - head > tail - head) - *sequence = head; // Out of window, skip forward to first available. - - if (*sequence == tail) return false; // No new records available. - - Geometry geometry = - CalculateGeometry(record_count(), record_size(), *sequence, tail); - - // Compute address explicitly in case record_size > sizeof(Record). - RecordStorage* record_storage = record_mmap_reader(geometry.head_index); - - GetRecordInternal(record_storage, record); - - // NB: It is not sufficient to change this to a load-acquire of |head|. - std::atomic_thread_fence(std::memory_order_acquire); - - uint32_t final_head = std::atomic_load_explicit( - &header_mmap()->head, std::memory_order_relaxed); - - if (final_head - head > *sequence - head) - continue; // Concurrent modification; re-try. - - // Note: Combining the above 4 comparisons gives: - // 0 <= final_head - head <= sequence - head < tail - head <= record_count - // - // We can also write this as: - // head <=* final_head <=* sequence <* tail <=* head + record_count - // - // where <* orders by difference from head: x <* y if x - head < y - head. - // This agrees with the order of sequence updates during "put" operations. - return true; - } - } - - // Copies the newest available record with sequence at least |*sequence| to - // |record|. - // - // Returns false if there is no recent enough record available. - // - // Updates |*sequence| with the sequence number of the record returned. To get - // the following record, increment this number by one. - bool GetNewest(uint32_t* sequence, Record* record) const { - uint32_t newest_sequence = GetNewestSequence(); - if (*sequence == newest_sequence + 1) return false; - *sequence = newest_sequence; - return Get(sequence, record); - } - - // Returns true if this instance has been created or imported. - bool is_valid() const { return !!data_.mmap; } - - uint32_t record_count() const { return record_count_internal(); } - uint32_t record_size() const { return record_size_internal(); } - static constexpr uint32_t mmap_alignment() { return alignof(Mmap); } - - private: - struct Header { - // Record size for reading out of the ring. Writers always write the full - // length; readers may need to read a prefix of each record. - std::atomic record_size; - - // Number of records in the ring. - std::atomic record_count; - - // Readable region is [head % record_count, tail % record_count). - // - // The region in [tail % record_count, head % record_count) was either never - // populated or is being updated. - // - // These are sequences numbers, not indexes - indexes should be computed - // with a modulus. - // - // To ensure consistency: - // - // (1) Writes advance |head| past any updated records before writing to - // them, and advance |tail| after they are written. - // (2) Readers check |tail| before reading data and |head| after, - // making sure to discard any data that was written to concurrently. - std::atomic head; - std::atomic tail; - }; - - // Store using the standard word size. - using StorageType = long; // NOLINT - - // Always require 8 byte alignment so that the same record sizes are legal on - // 32 and 64 bit builds. - static constexpr size_t kRecordAlignment = 8; - static_assert(kRecordAlignment % sizeof(StorageType) == 0, - "Bad record alignment"); - - struct RecordStorage { - // This is accessed with relaxed atomics to prevent data races on the - // contained data, which would be undefined behavior. - std::atomic data[sizeof(Record) / sizeof(StorageType)]; - }; - - static_assert(sizeof(StorageType) * - std::extent() == - sizeof(Record), - "Record length must be a multiple of sizeof(StorageType)"); - - struct Geometry { - // Static geometry. - uint32_t record_count; - uint32_t record_size; - - // Copy of atomic sequence counts. - uint32_t head; - uint32_t tail; - - // First index of readable region. - uint32_t head_index; - - // First index of writable region. - uint32_t tail_index; - - // Number of records in readable region. - uint32_t count; - - // Number of records in writable region. - uint32_t space; - }; - - // Mmap area layout. - // - // Readers should not index directly into |records| as this is not valid when - // dynamic record sizes are used; use record_mmap_reader() instead. - struct Mmap { - Header header; - RecordStorage records[]; - }; - - static_assert(std::is_standard_layout::value, - "Mmap must be standard layout"); - static_assert(sizeof(std::atomic) == sizeof(uint32_t), - "Lockless atomics contain extra state"); - static_assert(sizeof(std::atomic) == sizeof(StorageType), - "Lockless atomics contain extra state"); - - explicit BroadcastRing(void* mmap) { - CHECK_EQ(0U, reinterpret_cast(mmap) % alignof(Mmap)); - data_.mmap = reinterpret_cast(mmap); - } - - // Initializes the mmap area header for a new ring. - void InitializeHeader(uint32_t record_size, uint32_t record_count) { - constexpr uint32_t kInitialSequence = -256; // Force an early wrap. - std::atomic_store_explicit(&header_mmap()->record_size, record_size, - std::memory_order_relaxed); - std::atomic_store_explicit(&header_mmap()->record_count, record_count, - std::memory_order_relaxed); - std::atomic_store_explicit(&header_mmap()->head, kInitialSequence, - std::memory_order_relaxed); - std::atomic_store_explicit(&header_mmap()->tail, kInitialSequence, - std::memory_order_relaxed); - } - - // Validates ring geometry. - // - // Ring geometry is validated carefully on import and then cached. This allows - // us to avoid out-of-range accesses even if the parameters in the header are - // later changed. - bool ValidateGeometry(size_t mmap_size, uint32_t header_record_size, - uint32_t header_record_count) { - set_record_size(header_record_size); - set_record_count(header_record_count); - - if (record_size() != header_record_size) return false; - if (record_count() != header_record_count) return false; - if (record_count() < Traits::kMinRecordCount) return false; - if (record_size() < sizeof(Record)) return false; - if (record_size() % kRecordAlignment != 0) return false; - if (!IsPowerOfTwo(record_count())) return false; - - size_t memory_size = record_count() * record_size(); - if (memory_size / record_size() != record_count()) return false; - if (memory_size + sizeof(Header) < memory_size) return false; - if (memory_size + sizeof(Header) > mmap_size) return false; - - return true; - } - - // Copies a record into the ring. - // - // This is done with relaxed atomics because otherwise it is racy according to - // the C++ memory model. This is very low overhead once optimized. - static inline void PutRecordInternal(const Record* in, RecordStorage* out) { - StorageType data[sizeof(Record) / sizeof(StorageType)]; - memcpy(data, in, sizeof(*in)); - for (size_t i = 0; i < std::extent(); ++i) { - std::atomic_store_explicit(&out->data[i], data[i], - std::memory_order_relaxed); - } - } - - // Copies a record out of the ring. - // - // This is done with relaxed atomics because otherwise it is racy according to - // the C++ memory model. This is very low overhead once optimized. - static inline void GetRecordInternal(RecordStorage* in, Record* out) { - StorageType data[sizeof(Record) / sizeof(StorageType)]; - for (size_t i = 0; i < std::extent(); ++i) { - data[i] = - std::atomic_load_explicit(&in->data[i], std::memory_order_relaxed); - } - memcpy(out, &data, sizeof(*out)); - } - - // Converts a record's sequence number into a storage index. - static uint32_t SequenceToIndex(uint32_t sequence, uint32_t record_count) { - return sequence & (record_count - 1); - } - - // Computes readable & writable ranges from ring parameters. - static Geometry CalculateGeometry(uint32_t record_count, uint32_t record_size, - uint32_t head, uint32_t tail) { - Geometry geometry; - geometry.record_count = record_count; - geometry.record_size = record_size; - DCHECK_EQ(0U, geometry.record_size % kRecordAlignment); - geometry.head = head; - geometry.tail = tail; - geometry.head_index = SequenceToIndex(head, record_count); - geometry.tail_index = SequenceToIndex(tail, record_count); - geometry.count = geometry.tail - geometry.head; - DCHECK_LE(geometry.count, record_count); - geometry.space = geometry.record_count - geometry.count; - return geometry; - } - - // Gets the current ring readable & writable regions. - // - // This this is always safe from the writing thread since it is the only - // thread allowed to update the header. - Geometry GetGeometry() const { - return CalculateGeometry( - record_count(), record_size(), - std::atomic_load_explicit(&header_mmap()->head, - std::memory_order_relaxed), - std::atomic_load_explicit(&header_mmap()->tail, - std::memory_order_relaxed)); - } - - // Makes space for at least |reserve_count| records. - // - // There is nothing to prevent overwriting records that have concurrent - // readers. We do however ensure that this situation can be detected: the - // fence ensures the |head| update will be the first update seen by readers, - // and readers check this value after reading and discard data that may have - // been concurrently modified. - void Reserve(uint32_t reserve_count) { - Geometry geometry = GetGeometry(); - DCHECK_LE(reserve_count, Traits::kMaxReservedRecords); - uint32_t needed = - (geometry.space >= reserve_count ? 0 : reserve_count - geometry.space); - - std::atomic_store_explicit(&header_mmap()->head, geometry.head + needed, - std::memory_order_relaxed); - - // NB: It is not sufficient to change this to a store-release of |head|. - std::atomic_thread_fence(std::memory_order_release); - } - - // Makes |publish_count| records visible to readers. - // - // Space must have been reserved by a previous call to Reserve(). - void Publish(uint32_t publish_count) { - Geometry geometry = GetGeometry(); - DCHECK_LE(publish_count, geometry.space); - std::atomic_store_explicit(&header_mmap()->tail, - geometry.tail + publish_count, - std::memory_order_release); - } - - // Helpers to compute addresses in mmap area. - Mmap* mmap() const { return data_.mmap; } - Header* header_mmap() const { return &data_.mmap->header; } - RecordStorage* record_mmap_writer(uint32_t index) const { - DCHECK_EQ(sizeof(Record), record_size()); - return &data_.mmap->records[index]; - } - RecordStorage* record_mmap_reader(uint32_t index) const { - if (Traits::kUseStaticRecordSize) { - return &data_.mmap->records[index]; - } else { - // Calculate the location of a record in the ring without assuming that - // sizeof(Record) == record_size. - return reinterpret_cast( - reinterpret_cast(data_.mmap->records) + index * record_size()); - } - } - - // The following horrifying template gunk enables us to store just the mmap - // base pointer for compile-time statically sized rings. Dynamically sized - // rings also store the validated copy of the record size & count. - // - // This boils down to: use a compile time constant if available, and otherwise - // load the value that was validated on import from a member variable. - template - typename std::enable_if::type - record_size_internal() const { - return sizeof(Record); - } - - template - typename std::enable_if::type - record_size_internal() const { - return data_.record_size; - } - - template - typename std::enable_if::type set_record_size( - uint32_t /*record_size*/) {} - - template - typename std::enable_if::type set_record_size( - uint32_t record_size) { - data_.record_size = record_size; - } - - template - typename std::enable_if::type - record_count_internal() const { - return Traits::kStaticRecordCount; - } - - template - typename std::enable_if::type - record_count_internal() const { - return data_.record_count; - } - - template - typename std::enable_if::type - set_record_count(uint32_t /*record_count*/) const {} - - template - typename std::enable_if::type - set_record_count(uint32_t record_count) { - data_.record_count = record_count; - } - - // Data we need to store for statically sized rings. - struct DataStaticSize { - Mmap* mmap = nullptr; - }; - - // Data we need to store for dynamically sized rings. - struct DataDynamicSize { - Mmap* mmap = nullptr; - - // These are cached to make sure misbehaving writers cannot cause - // out-of-bounds memory accesses by updating the values in the mmap header. - uint32_t record_size = 0; - uint32_t record_count = 0; - }; - - using DataStaticOrDynamic = - typename std::conditional::type; - - DataStaticOrDynamic data_; -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_BROADCAST_RING_H_ diff --git a/libs/vr/libbufferhub/Android.bp b/libs/vr/libbufferhub/Android.bp deleted file mode 100644 index 583ad1dd94..0000000000 --- a/libs/vr/libbufferhub/Android.bp +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (C) 2016 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 { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_library_headers { - name: "libbufferhub_headers", - export_include_dirs: ["include"], - vendor_available: true, // TODO(b/112338314): Does shouldn't be available to vendor. - apex_available: [ - "//apex_available:platform", - "com.android.media", - "com.android.media.swcodec", - ], - min_sdk_version: "29", -} - -sourceFiles = [ - "buffer_hub_base.cpp", - "buffer_hub_rpc.cpp", - "consumer_buffer.cpp", - "ion_buffer.cpp", - "producer_buffer.cpp", -] - -sharedLibraries = [ - "libbase", - "libcutils", - "liblog", - "libui", - "libutils", - "libpdx_default_transport", -] - -headerLibraries = [ - "libbufferhub_headers", - "libdvr_headers", - "libnativebase_headers", -] - -cc_library { - srcs: sourceFiles, - cflags: [ - "-DLOG_TAG=\"libbufferhub\"", - "-DTRACE=0", - "-DATRACE_TAG=ATRACE_TAG_GRAPHICS", - "-Wall", - "-Werror", - ], - shared_libs: sharedLibraries, - header_libs: headerLibraries, - name: "libbufferhub", - export_header_lib_headers: [ - "libbufferhub_headers", - "libnativebase_headers", - ], -} - -cc_test { - srcs: ["buffer_hub-test.cpp"], - static_libs: ["libbufferhub"], - shared_libs: sharedLibraries, - header_libs: headerLibraries, - name: "buffer_hub-test", -} diff --git a/libs/vr/libbufferhub/buffer_hub-test.cpp b/libs/vr/libbufferhub/buffer_hub-test.cpp deleted file mode 100644 index 27ab0242ad..0000000000 --- a/libs/vr/libbufferhub/buffer_hub-test.cpp +++ /dev/null @@ -1,906 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace { -#define RETRY_EINTR(fnc_call) \ - ([&]() -> decltype(fnc_call) { \ - decltype(fnc_call) result; \ - do { \ - result = (fnc_call); \ - } while (result == -1 && errno == EINTR); \ - return result; \ - })() - -using android::BufferHubDefs::isAnyClientAcquired; -using android::BufferHubDefs::isAnyClientGained; -using android::BufferHubDefs::isAnyClientPosted; -using android::BufferHubDefs::isClientAcquired; -using android::BufferHubDefs::isClientPosted; -using android::BufferHubDefs::isClientReleased; -using android::BufferHubDefs::kFirstClientBitMask; -using android::dvr::ConsumerBuffer; -using android::dvr::ProducerBuffer; -using android::pdx::LocalHandle; -using android::pdx::Status; -using LibBufferHubTest = ::testing::Test; - -const int kWidth = 640; -const int kHeight = 480; -const int kFormat = HAL_PIXEL_FORMAT_RGBA_8888; -const int kUsage = 0; -// Maximum number of consumers for the buffer that only has one producer in the -// test. -const size_t kMaxConsumerCount = - android::BufferHubDefs::kMaxNumberOfClients - 1; -const int kPollTimeoutMs = 100; - -// Helper function to poll the eventfd in BufferHubBase. -template -int PollBufferEvent(const std::unique_ptr& buffer, - int timeout_ms = kPollTimeoutMs) { - pollfd p = {buffer->event_fd(), POLLIN, 0}; - return poll(&p, 1, timeout_ms); -} - -} // namespace - -TEST_F(LibBufferHubTest, TestBasicUsage) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c1 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c1.get() != nullptr); - // Check that consumers can spawn other consumers. - std::unique_ptr c2 = - ConsumerBuffer::Import(c1->CreateConsumer()); - ASSERT_TRUE(c2.get() != nullptr); - - // Checks the state masks of client p, c1 and c2. - EXPECT_EQ(p->client_state_mask(), kFirstClientBitMask); - EXPECT_EQ(c1->client_state_mask(), kFirstClientBitMask << 1); - EXPECT_EQ(c2->client_state_mask(), kFirstClientBitMask << 2); - - // Initial state: producer not available, consumers not available. - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c1))); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c2))); - - EXPECT_EQ(0, p->GainAsync()); - EXPECT_EQ(0, p->Post(LocalHandle())); - - // New state: producer not available, consumers available. - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(1, RETRY_EINTR(PollBufferEvent(c1))); - EXPECT_EQ(1, RETRY_EINTR(PollBufferEvent(c2))); - - LocalHandle fence; - EXPECT_EQ(0, c1->Acquire(&fence)); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c1))); - EXPECT_EQ(1, RETRY_EINTR(PollBufferEvent(c2))); - - EXPECT_EQ(0, c2->Acquire(&fence)); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c2))); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c1))); - - EXPECT_EQ(0, c1->Release(LocalHandle())); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(0, c2->Discard()); - EXPECT_EQ(1, RETRY_EINTR(PollBufferEvent(p))); - - EXPECT_EQ(0, p->Gain(&fence)); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c1))); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c2))); -} - -TEST_F(LibBufferHubTest, TestEpoll) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - - LocalHandle epoll_fd{epoll_create1(EPOLL_CLOEXEC)}; - ASSERT_TRUE(epoll_fd.IsValid()); - - epoll_event event; - std::array events; - - auto event_sources = p->GetEventSources(); - ASSERT_LT(event_sources.size(), events.size()); - - for (const auto& event_source : event_sources) { - event = {.events = event_source.event_mask | EPOLLET, - .data = {.fd = p->event_fd()}}; - ASSERT_EQ(0, epoll_ctl(epoll_fd.Get(), EPOLL_CTL_ADD, event_source.event_fd, - &event)); - } - - event_sources = c->GetEventSources(); - ASSERT_LT(event_sources.size(), events.size()); - - for (const auto& event_source : event_sources) { - event = {.events = event_source.event_mask | EPOLLET, - .data = {.fd = c->event_fd()}}; - ASSERT_EQ(0, epoll_ctl(epoll_fd.Get(), EPOLL_CTL_ADD, event_source.event_fd, - &event)); - } - - // No events should be signaled initially. - ASSERT_EQ(0, epoll_wait(epoll_fd.Get(), events.data(), events.size(), 0)); - - // Gain and post the producer and check for consumer signal. - EXPECT_EQ(0, p->GainAsync()); - EXPECT_EQ(0, p->Post({})); - ASSERT_EQ(1, epoll_wait(epoll_fd.Get(), events.data(), events.size(), - kPollTimeoutMs)); - ASSERT_TRUE(events[0].events & EPOLLIN); - ASSERT_EQ(c->event_fd(), events[0].data.fd); - - // Save the event bits to translate later. - event = events[0]; - - // Check for events again. Edge-triggered mode should prevent any. - EXPECT_EQ(0, epoll_wait(epoll_fd.Get(), events.data(), events.size(), - kPollTimeoutMs)); - EXPECT_EQ(0, epoll_wait(epoll_fd.Get(), events.data(), events.size(), - kPollTimeoutMs)); - EXPECT_EQ(0, epoll_wait(epoll_fd.Get(), events.data(), events.size(), - kPollTimeoutMs)); - EXPECT_EQ(0, epoll_wait(epoll_fd.Get(), events.data(), events.size(), - kPollTimeoutMs)); - - // Translate the events. - auto event_status = c->GetEventMask(event.events); - ASSERT_TRUE(event_status); - ASSERT_TRUE(event_status.get() & EPOLLIN); - - // Check for events again. Edge-triggered mode should prevent any. - EXPECT_EQ(0, epoll_wait(epoll_fd.Get(), events.data(), events.size(), - kPollTimeoutMs)); -} - -TEST_F(LibBufferHubTest, TestStateMask) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - - // It's ok to create up to kMaxConsumerCount consumer buffers. - uint32_t client_state_masks = p->client_state_mask(); - std::array, kMaxConsumerCount> cs; - for (size_t i = 0; i < kMaxConsumerCount; i++) { - cs[i] = ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(cs[i].get() != nullptr); - // Expect all buffers have unique state mask. - EXPECT_EQ(client_state_masks & cs[i]->client_state_mask(), 0U); - client_state_masks |= cs[i]->client_state_mask(); - } - EXPECT_EQ(client_state_masks, ~0U); - - // The 64th creation will fail with out-of-memory error. - auto state = p->CreateConsumer(); - EXPECT_EQ(state.error(), E2BIG); - - // Release any consumer should allow us to re-create. - for (size_t i = 0; i < kMaxConsumerCount; i++) { - client_state_masks &= ~cs[i]->client_state_mask(); - cs[i] = nullptr; - cs[i] = ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(cs[i].get() != nullptr); - // The released state mask will be reused. - EXPECT_EQ(client_state_masks & cs[i]->client_state_mask(), 0U); - client_state_masks |= cs[i]->client_state_mask(); - } -} - -TEST_F(LibBufferHubTest, TestStateTransitions) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - - LocalHandle fence; - EXPECT_EQ(0, p->GainAsync()); - - // Acquire in gained state should fail. - EXPECT_EQ(-EBUSY, c->Acquire(&fence)); - - // Post in gained state should succeed. - EXPECT_EQ(0, p->Post(LocalHandle())); - - // Post and gain in posted state should fail. - EXPECT_EQ(-EBUSY, p->Post(LocalHandle())); - EXPECT_EQ(-EBUSY, p->Gain(&fence)); - - // Acquire in posted state should succeed. - EXPECT_EQ(0, c->Acquire(&fence)); - - // Acquire, post, and gain in acquired state should fail. - EXPECT_EQ(-EBUSY, c->Acquire(&fence)); - EXPECT_EQ(-EBUSY, p->Post(LocalHandle())); - EXPECT_EQ(-EBUSY, p->Gain(&fence)); - - // Release in acquired state should succeed. - EXPECT_EQ(0, c->Release(LocalHandle())); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - - // Acquire and post in released state should fail. - EXPECT_EQ(-EBUSY, c->Acquire(&fence)); - EXPECT_EQ(-EBUSY, p->Post(LocalHandle())); - - // Gain in released state should succeed. - EXPECT_EQ(0, p->Gain(&fence)); - - // Acquire in gained state should fail. - EXPECT_EQ(-EBUSY, c->Acquire(&fence)); -} - -TEST_F(LibBufferHubTest, TestAsyncStateTransitions) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - EXPECT_EQ(0, p->GainAsync()); - - // Acquire in gained state should fail. - EXPECT_EQ(-EBUSY, c->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - EXPECT_FALSE(invalid_fence.IsValid()); - - // Post in gained state should succeed. - EXPECT_EQ(0, p->PostAsync(&metadata, invalid_fence)); - EXPECT_EQ(p->buffer_state(), c->buffer_state()); - EXPECT_TRUE(isAnyClientPosted(p->buffer_state())); - - // Post and gain in posted state should fail. - EXPECT_EQ(-EBUSY, p->PostAsync(&metadata, invalid_fence)); - EXPECT_EQ(-EBUSY, p->GainAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - - // Acquire in posted state should succeed. - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c))); - EXPECT_EQ(0, c->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - EXPECT_EQ(p->buffer_state(), c->buffer_state()); - EXPECT_TRUE(isAnyClientAcquired(p->buffer_state())); - - // Acquire, post, and gain in acquired state should fail. - EXPECT_EQ(-EBUSY, c->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - EXPECT_EQ(-EBUSY, p->PostAsync(&metadata, invalid_fence)); - EXPECT_EQ(-EBUSY, p->GainAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - - // Release in acquired state should succeed. - EXPECT_EQ(0, c->ReleaseAsync(&metadata, invalid_fence)); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(p->buffer_state(), c->buffer_state()); - EXPECT_TRUE(p->is_released()); - - // Acquire and post in released state should fail. - EXPECT_EQ(-EBUSY, c->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - EXPECT_EQ(-EBUSY, p->PostAsync(&metadata, invalid_fence)); - - // Gain in released state should succeed. - EXPECT_EQ(0, p->GainAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); - EXPECT_EQ(p->buffer_state(), c->buffer_state()); - EXPECT_TRUE(isAnyClientGained(p->buffer_state())); - - // Acquire and gain in gained state should fail. - EXPECT_EQ(-EBUSY, c->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_FALSE(invalid_fence.IsValid()); -} - -TEST_F(LibBufferHubTest, TestGainTwiceByTheSameProducer) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - - ASSERT_EQ(0, p->GainAsync()); - ASSERT_EQ(0, p->GainAsync()); -} - -TEST_F(LibBufferHubTest, TestGainPostedBuffer) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - ASSERT_EQ(0, p->GainAsync()); - ASSERT_EQ(0, p->Post(LocalHandle())); - ASSERT_TRUE(isAnyClientPosted(p->buffer_state())); - - // Gain in posted state should only succeed with gain_posted_buffer = true. - LocalHandle invalid_fence; - EXPECT_EQ(-EBUSY, p->Gain(&invalid_fence, false)); - EXPECT_EQ(0, p->Gain(&invalid_fence, true)); -} - -TEST_F(LibBufferHubTest, TestGainPostedBufferAsync) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - ASSERT_EQ(0, p->GainAsync()); - ASSERT_EQ(0, p->Post(LocalHandle())); - ASSERT_TRUE(isAnyClientPosted(p->buffer_state())); - - // GainAsync in posted state should only succeed with gain_posted_buffer - // equals true. - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - EXPECT_EQ(-EBUSY, p->GainAsync(&metadata, &invalid_fence, false)); - EXPECT_EQ(0, p->GainAsync(&metadata, &invalid_fence, true)); -} - -TEST_F(LibBufferHubTest, TestGainPostedBuffer_noConsumer) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - ASSERT_EQ(0, p->GainAsync()); - ASSERT_EQ(0, p->Post(LocalHandle())); - // Producer state bit is in released state after post, other clients shall be - // in posted state although there is no consumer of this buffer yet. - ASSERT_TRUE(isClientReleased(p->buffer_state(), p->client_state_mask())); - ASSERT_TRUE(p->is_released()); - ASSERT_TRUE(isAnyClientPosted(p->buffer_state())); - - // Gain in released state should succeed. - LocalHandle invalid_fence; - EXPECT_EQ(0, p->Gain(&invalid_fence, false)); -} - -TEST_F(LibBufferHubTest, TestMaxConsumers) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - uint32_t producer_state_mask = p->client_state_mask(); - - std::array, kMaxConsumerCount> cs; - for (size_t i = 0; i < kMaxConsumerCount; ++i) { - cs[i] = ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(cs[i].get() != nullptr); - EXPECT_TRUE(cs[i]->is_released()); - EXPECT_NE(producer_state_mask, cs[i]->client_state_mask()); - } - - EXPECT_EQ(0, p->GainAsync()); - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - - // Post the producer should trigger all consumers to be available. - EXPECT_EQ(0, p->PostAsync(&metadata, invalid_fence)); - EXPECT_TRUE(isClientReleased(p->buffer_state(), p->client_state_mask())); - for (size_t i = 0; i < kMaxConsumerCount; ++i) { - EXPECT_TRUE( - isClientPosted(cs[i]->buffer_state(), cs[i]->client_state_mask())); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(cs[i]))); - EXPECT_EQ(0, cs[i]->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_TRUE( - isClientAcquired(p->buffer_state(), cs[i]->client_state_mask())); - } - - // All consumers have to release before the buffer is considered to be - // released. - for (size_t i = 0; i < kMaxConsumerCount; i++) { - EXPECT_FALSE(p->is_released()); - EXPECT_EQ(0, cs[i]->ReleaseAsync(&metadata, invalid_fence)); - } - - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_TRUE(p->is_released()); - - // Buffer state cross all clients must be consistent. - for (size_t i = 0; i < kMaxConsumerCount; i++) { - EXPECT_EQ(p->buffer_state(), cs[i]->buffer_state()); - } -} - -TEST_F(LibBufferHubTest, TestCreateConsumerWhenBufferGained) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - EXPECT_TRUE(isAnyClientGained(p->buffer_state())); - - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_TRUE(isAnyClientGained(c->buffer_state())); - - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - - // Post the gained buffer should signal already created consumer. - EXPECT_EQ(0, p->PostAsync(&metadata, invalid_fence)); - EXPECT_TRUE(isAnyClientPosted(p->buffer_state())); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c))); - EXPECT_EQ(0, c->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_TRUE(isAnyClientAcquired(c->buffer_state())); -} - -TEST_F(LibBufferHubTest, TestCreateTheFirstConsumerAfterPostingBuffer) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - EXPECT_TRUE(isAnyClientGained(p->buffer_state())); - - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - - // Post the gained buffer before any consumer gets created. - EXPECT_EQ(0, p->PostAsync(&metadata, invalid_fence)); - EXPECT_TRUE(p->is_released()); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(p))); - - // Newly created consumer will be signalled for the posted buffer although it - // is created after producer posting. - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_TRUE(isClientPosted(c->buffer_state(), c->client_state_mask())); - EXPECT_EQ(0, c->AcquireAsync(&metadata, &invalid_fence)); -} - -TEST_F(LibBufferHubTest, TestCreateConsumerWhenBufferReleased) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - - std::unique_ptr c1 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c1.get() != nullptr); - - EXPECT_EQ(0, p->GainAsync()); - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - - // Post, acquire, and release the buffer.. - EXPECT_EQ(0, p->PostAsync(&metadata, invalid_fence)); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c1))); - EXPECT_EQ(0, c1->AcquireAsync(&metadata, &invalid_fence)); - EXPECT_EQ(0, c1->ReleaseAsync(&metadata, invalid_fence)); - - // Note that the next PDX call is on the producer channel, which may be - // executed before Release impulse gets executed by bufferhubd. Thus, here we - // need to wait until the releasd is confirmed before creating another - // consumer. - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_TRUE(p->is_released()); - - // Create another consumer immediately after the release, should not make the - // buffer un-released. - std::unique_ptr c2 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c2.get() != nullptr); - - EXPECT_TRUE(p->is_released()); - EXPECT_EQ(0, p->GainAsync(&metadata, &invalid_fence)); - EXPECT_TRUE(isAnyClientGained(p->buffer_state())); -} - -TEST_F(LibBufferHubTest, TestWithCustomMetadata) { - struct Metadata { - int64_t field1; - int64_t field2; - }; - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(Metadata)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - Metadata m = {1, 3}; - EXPECT_EQ(0, p->Post(LocalHandle(), &m, sizeof(Metadata))); - EXPECT_LE(0, RETRY_EINTR(PollBufferEvent(c))); - LocalHandle fence; - Metadata m2 = {}; - EXPECT_EQ(0, c->Acquire(&fence, &m2, sizeof(m2))); - EXPECT_EQ(m.field1, m2.field1); - EXPECT_EQ(m.field2, m2.field2); - EXPECT_EQ(0, c->Release(LocalHandle())); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p, /*timeout_ms=*/0))); -} - -TEST_F(LibBufferHubTest, TestPostWithWrongMetaSize) { - struct Metadata { - int64_t field1; - int64_t field2; - }; - struct OverSizedMetadata { - int64_t field1; - int64_t field2; - int64_t field3; - }; - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(Metadata)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - - // It is illegal to post metadata larger than originally requested during - // buffer allocation. - OverSizedMetadata evil_meta = {}; - EXPECT_NE(0, p->Post(LocalHandle(), &evil_meta, sizeof(OverSizedMetadata))); - EXPECT_GE(0, RETRY_EINTR(PollBufferEvent(c))); - - // It is ok to post metadata smaller than originally requested during - // buffer allocation. - EXPECT_EQ(0, p->Post(LocalHandle())); -} - -TEST_F(LibBufferHubTest, TestAcquireWithWrongMetaSize) { - struct Metadata { - int64_t field1; - int64_t field2; - }; - struct OverSizedMetadata { - int64_t field1; - int64_t field2; - int64_t field3; - }; - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(Metadata)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - - Metadata m = {1, 3}; - EXPECT_EQ(0, p->Post(LocalHandle(), &m, sizeof(m))); - - LocalHandle fence; - int64_t sequence; - OverSizedMetadata e; - - // It is illegal to acquire metadata larger than originally requested during - // buffer allocation. - EXPECT_NE(0, c->Acquire(&fence, &e, sizeof(e))); - - // It is ok to acquire metadata smaller than originally requested during - // buffer allocation. - EXPECT_EQ(0, c->Acquire(&fence, &sequence, sizeof(sequence))); - EXPECT_EQ(m.field1, sequence); -} - -TEST_F(LibBufferHubTest, TestAcquireWithNoMeta) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - - int64_t sequence = 3; - EXPECT_EQ(0, p->Post(LocalHandle(), &sequence, sizeof(sequence))); - - LocalHandle fence; - EXPECT_EQ(0, c->Acquire(&fence)); -} - -TEST_F(LibBufferHubTest, TestWithNoMeta) { - std::unique_ptr p = - ProducerBuffer::Create(kWidth, kHeight, kFormat, kUsage); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - - LocalHandle fence; - - EXPECT_EQ(0, p->Post(LocalHandle())); - EXPECT_EQ(0, c->Acquire(&fence)); -} - -TEST_F(LibBufferHubTest, TestFailureToPostMetaFromABufferWithoutMeta) { - std::unique_ptr p = - ProducerBuffer::Create(kWidth, kHeight, kFormat, kUsage); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - - int64_t sequence = 3; - EXPECT_NE(0, p->Post(LocalHandle(), &sequence, sizeof(sequence))); -} - -namespace { - -int PollFd(int fd, int timeout_ms) { - pollfd p = {fd, POLLIN, 0}; - return poll(&p, 1, timeout_ms); -} - -} // namespace - -TEST_F(LibBufferHubTest, TestAcquireFence) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, /*metadata_size=*/0); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c.get() != nullptr); - EXPECT_EQ(0, p->GainAsync()); - - DvrNativeBufferMetadata meta; - LocalHandle f1(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)); - - // Post with unsignaled fence. - EXPECT_EQ(0, p->PostAsync(&meta, f1)); - - // Should acquire a valid fence. - LocalHandle f2; - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c))); - EXPECT_EQ(0, c->AcquireAsync(&meta, &f2)); - EXPECT_TRUE(f2.IsValid()); - // The original fence and acquired fence should have different fd number. - EXPECT_NE(f1.Get(), f2.Get()); - EXPECT_GE(0, PollFd(f2.Get(), 0)); - - // Signal the original fence will trigger the new fence. - eventfd_write(f1.Get(), 1); - // Now the original FD has been signaled. - EXPECT_LT(0, PollFd(f2.Get(), kPollTimeoutMs)); - - // Release the consumer with an invalid fence. - EXPECT_EQ(0, c->ReleaseAsync(&meta, LocalHandle())); - - // Should gain an invalid fence. - LocalHandle f3; - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(0, p->GainAsync(&meta, &f3)); - EXPECT_FALSE(f3.IsValid()); - - // Post with a signaled fence. - EXPECT_EQ(0, p->PostAsync(&meta, f1)); - - // Should acquire a valid fence and it's already signalled. - LocalHandle f4; - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c))); - EXPECT_EQ(0, c->AcquireAsync(&meta, &f4)); - EXPECT_TRUE(f4.IsValid()); - EXPECT_LT(0, PollFd(f4.Get(), kPollTimeoutMs)); - - // Release with an unsignalled fence and signal it immediately after release - // without producer gainning. - LocalHandle f5(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)); - EXPECT_EQ(0, c->ReleaseAsync(&meta, f5)); - eventfd_write(f5.Get(), 1); - - // Should gain a valid fence, which is already signaled. - LocalHandle f6; - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - EXPECT_EQ(0, p->GainAsync(&meta, &f6)); - EXPECT_TRUE(f6.IsValid()); - EXPECT_LT(0, PollFd(f6.Get(), kPollTimeoutMs)); -} - -TEST_F(LibBufferHubTest, TestOrphanedAcquire) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c1 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c1.get() != nullptr); - const uint32_t client_state_mask1 = c1->client_state_mask(); - - EXPECT_EQ(0, p->GainAsync()); - DvrNativeBufferMetadata meta; - EXPECT_EQ(0, p->PostAsync(&meta, LocalHandle())); - - LocalHandle fence; - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c1))); - EXPECT_EQ(0, c1->AcquireAsync(&meta, &fence)); - - // Destroy the consumer who has acquired but not released the buffer. - c1 = nullptr; - - // The buffer is now available for the producer to gain. - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - - // Newly added consumer is not able to acquire the buffer. - std::unique_ptr c2 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c2.get() != nullptr); - const uint32_t client_state_mask2 = c2->client_state_mask(); - EXPECT_NE(client_state_mask1, client_state_mask2); - EXPECT_EQ(0, RETRY_EINTR(PollBufferEvent(c2))); - EXPECT_EQ(-EBUSY, c2->AcquireAsync(&meta, &fence)); - - // Producer should be able to gain. - EXPECT_EQ(0, p->GainAsync(&meta, &fence, false)); -} - -TEST_F(LibBufferHubTest, TestAcquireLastPosted) { - std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p.get() != nullptr); - std::unique_ptr c1 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c1.get() != nullptr); - const uint32_t client_state_mask1 = c1->client_state_mask(); - - EXPECT_EQ(0, p->GainAsync()); - DvrNativeBufferMetadata meta; - EXPECT_EQ(0, p->PostAsync(&meta, LocalHandle())); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c1))); - - // c2 is created when the buffer is in posted state. buffer state for c1 is - // posted. Thus, c2 should be automatically set to posted and able to acquire. - std::unique_ptr c2 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c2.get() != nullptr); - const uint32_t client_state_mask2 = c2->client_state_mask(); - EXPECT_NE(client_state_mask1, client_state_mask2); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c2))); - LocalHandle invalid_fence; - EXPECT_EQ(0, c2->AcquireAsync(&meta, &invalid_fence)); - - EXPECT_EQ(0, c1->AcquireAsync(&meta, &invalid_fence)); - - // c3 is created when the buffer is in acquired state. buffer state for c1 and - // c2 are acquired. Thus, c3 should be automatically set to posted and able to - // acquire. - std::unique_ptr c3 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c3.get() != nullptr); - const uint32_t client_state_mask3 = c3->client_state_mask(); - EXPECT_NE(client_state_mask1, client_state_mask3); - EXPECT_NE(client_state_mask2, client_state_mask3); - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(c3))); - EXPECT_EQ(0, c3->AcquireAsync(&meta, &invalid_fence)); - - // Releasing c2 and c3 in normal ways. - EXPECT_EQ(0, c2->Release(LocalHandle())); - EXPECT_EQ(0, c3->ReleaseAsync(&meta, LocalHandle())); - - // Destroy the c1 who has not released the buffer. - c1 = nullptr; - - // The buffer is now available for the producer to gain. - EXPECT_LT(0, RETRY_EINTR(PollBufferEvent(p))); - - // C4 is created in released state. Thus, it cannot gain the just posted - // buffer. - std::unique_ptr c4 = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(c4.get() != nullptr); - const uint32_t client_state_mask4 = c4->client_state_mask(); - EXPECT_NE(client_state_mask3, client_state_mask4); - EXPECT_GE(0, RETRY_EINTR(PollBufferEvent(c3))); - EXPECT_EQ(-EBUSY, c3->AcquireAsync(&meta, &invalid_fence)); - - // Producer should be able to gain. - EXPECT_EQ(0, p->GainAsync(&meta, &invalid_fence)); -} - -TEST_F(LibBufferHubTest, TestDetachBufferFromProducer) { - // TODO(b/112338294) rewrite test after migration - return; - - /* std::unique_ptr p = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - std::unique_ptr c = - ConsumerBuffer::Import(p->CreateConsumer()); - ASSERT_TRUE(p.get() != nullptr); - ASSERT_TRUE(c.get() != nullptr); - - DvrNativeBufferMetadata metadata; - LocalHandle invalid_fence; - int p_id = p->id(); - - // Detach in posted state should fail. - EXPECT_EQ(0, p->GainAsync()); - EXPECT_EQ(0, p->PostAsync(&metadata, invalid_fence)); - EXPECT_GT(RETRY_EINTR(PollBufferEvent(c)), 0); - auto s1 = p->Detach(); - EXPECT_FALSE(s1); - - // Detach in acquired state should fail. - EXPECT_EQ(0, c->AcquireAsync(&metadata, &invalid_fence)); - s1 = p->Detach(); - EXPECT_FALSE(s1); - - // Detach in released state should fail. - EXPECT_EQ(0, c->ReleaseAsync(&metadata, invalid_fence)); - EXPECT_GT(RETRY_EINTR(PollBufferEvent(p)), 0); - s1 = p->Detach(); - EXPECT_FALSE(s1); - - // Detach in gained state should succeed. - EXPECT_EQ(0, p->GainAsync(&metadata, &invalid_fence)); - s1 = p->Detach(); - EXPECT_TRUE(s1); - - LocalChannelHandle handle = s1.take(); - EXPECT_TRUE(handle.valid()); - - // Both producer and consumer should have hangup. - EXPECT_GT(RETRY_EINTR(PollBufferEvent(p)), 0); - auto s2 = p->GetEventMask(POLLHUP); - EXPECT_TRUE(s2); - EXPECT_EQ(s2.get(), POLLHUP); - - EXPECT_GT(RETRY_EINTR(PollBufferEvent(c)), 0); - s2 = p->GetEventMask(POLLHUP); - EXPECT_TRUE(s2); - EXPECT_EQ(s2.get(), POLLHUP); - - auto s3 = p->CreateConsumer(); - EXPECT_FALSE(s3); - // Note that here the expected error code is EOPNOTSUPP as the socket towards - // ProducerChannel has been teared down. - EXPECT_EQ(s3.error(), EOPNOTSUPP); - - s3 = c->CreateConsumer(); - EXPECT_FALSE(s3); - // Note that here the expected error code is EPIPE returned from - // ConsumerChannel::HandleMessage as the socket is still open but the producer - // is gone. - EXPECT_EQ(s3.error(), EPIPE); - - // Detached buffer handle can be use to construct a new BufferHubBuffer - // object. - auto d = BufferHubBuffer::Import(std::move(handle)); - EXPECT_FALSE(handle.valid()); - EXPECT_TRUE(d->IsConnected()); - EXPECT_TRUE(d->IsValid()); - - EXPECT_EQ(d->id(), p_id); */ -} - -TEST_F(LibBufferHubTest, TestDetach) { - // TODO(b/112338294) rewrite test after migration - return; - - /* std::unique_ptr p1 = ProducerBuffer::Create( - kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t)); - ASSERT_TRUE(p1.get() != nullptr); - int p1_id = p1->id(); - - // Detached the producer from gained state. - EXPECT_EQ(0, p1->GainAsync()); - auto status_or_handle = p1->Detach(); - EXPECT_TRUE(status_or_handle.ok()); - LocalChannelHandle h1 = status_or_handle.take(); - EXPECT_TRUE(h1.valid()); - - // Detached buffer handle can be use to construct a new BufferHubBuffer - // object. - auto b1 = BufferHubBuffer::Import(std::move(h1)); - EXPECT_FALSE(h1.valid()); - EXPECT_TRUE(b1->IsValid()); - int b1_id = b1->id(); - EXPECT_EQ(b1_id, p1_id); */ -} diff --git a/libs/vr/libbufferhub/buffer_hub_base.cpp b/libs/vr/libbufferhub/buffer_hub_base.cpp deleted file mode 100644 index 17930b4405..0000000000 --- a/libs/vr/libbufferhub/buffer_hub_base.cpp +++ /dev/null @@ -1,216 +0,0 @@ -#include -#include - -#include -#include -#include - -using android::pdx::LocalChannelHandle; -using android::pdx::LocalHandle; -using android::pdx::Status; -using android::pdx::default_transport::ClientChannel; -using android::pdx::default_transport::ClientChannelFactory; - -namespace android { -namespace dvr { - -BufferHubBase::BufferHubBase(LocalChannelHandle channel_handle) - : Client{pdx::default_transport::ClientChannel::Create( - std::move(channel_handle))}, - id_(-1), - cid_(-1) {} -BufferHubBase::BufferHubBase(const std::string& endpoint_path) - : Client{pdx::default_transport::ClientChannelFactory::Create( - endpoint_path)}, - id_(-1), - cid_(-1) {} - -BufferHubBase::~BufferHubBase() { - // buffer_state and fence_state are not reset here. They will be used to - // clean up epoll fd if necessary in ProducerChannel::RemoveConsumer method. - if (metadata_header_ != nullptr) { - metadata_buffer_.Unlock(); - } -} - -Status BufferHubBase::CreateConsumer() { - Status status = - InvokeRemoteMethod(); - ALOGE_IF(!status, - "BufferHub::CreateConsumer: Failed to create consumer channel: %s", - status.GetErrorMessage().c_str()); - return status; -} - -int BufferHubBase::ImportBuffer() { - ATRACE_NAME("BufferHubBase::ImportBuffer"); - - Status> status = - InvokeRemoteMethod(); - if (!status) { - ALOGE("BufferHubBase::ImportBuffer: Failed to get buffer: %s", - status.GetErrorMessage().c_str()); - return -status.error(); - } else if (status.get().id() < 0) { - ALOGE("BufferHubBase::ImportBuffer: Received an invalid id!"); - return -EIO; - } - - auto buffer_desc = status.take(); - - // Stash the buffer id to replace the value in id_. - const int new_id = buffer_desc.id(); - - // Import the buffer. - IonBuffer ion_buffer; - ALOGD_IF(TRACE, "BufferHubBase::ImportBuffer: id=%d.", buffer_desc.id()); - - if (const int ret = buffer_desc.ImportBuffer(&ion_buffer)) - return ret; - - // Import the metadata. - IonBuffer metadata_buffer; - if (const int ret = buffer_desc.ImportMetadata(&metadata_buffer)) { - ALOGE("Failed to import metadata buffer, error=%d", ret); - return ret; - } - size_t metadata_buf_size = metadata_buffer.width(); - if (metadata_buf_size < BufferHubDefs::kMetadataHeaderSize) { - ALOGE("BufferHubBase::ImportBuffer: metadata buffer too small: %zu", - metadata_buf_size); - return -ENOMEM; - } - - // If all imports succee, replace the previous buffer and id. - buffer_ = std::move(ion_buffer); - metadata_buffer_ = std::move(metadata_buffer); - metadata_buf_size_ = metadata_buf_size; - user_metadata_size_ = metadata_buf_size_ - BufferHubDefs::kMetadataHeaderSize; - - void* metadata_ptr = nullptr; - if (const int ret = - metadata_buffer_.Lock(BufferHubDefs::kMetadataUsage, /*x=*/0, - /*y=*/0, metadata_buf_size_, - /*height=*/1, &metadata_ptr)) { - ALOGE("BufferHubBase::ImportBuffer: Failed to lock metadata."); - return ret; - } - - // Set up shared fences. - shared_acquire_fence_ = buffer_desc.take_acquire_fence(); - shared_release_fence_ = buffer_desc.take_release_fence(); - if (!shared_acquire_fence_ || !shared_release_fence_) { - ALOGE("BufferHubBase::ImportBuffer: Failed to import shared fences."); - return -EIO; - } - - metadata_header_ = - reinterpret_cast(metadata_ptr); - if (user_metadata_size_) { - user_metadata_ptr_ = - reinterpret_cast(reinterpret_cast(metadata_ptr) + - BufferHubDefs::kMetadataHeaderSize); - } else { - user_metadata_ptr_ = nullptr; - } - - id_ = new_id; - cid_ = buffer_desc.buffer_cid(); - client_state_mask_ = buffer_desc.client_state_mask(); - - // Note that here the buffer_state, fence_state and active_clients_bit_mask - // are mapped from shared memory as an atomic object. The std::atomic's - // constructor will not be called so that the original value stored in the - // memory region will be preserved. - buffer_state_ = &metadata_header_->bufferState; - ALOGD_IF(TRACE, - "BufferHubBase::ImportBuffer: id=%d, buffer_state=%" PRIx32 ".", - id(), buffer_state_->load(std::memory_order_acquire)); - fence_state_ = &metadata_header_->fenceState; - ALOGD_IF(TRACE, - "BufferHubBase::ImportBuffer: id=%d, fence_state=%" PRIx32 ".", id(), - fence_state_->load(std::memory_order_acquire)); - active_clients_bit_mask_ = &metadata_header_->activeClientsBitMask; - ALOGD_IF( - TRACE, - "BufferHubBase::ImportBuffer: id=%d, active_clients_bit_mask=%" PRIx32 - ".", - id(), active_clients_bit_mask_->load(std::memory_order_acquire)); - - return 0; -} - -int BufferHubBase::CheckMetadata(size_t user_metadata_size) const { - if (user_metadata_size && !user_metadata_ptr_) { - ALOGE("BufferHubBase::CheckMetadata: doesn't support custom metadata."); - return -EINVAL; - } - if (user_metadata_size > user_metadata_size_) { - ALOGE("BufferHubBase::CheckMetadata: too big: %zu, maximum: %zu.", - user_metadata_size, user_metadata_size_); - return -E2BIG; - } - return 0; -} - -int BufferHubBase::UpdateSharedFence(const LocalHandle& new_fence, - const LocalHandle& shared_fence) { - if (pending_fence_fd_.Get() != new_fence.Get()) { - // First, replace the old fd if there was already one. Skipping if the new - // one is the same as the old. - if (pending_fence_fd_.IsValid()) { - const int ret = epoll_ctl(shared_fence.Get(), EPOLL_CTL_DEL, - pending_fence_fd_.Get(), nullptr); - ALOGW_IF(ret, - "BufferHubBase::UpdateSharedFence: failed to remove old fence " - "fd from epoll set, error: %s.", - strerror(errno)); - } - - if (new_fence.IsValid()) { - // If ready fence is valid, we put that into the epoll set. - epoll_event event; - event.events = EPOLLIN; - event.data.u32 = client_state_mask(); - pending_fence_fd_ = new_fence.Duplicate(); - if (epoll_ctl(shared_fence.Get(), EPOLL_CTL_ADD, pending_fence_fd_.Get(), - &event) < 0) { - const int error = errno; - ALOGE( - "BufferHubBase::UpdateSharedFence: failed to add new fence fd " - "into epoll set, error: %s.", - strerror(error)); - return -error; - } - // Set bit in fence state to indicate that there is a fence from this - // producer or consumer. - fence_state_->fetch_or(client_state_mask()); - } else { - // Unset bit in fence state to indicate that there is no fence, so that - // when consumer to acquire or producer to acquire, it knows no need to - // check fence for this buffer. - fence_state_->fetch_and(~client_state_mask()); - } - } - - return 0; -} - -int BufferHubBase::Lock(int usage, int x, int y, int width, int height, - void** address) { - return buffer_.Lock(usage, x, y, width, height, address); -} - -int BufferHubBase::Unlock() { return buffer_.Unlock(); } - -int BufferHubBase::GetBlobReadWritePointer(size_t size, void** addr) { - int width = static_cast(size); - int height = 1; - int ret = Lock(usage(), 0, 0, width, height, addr); - if (ret == 0) - Unlock(); - return ret; -} - -} // namespace dvr -} // namespace android diff --git a/libs/vr/libbufferhub/buffer_hub_rpc.cpp b/libs/vr/libbufferhub/buffer_hub_rpc.cpp deleted file mode 100644 index 9a67faa8aa..0000000000 --- a/libs/vr/libbufferhub/buffer_hub_rpc.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "include/private/dvr/bufferhub_rpc.h" - -namespace android { -namespace dvr { - -constexpr char BufferHubRPC::kClientPath[]; - -} // namespace dvr -} // namespace android diff --git a/libs/vr/libbufferhub/consumer_buffer.cpp b/libs/vr/libbufferhub/consumer_buffer.cpp deleted file mode 100644 index 7823e36d3d..0000000000 --- a/libs/vr/libbufferhub/consumer_buffer.cpp +++ /dev/null @@ -1,201 +0,0 @@ -#include - -using android::pdx::LocalChannelHandle; -using android::pdx::LocalHandle; -using android::pdx::Status; - -namespace android { -namespace dvr { - -ConsumerBuffer::ConsumerBuffer(LocalChannelHandle channel) - : BASE(std::move(channel)) { - const int ret = ImportBuffer(); - if (ret < 0) { - ALOGE("ConsumerBuffer::ConsumerBuffer: Failed to import buffer: %s", - strerror(-ret)); - Close(ret); - } -} - -std::unique_ptr ConsumerBuffer::Import( - LocalChannelHandle channel) { - ATRACE_NAME("ConsumerBuffer::Import"); - ALOGD_IF(TRACE, "ConsumerBuffer::Import: channel=%d", channel.value()); - return ConsumerBuffer::Create(std::move(channel)); -} - -std::unique_ptr ConsumerBuffer::Import( - Status status) { - return Import(status ? status.take() - : LocalChannelHandle{nullptr, -status.error()}); -} - -int ConsumerBuffer::LocalAcquire(DvrNativeBufferMetadata* out_meta, - LocalHandle* out_fence) { - if (!out_meta) - return -EINVAL; - - // The buffer can be acquired iff the buffer state for this client is posted. - uint32_t current_buffer_state = - buffer_state_->load(std::memory_order_acquire); - if (!BufferHubDefs::isClientPosted(current_buffer_state, - client_state_mask())) { - ALOGE( - "%s: Failed to acquire the buffer. The buffer is not posted, id=%d " - "state=%" PRIx32 " client_state_mask=%" PRIx32 ".", - __FUNCTION__, id(), current_buffer_state, client_state_mask()); - return -EBUSY; - } - - // Change the buffer state for this consumer from posted to acquired. - uint32_t updated_buffer_state = current_buffer_state ^ client_state_mask(); - while (!buffer_state_->compare_exchange_weak( - current_buffer_state, updated_buffer_state, std::memory_order_acq_rel, - std::memory_order_acquire)) { - if (!BufferHubDefs::isClientPosted(current_buffer_state, - client_state_mask())) { - ALOGE( - "%s: Failed to acquire the buffer. The buffer is no longer posted, " - "id=%d state=%" PRIx32 " client_state_mask=%" PRIx32 ".", - __FUNCTION__, id(), current_buffer_state, client_state_mask()); - return -EBUSY; - } - // The failure of compare_exchange_weak updates current_buffer_state. - updated_buffer_state = current_buffer_state ^ client_state_mask(); - } - - // Copy the canonical metadata. - void* metadata_ptr = reinterpret_cast(&metadata_header_->metadata); - memcpy(out_meta, metadata_ptr, sizeof(DvrNativeBufferMetadata)); - // Fill in the user_metadata_ptr in address space of the local process. - if (out_meta->user_metadata_size) { - out_meta->user_metadata_ptr = - reinterpret_cast(user_metadata_ptr_); - } else { - out_meta->user_metadata_ptr = 0; - } - - uint32_t fence_state = fence_state_->load(std::memory_order_acquire); - // If there is an acquire fence from producer, we need to return it. - // The producer state bit mask is kFirstClientBitMask for now. - if (fence_state & BufferHubDefs::kFirstClientBitMask) { - *out_fence = shared_acquire_fence_.Duplicate(); - } - - return 0; -} - -int ConsumerBuffer::Acquire(LocalHandle* ready_fence) { - return Acquire(ready_fence, nullptr, 0); -} - -int ConsumerBuffer::Acquire(LocalHandle* ready_fence, void* meta, - size_t user_metadata_size) { - ATRACE_NAME("ConsumerBuffer::Acquire"); - - if (const int error = CheckMetadata(user_metadata_size)) - return error; - - DvrNativeBufferMetadata canonical_meta; - if (const int error = LocalAcquire(&canonical_meta, ready_fence)) - return error; - - if (meta && user_metadata_size) { - void* metadata_src = - reinterpret_cast(canonical_meta.user_metadata_ptr); - if (metadata_src) { - memcpy(meta, metadata_src, user_metadata_size); - } else { - ALOGW("ConsumerBuffer::Acquire: no user-defined metadata."); - } - } - - auto status = InvokeRemoteMethod(); - if (!status) - return -status.error(); - return 0; -} - -int ConsumerBuffer::AcquireAsync(DvrNativeBufferMetadata* out_meta, - LocalHandle* out_fence) { - ATRACE_NAME("ConsumerBuffer::AcquireAsync"); - - if (const int error = LocalAcquire(out_meta, out_fence)) - return error; - - auto status = SendImpulse(BufferHubRPC::ConsumerAcquire::Opcode); - if (!status) - return -status.error(); - return 0; -} - -int ConsumerBuffer::LocalRelease(const DvrNativeBufferMetadata* meta, - const LocalHandle& release_fence) { - if (const int error = CheckMetadata(meta->user_metadata_size)) - return error; - - // Set the buffer state of this client to released if it is not already in - // released state. - uint32_t current_buffer_state = - buffer_state_->load(std::memory_order_acquire); - if (BufferHubDefs::isClientReleased(current_buffer_state, - client_state_mask())) { - return 0; - } - uint32_t updated_buffer_state = current_buffer_state & (~client_state_mask()); - while (!buffer_state_->compare_exchange_weak( - current_buffer_state, updated_buffer_state, std::memory_order_acq_rel, - std::memory_order_acquire)) { - // The failure of compare_exchange_weak updates current_buffer_state. - updated_buffer_state = current_buffer_state & (~client_state_mask()); - } - - // On release, only the user requested metadata is copied back into the shared - // memory for metadata. Since there are multiple consumers, it doesn't make - // sense to send the canonical metadata back to the producer. However, one of - // the consumer can still choose to write up to user_metadata_size bytes of - // data into user_metadata_ptr. - if (meta->user_metadata_ptr && meta->user_metadata_size) { - void* metadata_src = reinterpret_cast(meta->user_metadata_ptr); - memcpy(user_metadata_ptr_, metadata_src, meta->user_metadata_size); - } - - // Send out the release fence through the shared epoll fd. Note that during - // releasing the producer is not expected to be polling on the fence. - if (const int error = UpdateSharedFence(release_fence, shared_release_fence_)) - return error; - - return 0; -} - -int ConsumerBuffer::Release(const LocalHandle& release_fence) { - ATRACE_NAME("ConsumerBuffer::Release"); - - DvrNativeBufferMetadata meta; - if (const int error = LocalRelease(&meta, release_fence)) - return error; - - return ReturnStatusOrError(InvokeRemoteMethod( - BorrowedFence(release_fence.Borrow()))); -} - -int ConsumerBuffer::ReleaseAsync() { - DvrNativeBufferMetadata meta; - return ReleaseAsync(&meta, LocalHandle()); -} - -int ConsumerBuffer::ReleaseAsync(const DvrNativeBufferMetadata* meta, - const LocalHandle& release_fence) { - ATRACE_NAME("ConsumerBuffer::ReleaseAsync"); - - if (const int error = LocalRelease(meta, release_fence)) - return error; - - return ReturnStatusOrError( - SendImpulse(BufferHubRPC::ConsumerRelease::Opcode)); -} - -int ConsumerBuffer::Discard() { return Release(LocalHandle()); } - -} // namespace dvr -} // namespace android diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h deleted file mode 100644 index 8a490d9983..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef ANDROID_DVR_BUFFER_HUB_BASE_H_ -#define ANDROID_DVR_BUFFER_HUB_BASE_H_ - -#include - -#include - -namespace android { -namespace dvr { - -// Base class of two types of BufferHub clients: dvr::ProducerBuffer and -// dvr::ConsumerBuffer. -class BufferHubBase : public pdx::Client { - public: - using LocalHandle = pdx::LocalHandle; - using LocalChannelHandle = pdx::LocalChannelHandle; - template - using Status = pdx::Status; - - // Create a new consumer channel that is attached to the producer. Returns - // a file descriptor for the new channel or a negative error code. - Status CreateConsumer(); - - // Gets a blob buffer that was created with ProducerBuffer::CreateBlob. - // Locking and Unlocking is handled internally. There's no need to Unlock - // after calling this method. - int GetBlobReadWritePointer(size_t size, void** addr); - - // Returns a dup'd file descriptor for accessing the blob shared memory. The - // caller takes ownership of the file descriptor and must close it or pass on - // ownership. Some GPU API extensions can take file descriptors to bind shared - // memory gralloc buffers to GPU buffer objects. - LocalHandle GetBlobFd() const { - // Current GPU vendor puts the buffer allocation in one FD. If we change GPU - // vendors and this is the wrong fd, late-latching and EDS will very clearly - // stop working and we will need to correct this. The alternative is to use - // a GL context in the pose service to allocate this buffer or to use the - // ION API directly instead of gralloc. - return LocalHandle(dup(native_handle()->data[0])); - } - - using Client::event_fd; - - Status GetEventMask(int events) { - if (auto* client_channel = GetChannel()) { - return client_channel->GetEventMask(events); - } else { - return pdx::ErrorStatus(EINVAL); - } - } - - std::vector GetEventSources() const { - if (auto* client_channel = GetChannel()) { - return client_channel->GetEventSources(); - } else { - return {}; - } - } - - native_handle_t* native_handle() const { - return const_cast(buffer_.handle()); - } - - IonBuffer* buffer() { return &buffer_; } - const IonBuffer* buffer() const { return &buffer_; } - - // Gets ID of the buffer client. All BufferHub clients derived from the same - // buffer in bufferhubd share the same buffer id. - int id() const { return id_; } - - // Gets the channel id of the buffer client. Each BufferHub client has its - // system unique channel id. - int cid() const { return cid_; } - - // Returns the buffer buffer state. - uint32_t buffer_state() { - return buffer_state_->load(std::memory_order_acquire); - }; - - // Returns whether the buffer is already released by all current clients. - bool is_released() { - return (buffer_state() & - active_clients_bit_mask_->load(std::memory_order_acquire)) == 0; - } - - // A state mask which is unique to a buffer hub client among all its siblings - // sharing the same concrete graphic buffer. - uint32_t client_state_mask() const { return client_state_mask_; } - - // The following methods return settings of the first buffer. Currently, - // it is only possible to create multi-buffer BufferHubBases with the same - // settings. - uint32_t width() const { return buffer_.width(); } - uint32_t height() const { return buffer_.height(); } - uint32_t stride() const { return buffer_.stride(); } - uint32_t format() const { return buffer_.format(); } - uint32_t usage() const { return buffer_.usage(); } - uint32_t layer_count() const { return buffer_.layer_count(); } - - uint64_t GetQueueIndex() const { return metadata_header_->queueIndex; } - void SetQueueIndex(uint64_t index) { metadata_header_->queueIndex = index; } - - protected: - explicit BufferHubBase(LocalChannelHandle channel); - explicit BufferHubBase(const std::string& endpoint_path); - virtual ~BufferHubBase(); - - // Initialization helper. - int ImportBuffer(); - - // Check invalid metadata operation. Returns 0 if requested metadata is valid. - int CheckMetadata(size_t user_metadata_size) const; - - // Send out the new fence by updating the shared fence (shared_release_fence - // for producer and shared_acquire_fence for consumer). Note that during this - // should only be used in LocalPost() or LocalRelease, and the shared fence - // shouldn't be poll'ed by the other end. - int UpdateSharedFence(const LocalHandle& new_fence, - const LocalHandle& shared_fence); - - // Locks the area specified by (x, y, width, height) for a specific usage. If - // the usage is software then |addr| will be updated to point to the address - // of the buffer in virtual memory. The caller should only access/modify the - // pixels in the specified area. anything else is undefined behavior. - int Lock(int usage, int x, int y, int width, int height, void** addr); - - // Must be called after Lock() when the caller has finished changing the - // buffer. - int Unlock(); - - // IonBuffer that is shared between bufferhubd, producer, and consumers. - size_t metadata_buf_size_{0}; - size_t user_metadata_size_{0}; - BufferHubDefs::MetadataHeader* metadata_header_ = nullptr; - void* user_metadata_ptr_ = nullptr; - std::atomic* buffer_state_ = nullptr; - std::atomic* fence_state_ = nullptr; - std::atomic* active_clients_bit_mask_ = nullptr; - - LocalHandle shared_acquire_fence_; - LocalHandle shared_release_fence_; - - // A local fence fd that holds the ownership of the fence fd on Post (for - // producer) and Release (for consumer). - LocalHandle pending_fence_fd_; - - private: - BufferHubBase(const BufferHubBase&) = delete; - void operator=(const BufferHubBase&) = delete; - - // Global id for the buffer that is consistent across processes. It is meant - // for logging and debugging purposes only and should not be used for lookup - // or any other functional purpose as a security precaution. - int id_; - - // Channel id. - int cid_; - - // Client bit mask which indicates the locations of this client object in the - // buffer_state_. - uint32_t client_state_mask_{0U}; - IonBuffer buffer_; - IonBuffer metadata_buffer_; -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_BUFFER_HUB_BASE_H_ diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h deleted file mode 100644 index e610e18849..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h +++ /dev/null @@ -1,164 +0,0 @@ -#ifndef ANDROID_DVR_BUFFER_HUB_DEFS_H_ -#define ANDROID_DVR_BUFFER_HUB_DEFS_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace android { -namespace dvr { - -namespace BufferHubDefs { - -static constexpr uint32_t kMetadataFormat = HAL_PIXEL_FORMAT_BLOB; -static constexpr uint32_t kMetadataUsage = - GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN; - -// See more details in libs/ui/include/ui/BufferHubDefs.h -static constexpr int kMaxNumberOfClients = - android::BufferHubDefs::kMaxNumberOfClients; -static constexpr uint32_t kLowbitsMask = android::BufferHubDefs::kLowbitsMask; -static constexpr uint32_t kHighBitsMask = android::BufferHubDefs::kHighBitsMask; -static constexpr uint32_t kFirstClientBitMask = - android::BufferHubDefs::kFirstClientBitMask; - -static inline bool isAnyClientGained(uint32_t state) { - return android::BufferHubDefs::isAnyClientGained(state); -} - -static inline bool isClientGained(uint32_t state, uint32_t client_bit_mask) { - return android::BufferHubDefs::isClientGained(state, client_bit_mask); -} - -static inline bool isAnyClientPosted(uint32_t state) { - return android::BufferHubDefs::isAnyClientPosted(state); -} - -static inline bool isClientPosted(uint32_t state, uint32_t client_bit_mask) { - return android::BufferHubDefs::isClientPosted(state, client_bit_mask); -} - -static inline bool isAnyClientAcquired(uint32_t state) { - return android::BufferHubDefs::isAnyClientAcquired(state); -} - -static inline bool isClientAcquired(uint32_t state, uint32_t client_bit_mask) { - return android::BufferHubDefs::isClientAcquired(state, client_bit_mask); -} - -static inline bool isClientReleased(uint32_t state, uint32_t client_bit_mask) { - return android::BufferHubDefs::isClientReleased(state, client_bit_mask); -} - -// Returns the next available buffer client's client_state_masks. -// @params union_bits. Union of all existing clients' client_state_masks. -static inline uint32_t findNextAvailableClientStateMask(uint32_t union_bits) { - return android::BufferHubDefs::findNextAvailableClientStateMask(union_bits); -} - -using MetadataHeader = android::BufferHubDefs::MetadataHeader; -static constexpr size_t kMetadataHeaderSize = - android::BufferHubDefs::kMetadataHeaderSize; - -} // namespace BufferHubDefs - -template -class BufferTraits { - public: - BufferTraits() = default; - BufferTraits(const native_handle_t* buffer_handle, - const FileHandleType& metadata_handle, int id, - uint32_t client_state_mask, uint64_t metadata_size, - uint32_t width, uint32_t height, uint32_t layer_count, - uint32_t format, uint64_t usage, uint32_t stride, - const FileHandleType& acquire_fence_fd, - const FileHandleType& release_fence_fd) - : id_(id), - client_state_mask_(client_state_mask), - metadata_size_(metadata_size), - width_(width), - height_(height), - layer_count_(layer_count), - format_(format), - usage_(usage), - stride_(stride), - buffer_handle_(buffer_handle), - metadata_handle_(metadata_handle.Borrow()), - acquire_fence_fd_(acquire_fence_fd.Borrow()), - release_fence_fd_(release_fence_fd.Borrow()) {} - - BufferTraits(BufferTraits&& other) = default; - BufferTraits& operator=(BufferTraits&& other) = default; - - // ID of the buffer client. All BufferHubBuffer clients derived from the same - // buffer in bufferhubd share the same buffer id. - int id() const { return id_; } - - // State mask of the buffer client. Each BufferHubBuffer client backed by the - // same buffer channel has uniqued state bit among its siblings. For a - // producer buffer the bit must be kFirstClientBitMask; for a consumer the bit - // must be one of the kConsumerStateMask. - uint32_t client_state_mask() const { return client_state_mask_; } - uint64_t metadata_size() const { return metadata_size_; } - - uint32_t width() { return width_; } - uint32_t height() { return height_; } - uint32_t layer_count() { return layer_count_; } - uint32_t format() { return format_; } - uint64_t usage() { return usage_; } - uint32_t stride() { return stride_; } - - const NativeHandleWrapper& buffer_handle() const { - return buffer_handle_; - } - - NativeHandleWrapper take_buffer_handle() { - return std::move(buffer_handle_); - } - FileHandleType take_metadata_handle() { return std::move(metadata_handle_); } - FileHandleType take_acquire_fence() { return std::move(acquire_fence_fd_); } - FileHandleType take_release_fence() { return std::move(release_fence_fd_); } - - private: - // BufferHub specific traits. - int id_ = -1; - uint32_t client_state_mask_; - uint64_t metadata_size_; - - // Traits for a GraphicBuffer. - uint32_t width_; - uint32_t height_; - uint32_t layer_count_; - uint32_t format_; - uint64_t usage_; - uint32_t stride_; - - // Native handle for the graphic buffer. - NativeHandleWrapper buffer_handle_; - - // File handle of an ashmem that holds buffer metadata. - FileHandleType metadata_handle_; - - // Pamameters for shared fences. - FileHandleType acquire_fence_fd_; - FileHandleType release_fence_fd_; - - PDX_SERIALIZABLE_MEMBERS(BufferTraits, id_, - client_state_mask_, metadata_size_, stride_, width_, - height_, layer_count_, format_, usage_, - buffer_handle_, metadata_handle_, acquire_fence_fd_, - release_fence_fd_); - - BufferTraits(const BufferTraits&) = delete; - void operator=(const BufferTraits&) = delete; -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_BUFFER_HUB_DEFS_H_ diff --git a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h deleted file mode 100644 index f1cd0b4adc..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h +++ /dev/null @@ -1,377 +0,0 @@ -#ifndef ANDROID_DVR_BUFFERHUB_RPC_H_ -#define ANDROID_DVR_BUFFERHUB_RPC_H_ - -#include "buffer_hub_defs.h" - -#include -#include - -#include -#include -#include -#include -#include - -namespace android { -namespace dvr { - -template -class NativeBufferHandle { - public: - NativeBufferHandle() { Clear(); } - NativeBufferHandle(const IonBuffer& buffer, int id) - : id_(id), - stride_(buffer.stride()), - width_(buffer.width()), - height_(buffer.height()), - layer_count_(buffer.layer_count()), - format_(buffer.format()), - usage_(buffer.usage()) { - // Populate the fd and int vectors: native_handle->data[] is an array of fds - // followed by an array of opaque ints. - const int fd_count = buffer.handle()->numFds; - const int int_count = buffer.handle()->numInts; - for (int i = 0; i < fd_count; i++) { - fds_.emplace_back(FileHandleType::AsDuplicate(buffer.handle()->data[i])); - } - for (int i = 0; i < int_count; i++) { - opaque_ints_.push_back(buffer.handle()->data[fd_count + i]); - } - } - NativeBufferHandle(NativeBufferHandle&& other) noexcept = default; - NativeBufferHandle& operator=(NativeBufferHandle&& other) noexcept = default; - - // Imports the native handle into the given IonBuffer instance. - int Import(IonBuffer* buffer) { - // This is annoying, but we need to convert the vector of FileHandles into a - // vector of ints for the Import API. - std::vector fd_ints; - for (const auto& fd : fds_) - fd_ints.push_back(fd.Get()); - - const int ret = - buffer->Import(fd_ints.data(), fd_ints.size(), opaque_ints_.data(), - opaque_ints_.size(), width_, height_, layer_count_, - stride_, format_, usage_); - if (ret < 0) - return ret; - - // Import succeeded, release the file handles which are now owned by the - // IonBuffer and clear members. - for (auto& fd : fds_) - fd.Release(); - opaque_ints_.clear(); - Clear(); - - return 0; - } - - int id() const { return id_; } - size_t IntCount() const { return opaque_ints_.size(); } - size_t FdCount() const { return fds_.size(); } - - private: - int id_; - uint32_t stride_; - uint32_t width_; - uint32_t height_; - uint32_t layer_count_; - uint32_t format_; - uint64_t usage_; - std::vector opaque_ints_; - std::vector fds_; - - void Clear() { - id_ = -1; - stride_ = width_ = height_ = format_ = usage_ = 0; - } - - PDX_SERIALIZABLE_MEMBERS(NativeBufferHandle, id_, stride_, - width_, height_, layer_count_, format_, usage_, - opaque_ints_, fds_); - - NativeBufferHandle(const NativeBufferHandle&) = delete; - void operator=(const NativeBufferHandle&) = delete; -}; - -template -class BufferDescription { - public: - BufferDescription() = default; - BufferDescription(const IonBuffer& buffer, const IonBuffer& metadata, int id, - int buffer_cid, uint32_t client_state_mask, - const FileHandleType& acquire_fence_fd, - const FileHandleType& release_fence_fd) - : id_(id), - buffer_cid_(buffer_cid), - client_state_mask_(client_state_mask), - buffer_(buffer, id), - metadata_(metadata, id), - acquire_fence_fd_(acquire_fence_fd.Borrow()), - release_fence_fd_(release_fence_fd.Borrow()) {} - - BufferDescription(BufferDescription&& other) noexcept = default; - BufferDescription& operator=(BufferDescription&& other) noexcept = default; - - // ID of the buffer client. All BufferHub clients derived from the same buffer - // in bufferhubd share the same buffer id. - int id() const { return id_; } - - // Channel ID of the buffer client. Each BufferHub client has its system - // unique channel id. - int buffer_cid() const { return buffer_cid_; } - - // State mask of the buffer client. Each BufferHub client backed by the - // same buffer channel has uniqued state bit among its siblings. - uint32_t client_state_mask() const { return client_state_mask_; } - FileHandleType take_acquire_fence() { return std::move(acquire_fence_fd_); } - FileHandleType take_release_fence() { return std::move(release_fence_fd_); } - - int ImportBuffer(IonBuffer* buffer) { return buffer_.Import(buffer); } - int ImportMetadata(IonBuffer* metadata) { return metadata_.Import(metadata); } - - private: - int id_{-1}; - int buffer_cid_{-1}; - uint32_t client_state_mask_{0U}; - // Two IonBuffers: one for the graphic buffer and one for metadata. - NativeBufferHandle buffer_; - NativeBufferHandle metadata_; - - // Pamameters for shared fences. - FileHandleType acquire_fence_fd_; - FileHandleType release_fence_fd_; - - PDX_SERIALIZABLE_MEMBERS(BufferDescription, id_, buffer_cid_, - client_state_mask_, buffer_, metadata_, - acquire_fence_fd_, release_fence_fd_); - - BufferDescription(const BufferDescription&) = delete; - void operator=(const BufferDescription&) = delete; -}; - -using BorrowedNativeBufferHandle = NativeBufferHandle; -using LocalNativeBufferHandle = NativeBufferHandle; - -template -class FenceHandle { - public: - FenceHandle() = default; - explicit FenceHandle(int fence) : fence_{fence} {} - explicit FenceHandle(FileHandleType&& fence) : fence_{std::move(fence)} {} - FenceHandle(FenceHandle&&) noexcept = default; - FenceHandle& operator=(FenceHandle&&) noexcept = default; - - explicit operator bool() const { return fence_.IsValid(); } - - const FileHandleType& get() const { fence_; } - FileHandleType&& take() { return std::move(fence_); } - - int get_fd() const { return fence_.Get(); } - void close() { fence_.Close(); } - - FenceHandle borrow() const { - return FenceHandle(fence_.Borrow()); - } - - private: - FileHandleType fence_; - - PDX_SERIALIZABLE_MEMBERS(FenceHandle, fence_); - - FenceHandle(const FenceHandle&) = delete; - void operator=(const FenceHandle&) = delete; -}; - -using LocalFence = FenceHandle; -using BorrowedFence = FenceHandle; - -struct ProducerQueueConfig { - // Whether the buffer queue is operating in Async mode. - // From GVR's perspective of view, this means a buffer can be acquired - // asynchronously by the compositor. - // From Android Surface's perspective of view, this is equivalent to - // IGraphicBufferProducer's async mode. When in async mode, a producer - // will never block even if consumer is running slow. - bool is_async; - - // Default buffer width that is set during ProducerQueue's creation. - uint32_t default_width; - - // Default buffer height that is set during ProducerQueue's creation. - uint32_t default_height; - - // Default buffer format that is set during ProducerQueue's creation. - uint32_t default_format; - - // Size of the meta data associated with all the buffers allocated from the - // queue. - size_t user_metadata_size; - - private: - PDX_SERIALIZABLE_MEMBERS(ProducerQueueConfig, is_async, default_width, - default_height, default_format, user_metadata_size); -}; - -class ProducerQueueConfigBuilder { - public: - // Build a ProducerQueueConfig object. - ProducerQueueConfig Build() { - return {is_async_, default_width_, default_height_, default_format_, - user_metadata_size_}; - } - - ProducerQueueConfigBuilder& SetIsAsync(bool is_async) { - is_async_ = is_async; - return *this; - } - - ProducerQueueConfigBuilder& SetDefaultWidth(uint32_t width) { - default_width_ = width; - return *this; - } - - ProducerQueueConfigBuilder& SetDefaultHeight(uint32_t height) { - default_height_ = height; - return *this; - } - - ProducerQueueConfigBuilder& SetDefaultFormat(uint32_t format) { - default_format_ = format; - return *this; - } - - template - ProducerQueueConfigBuilder& SetMetadata() { - user_metadata_size_ = sizeof(Meta); - return *this; - } - - ProducerQueueConfigBuilder& SetMetadataSize(size_t user_metadata_size) { - user_metadata_size_ = user_metadata_size; - return *this; - } - - private: - bool is_async_{false}; - uint32_t default_width_{1}; - uint32_t default_height_{1}; - uint32_t default_format_{1}; // PIXEL_FORMAT_RGBA_8888 - size_t user_metadata_size_{0}; -}; - -// Explicit specializations of ProducerQueueConfigBuilder::Build for void -// metadata type. -template <> -inline ProducerQueueConfigBuilder& -ProducerQueueConfigBuilder::SetMetadata() { - user_metadata_size_ = 0; - return *this; -} - -struct QueueInfo { - ProducerQueueConfig producer_config; - int id; - - private: - PDX_SERIALIZABLE_MEMBERS(QueueInfo, producer_config, id); -}; - -struct UsagePolicy { - uint64_t usage_set_mask{0}; - uint64_t usage_clear_mask{0}; - uint64_t usage_deny_set_mask{0}; - uint64_t usage_deny_clear_mask{0}; - - private: - PDX_SERIALIZABLE_MEMBERS(UsagePolicy, usage_set_mask, usage_clear_mask, - usage_deny_set_mask, usage_deny_clear_mask); -}; - -// BufferHub Service RPC interface. Defines the endpoints, op codes, and method -// type signatures supported by bufferhubd. -struct BufferHubRPC { - // Service path. - static constexpr char kClientPath[] = "system/buffer_hub/client"; - - // |BufferHubQueue| will keep track of at most this value of buffers. - // Attempts at runtime to increase the number of buffers past this - // will fail. Note that the value is in sync with |android::BufferQueue|, so - // that slot id can be shared between |android::dvr::BufferHubQueueProducer| - // and |android::BufferQueueProducer| which both implements the same - // interface: |android::IGraphicBufferProducer|. - static constexpr size_t kMaxQueueCapacity = - android::BufferQueueDefs::NUM_BUFFER_SLOTS; - - // Op codes. - enum { - kOpCreateBuffer = 0, - kOpGetBuffer, - kOpNewConsumer, - kOpProducerPost, - kOpProducerGain, - kOpConsumerAcquire, - kOpConsumerRelease, - kOpConsumerBufferDetach, - kOpCreateProducerQueue, - kOpCreateConsumerQueue, - kOpGetQueueInfo, - kOpProducerQueueAllocateBuffers, - kOpProducerQueueInsertBuffer, - kOpProducerQueueRemoveBuffer, - kOpConsumerQueueImportBuffers, - // TODO(b/77153033): Separate all those RPC operations into subclasses. - }; - - // Aliases. - using LocalChannelHandle = pdx::LocalChannelHandle; - using LocalHandle = pdx::LocalHandle; - using Void = pdx::rpc::Void; - - // Methods. - PDX_REMOTE_METHOD(CreateBuffer, kOpCreateBuffer, - void(uint32_t width, uint32_t height, uint32_t format, - uint64_t usage, size_t user_metadata_size)); - PDX_REMOTE_METHOD(GetBuffer, kOpGetBuffer, - BufferDescription(Void)); - PDX_REMOTE_METHOD(NewConsumer, kOpNewConsumer, LocalChannelHandle(Void)); - PDX_REMOTE_METHOD(ProducerPost, kOpProducerPost, - void(LocalFence acquire_fence)); - PDX_REMOTE_METHOD(ProducerGain, kOpProducerGain, LocalFence(Void)); - PDX_REMOTE_METHOD(ConsumerAcquire, kOpConsumerAcquire, LocalFence(Void)); - PDX_REMOTE_METHOD(ConsumerRelease, kOpConsumerRelease, - void(LocalFence release_fence)); - - // Detaches a ConsumerBuffer from an existing producer/consumer set. Can only - // be called when the consumer is the only consumer and it has exclusive - // access to the buffer (i.e. in the acquired'ed state). On the successful - // return of the IPC call, a new DetachedBufferChannel handle will be returned - // and all existing producer and consumer channels will be closed. Further - // IPCs towards those channels will return error. - PDX_REMOTE_METHOD(ConsumerBufferDetach, kOpConsumerBufferDetach, - LocalChannelHandle(Void)); - - // Buffer Queue Methods. - PDX_REMOTE_METHOD(CreateProducerQueue, kOpCreateProducerQueue, - QueueInfo(const ProducerQueueConfig& producer_config, - const UsagePolicy& usage_policy)); - PDX_REMOTE_METHOD(CreateConsumerQueue, kOpCreateConsumerQueue, - LocalChannelHandle(bool silent_queue)); - PDX_REMOTE_METHOD(GetQueueInfo, kOpGetQueueInfo, QueueInfo(Void)); - PDX_REMOTE_METHOD(ProducerQueueAllocateBuffers, - kOpProducerQueueAllocateBuffers, - std::vector>( - uint32_t width, uint32_t height, uint32_t layer_count, - uint32_t format, uint64_t usage, size_t buffer_count)); - PDX_REMOTE_METHOD(ProducerQueueInsertBuffer, kOpProducerQueueInsertBuffer, - size_t(int buffer_cid)); - PDX_REMOTE_METHOD(ProducerQueueRemoveBuffer, kOpProducerQueueRemoveBuffer, - void(size_t slot)); - PDX_REMOTE_METHOD(ConsumerQueueImportBuffers, kOpConsumerQueueImportBuffers, - std::vector>(Void)); -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_BUFFERHUB_RPC_H_ diff --git a/libs/vr/libbufferhub/include/private/dvr/consumer_buffer.h b/libs/vr/libbufferhub/include/private/dvr/consumer_buffer.h deleted file mode 100644 index 726f0350b0..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/consumer_buffer.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef ANDROID_DVR_CONSUMER_BUFFER_H_ -#define ANDROID_DVR_CONSUMER_BUFFER_H_ - -#include - -namespace android { -namespace dvr { - -// This is a connection to a producer buffer, which can be located in another -// application. When that buffer is Post()ed, this fd will be signaled and -// Acquire allows read access. The user is responsible for making sure that -// Acquire is called with the correct metadata structure. The only guarantee the -// API currently provides is that an Acquire() with metadata of the wrong size -// will fail. -class ConsumerBuffer : public pdx::ClientBase { - public: - // This call assumes ownership of |fd|. - static std::unique_ptr Import(LocalChannelHandle channel); - static std::unique_ptr Import( - Status status); - - // Attempt to retrieve a post event from buffer hub. If successful, - // |ready_fence| will be set to a fence to wait on until the buffer is ready. - // This call will only succeed after the fd is signalled. This call may be - // performed as an alternative to the Acquire() with metadata. In such cases - // the metadata is not read. - // - // This returns zero or negative unix error code. - int Acquire(LocalHandle* ready_fence); - - // Attempt to retrieve a post event from buffer hub. If successful, - // |ready_fence| is set to a fence signaling that the contents of the buffer - // are available. This call will only succeed if the buffer is in the posted - // state. - // Returns zero on success, or a negative errno code otherwise. - int Acquire(LocalHandle* ready_fence, void* meta, size_t user_metadata_size); - - // Asynchronously acquires a bufer. - int AcquireAsync(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence); - - // Releases the buffer from any buffer state. If the fence is valid the fence - // determines the buffer usage, otherwise the buffer is released immediately. - // This returns zero or a negative unix error code. - int Release(const LocalHandle& release_fence); - int ReleaseAsync(); - - // Asynchronously releases a buffer. Similar to the synchronous version above, - // except that it does not wait for BufferHub to reply with success or error. - // The fence and metadata are passed to consumer via shared fd and shared - // memory. - int ReleaseAsync(const DvrNativeBufferMetadata* meta, - const LocalHandle& release_fence); - - // May be called after or instead of Acquire to indicate that the consumer - // does not need to access the buffer this cycle. This returns zero or a - // negative unix error code. - int Discard(); - - private: - friend BASE; - - explicit ConsumerBuffer(LocalChannelHandle channel); - - // Local state transition helpers. - int LocalAcquire(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence); - int LocalRelease(const DvrNativeBufferMetadata* meta, - const LocalHandle& release_fence); -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_CONSUMER_BUFFER_H_ diff --git a/libs/vr/libbufferhub/include/private/dvr/ion_buffer.h b/libs/vr/libbufferhub/include/private/dvr/ion_buffer.h deleted file mode 100644 index ed38e7f448..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/ion_buffer.h +++ /dev/null @@ -1,100 +0,0 @@ -#ifndef ANDROID_DVR_ION_BUFFER_H_ -#define ANDROID_DVR_ION_BUFFER_H_ - -#include -#include -#include - -namespace android { -namespace dvr { - -// IonBuffer is an abstraction of Ion/Gralloc buffers. -class IonBuffer { - public: - IonBuffer(); - IonBuffer(uint32_t width, uint32_t height, uint32_t format, uint64_t usage); - IonBuffer(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t stride, uint32_t format, uint64_t usage); - IonBuffer(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage); - ~IonBuffer(); - - IonBuffer(IonBuffer&& other) noexcept; - IonBuffer& operator=(IonBuffer&& other) noexcept; - - // Returns check this IonBuffer holds a valid Gralloc buffer. - bool IsValid() const { return buffer_ && buffer_->initCheck() == OK; } - - // Frees the underlying native handle and leaves the instance initialized to - // empty. - void FreeHandle(); - - // Allocates a new native handle with the given parameters, freeing the - // previous native handle if necessary. Returns 0 on success or a negative - // errno code otherwise. If allocation fails the previous native handle is - // left intact. - int Alloc(uint32_t width, uint32_t height, uint32_t layer_count, - uint32_t format, uint64_t usage); - - // Resets the underlying native handle and parameters, freeing the previous - // native handle if necessary. - void Reset(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage); - - // Like Reset but also registers the native handle, which is necessary for - // native handles received over IPC. Returns 0 on success or a negative errno - // code otherwise. If import fails the previous native handle is left intact. - int Import(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage); - - // Like Reset but imports a native handle from raw fd and int arrays. Returns - // 0 on success or a negative errno code otherwise. If import fails the - // previous native handle is left intact. - int Import(const int* fd_array, int fd_count, const int* int_array, - int int_count, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage); - - // Duplicates the native handle underlying |other| and then imports it. This - // is useful for creating multiple, independent views of the same Ion/Gralloc - // buffer. Returns 0 on success or a negative errno code otherwise. If - // duplication or import fail the previous native handle is left intact. - int Duplicate(const IonBuffer* other); - - int Lock(uint32_t usage, int x, int y, int width, int height, void** address); - int LockYUV(uint32_t usage, int x, int y, int width, int height, - struct android_ycbcr* yuv); - int Unlock(); - - sp& buffer() { return buffer_; } - const sp& buffer() const { return buffer_; } - buffer_handle_t handle() const { - return buffer_.get() ? buffer_->handle : nullptr; - } - uint32_t width() const { return buffer_.get() ? buffer_->getWidth() : 0; } - uint32_t height() const { return buffer_.get() ? buffer_->getHeight() : 0; } - uint32_t layer_count() const { - return buffer_.get() ? buffer_->getLayerCount() : 0; - } - uint32_t stride() const { return buffer_.get() ? buffer_->getStride() : 0; } - uint32_t format() const { - return buffer_.get() ? buffer_->getPixelFormat() : 0; - } - uint64_t usage() const { - return buffer_.get() ? static_cast(buffer_->getUsage()) : 0; - } - - private: - sp buffer_; - - IonBuffer(const IonBuffer&) = delete; - void operator=(const IonBuffer&) = delete; -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_ION_BUFFER_H_ diff --git a/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h b/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h deleted file mode 100644 index a5c6ca238a..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef ANDROID_DVR_NATIVE_HANDLE_WRAPPER_H_ -#define ANDROID_DVR_NATIVE_HANDLE_WRAPPER_H_ - -#include -#include -#include - -#include - -namespace android { -namespace dvr { - -// A PDX-friendly wrapper to maintain the life cycle of a native_handle_t -// object. -// -// See https://source.android.com/devices/architecture/hidl/types#handle_t for -// more information about native_handle_t. -template -class NativeHandleWrapper { - public: - NativeHandleWrapper() = default; - NativeHandleWrapper(NativeHandleWrapper&& other) = default; - NativeHandleWrapper& operator=(NativeHandleWrapper&& other) = default; - - // Create a new NativeHandleWrapper by duplicating the handle. - explicit NativeHandleWrapper(const native_handle_t* handle) { - const int fd_count = handle->numFds; - const int int_count = handle->numInts; - - // Populate the fd and int vectors: native_handle->data[] is an array of fds - // followed by an array of opaque ints. - for (int i = 0; i < fd_count; i++) { - fds_.emplace_back(FileHandleType::AsDuplicate(handle->data[i])); - } - for (int i = 0; i < int_count; i++) { - ints_.push_back(handle->data[fd_count + i]); - } - } - - size_t int_count() const { return ints_.size(); } - size_t fd_count() const { return fds_.size(); } - bool IsValid() const { return ints_.size() != 0 || fds_.size() != 0; } - - // Duplicate a native handle from the wrapper. - native_handle_t* DuplicateHandle() const { - if (!IsValid()) { - return nullptr; - } - - // numFds + numInts ints. - std::vector fds; - for (const auto& fd : fds_) { - if (!fd.IsValid()) { - return nullptr; - } - fds.emplace_back(fd.Duplicate()); - } - - return FromFdsAndInts(std::move(fds), ints_); - } - - // Takes the native handle out of the wrapper. - native_handle_t* TakeHandle() { - if (!IsValid()) { - return nullptr; - } - - return FromFdsAndInts(std::move(fds_), std::move(ints_)); - } - - private: - NativeHandleWrapper(const NativeHandleWrapper&) = delete; - void operator=(const NativeHandleWrapper&) = delete; - - static native_handle_t* FromFdsAndInts(std::vector fds, - std::vector ints) { - native_handle_t* handle = native_handle_create(fds.size(), ints.size()); - if (!handle) { - ALOGE("NativeHandleWrapper::TakeHandle: Failed to create new handle."); - return nullptr; - } - - // numFds + numInts ints. - for (int i = 0; i < handle->numFds; i++) { - handle->data[i] = fds[i].Release(); - } - memcpy(&handle->data[handle->numFds], ints.data(), - sizeof(int) * handle->numInts); - - return handle; - } - - std::vector ints_; - std::vector fds_; - - PDX_SERIALIZABLE_MEMBERS(NativeHandleWrapper, ints_, fds_); -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_NATIVE_HANDLE_WRAPPER_H_ diff --git a/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h b/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h deleted file mode 100644 index 7ec345c4b5..0000000000 --- a/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef ANDROID_DVR_PRODUCER_BUFFER_H_ -#define ANDROID_DVR_PRODUCER_BUFFER_H_ - -#include - -namespace android { -namespace dvr { - -// This represents a writable buffer. Calling Post notifies all clients and -// makes the buffer read-only. Call Gain to acquire write access. A buffer -// may have many consumers. -// -// The user of ProducerBuffer is responsible with making sure that the Post() is -// done with the correct metadata type and size. The user is also responsible -// for making sure that remote ends (ConsumerBuffers) are also using the correct -// metadata when acquiring the buffer. The API guarantees that a Post() with a -// metadata of wrong size will fail. However, it currently does not do any -// type checking. -// The API also assumes that metadata is a serializable type (plain old data). -class ProducerBuffer : public pdx::ClientBase { - public: - // Imports a bufferhub producer channel, assuming ownership of its handle. - static std::unique_ptr Import(LocalChannelHandle channel); - static std::unique_ptr Import( - Status status); - - // Asynchronously posts a buffer. The fence and metadata are passed to - // consumer via shared fd and shared memory. - int PostAsync(const DvrNativeBufferMetadata* meta, - const LocalHandle& ready_fence); - - // Post this buffer, passing |ready_fence| to the consumers. The bytes in - // |meta| are passed unaltered to the consumers. The producer must not modify - // the buffer until it is re-gained. - // This returns zero or a negative unix error code. - int Post(const LocalHandle& ready_fence, const void* meta, - size_t user_metadata_size); - - int Post(const LocalHandle& ready_fence) { - return Post(ready_fence, nullptr, 0); - } - - // Attempt to re-gain the buffer for writing. If |release_fence| is valid, it - // must be waited on before using the buffer. If it is not valid then the - // buffer is free for immediate use. This call will succeed if the buffer - // is in the released state, or in posted state and gain_posted_buffer is - // true. - // - // @param release_fence output fence. - // @param gain_posted_buffer whether to gain posted buffer or not. - // @return This returns zero or a negative unix error code. - int Gain(LocalHandle* release_fence, bool gain_posted_buffer = false); - - // Asynchronously marks a released buffer as gained. This method is similar to - // the synchronous version above, except that it does not wait for BufferHub - // to acknowledge success or failure. Because of the asynchronous nature of - // the underlying message, no error is returned if this method is called when - // the buffer is in an incorrect state. Returns zero if sending the message - // succeeded, or a negative errno code if local error check fails. - // TODO(b/112007999): gain_posted_buffer true is only used to prevent - // libdvrtracking from starving when there are non-responding clients. This - // gain_posted_buffer param can be removed once libdvrtracking start to use - // the new AHardwareBuffer API. - int GainAsync(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence, - bool gain_posted_buffer = false); - int GainAsync(); - - // Detaches a ProducerBuffer from an existing producer/consumer set. Can only - // be called when a producer buffer has exclusive access to the buffer (i.e. - // in the gain'ed state). On the successful return of the IPC call, a new - // LocalChannelHandle representing a detached buffer will be returned and all - // existing producer and consumer channels will be closed. Further IPCs - // towards those channels will return error. - Status Detach(); - - private: - friend BASE; - - // Constructors are automatically exposed through ProducerBuffer::Create(...) - // static template methods inherited from ClientBase, which take the same - // arguments as the constructors. - - // Constructs a buffer with the given geometry and parameters. - ProducerBuffer(uint32_t width, uint32_t height, uint32_t format, - uint64_t usage, size_t metadata_size = 0); - - // Constructs a blob (flat) buffer with the given usage flags. - ProducerBuffer(uint64_t usage, size_t size); - - // Imports the given file handle to a producer channel, taking ownership. - explicit ProducerBuffer(LocalChannelHandle channel); - - // Local state transition helpers. - int LocalGain(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence, - bool gain_posted_buffer = false); - int LocalPost(const DvrNativeBufferMetadata* meta, - const LocalHandle& ready_fence); -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_PRODUCER_BUFFER_H_ diff --git a/libs/vr/libbufferhub/ion_buffer.cpp b/libs/vr/libbufferhub/ion_buffer.cpp deleted file mode 100644 index 196541010e..0000000000 --- a/libs/vr/libbufferhub/ion_buffer.cpp +++ /dev/null @@ -1,240 +0,0 @@ -#include - -#include -#define ATRACE_TAG ATRACE_TAG_GRAPHICS -#include - -#include - -namespace { - -constexpr uint32_t kDefaultGraphicBufferLayerCount = 1; - -} // anonymous namespace - -namespace android { -namespace dvr { - -IonBuffer::IonBuffer() : IonBuffer(nullptr, 0, 0, 0, 0, 0, 0) {} - -IonBuffer::IonBuffer(uint32_t width, uint32_t height, uint32_t format, - uint64_t usage) - : IonBuffer() { - Alloc(width, height, kDefaultGraphicBufferLayerCount, format, usage); -} - -IonBuffer::IonBuffer(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t stride, uint32_t format, uint64_t usage) - : IonBuffer(handle, width, height, kDefaultGraphicBufferLayerCount, stride, - format, usage) {} - -IonBuffer::IonBuffer(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage) - : buffer_(nullptr) { - ALOGD_IF(TRACE, - "IonBuffer::IonBuffer: handle=%p width=%u height=%u layer_count=%u " - "stride=%u format=%u usage=%" PRIx64, - handle, width, height, layer_count, stride, format, usage); - if (handle != 0) { - Import(handle, width, height, layer_count, stride, format, usage); - } -} - -IonBuffer::~IonBuffer() { - ALOGD_IF(TRACE, - "IonBuffer::~IonBuffer: handle=%p width=%u height=%u stride=%u " - "format=%u usage=%" PRIx64, - handle(), width(), height(), stride(), format(), usage()); - FreeHandle(); -} - -IonBuffer::IonBuffer(IonBuffer&& other) noexcept : IonBuffer() { - *this = std::move(other); -} - -IonBuffer& IonBuffer::operator=(IonBuffer&& other) noexcept { - ALOGD_IF(TRACE, "IonBuffer::operator=: handle_=%p other.handle_=%p", handle(), - other.handle()); - - if (this != &other) { - buffer_ = other.buffer_; - other.FreeHandle(); - } - return *this; -} - -void IonBuffer::FreeHandle() { - if (buffer_.get()) { - // GraphicBuffer unregisters and cleans up the handle if needed - buffer_ = nullptr; - } -} - -int IonBuffer::Alloc(uint32_t width, uint32_t height, uint32_t layer_count, - uint32_t format, uint64_t usage) { - ALOGD_IF(TRACE, - "IonBuffer::Alloc: width=%u height=%u layer_count=%u format=%u " - "usage=%" PRIx64, width, height, layer_count, format, usage); - - sp buffer = - new GraphicBuffer(width, height, format, layer_count, usage); - if (buffer->initCheck() != OK) { - ALOGE("IonBuffer::Aloc: Failed to allocate buffer"); - return -EINVAL; - } else { - buffer_ = buffer; - return 0; - } -} - -void IonBuffer::Reset(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage) { - ALOGD_IF(TRACE, - "IonBuffer::Reset: handle=%p width=%u height=%u layer_count=%u " - "stride=%u format=%u usage=%" PRIx64, - handle, width, height, layer_count, stride, format, usage); - Import(handle, width, height, layer_count, stride, format, usage); -} - -int IonBuffer::Import(buffer_handle_t handle, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage) { - ATRACE_NAME("IonBuffer::Import1"); - ALOGD_IF(TRACE, - "IonBuffer::Import: handle=%p width=%u height=%u layer_count=%u " - "stride=%u format=%u usage=%" PRIx64, - handle, width, height, layer_count, stride, format, usage); - FreeHandle(); - sp buffer = - new GraphicBuffer(handle, GraphicBuffer::TAKE_UNREGISTERED_HANDLE, width, - height, format, layer_count, usage, stride); - if (buffer->initCheck() != OK) { - ALOGE("IonBuffer::Import: Failed to import buffer"); - return -EINVAL; - } else { - buffer_ = buffer; - return 0; - } -} - -int IonBuffer::Import(const int* fd_array, int fd_count, const int* int_array, - int int_count, uint32_t width, uint32_t height, - uint32_t layer_count, uint32_t stride, uint32_t format, - uint64_t usage) { - ATRACE_NAME("IonBuffer::Import2"); - ALOGD_IF(TRACE, - "IonBuffer::Import: fd_count=%d int_count=%d width=%u height=%u " - "layer_count=%u stride=%u format=%u usage=%" PRIx64, - fd_count, int_count, width, height, layer_count, stride, format, - usage); - - if (fd_count < 0 || int_count < 0) { - ALOGE("IonBuffer::Import: invalid arguments."); - return -EINVAL; - } - - native_handle_t* handle = native_handle_create(fd_count, int_count); - if (!handle) { - ALOGE("IonBuffer::Import: failed to create new native handle."); - return -ENOMEM; - } - - // Copy fd_array into the first part of handle->data and int_array right - // after it. - memcpy(handle->data, fd_array, sizeof(int) * fd_count); - memcpy(handle->data + fd_count, int_array, sizeof(int) * int_count); - - const int ret = - Import(handle, width, height, layer_count, stride, format, usage); - if (ret < 0) { - ALOGE("IonBuffer::Import: failed to import raw native handle: %s", - strerror(-ret)); - native_handle_close(handle); - native_handle_delete(handle); - } - - return ret; -} - -int IonBuffer::Duplicate(const IonBuffer* other) { - if (!other->handle()) - return -EINVAL; - - const int fd_count = other->handle()->numFds; - const int int_count = other->handle()->numInts; - - if (fd_count < 0 || int_count < 0) - return -EINVAL; - - native_handle_t* handle = native_handle_create(fd_count, int_count); - if (!handle) { - ALOGE("IonBuffer::Duplicate: Failed to create new native handle."); - return -ENOMEM; - } - - // Duplicate the file descriptors from the other native handle. - for (int i = 0; i < fd_count; i++) - handle->data[i] = dup(other->handle()->data[i]); - - // Copy the ints after the file descriptors. - memcpy(handle->data + fd_count, other->handle()->data + fd_count, - sizeof(int) * int_count); - - const int ret = - Import(handle, other->width(), other->height(), other->layer_count(), - other->stride(), other->format(), other->usage()); - if (ret < 0) { - ALOGE("IonBuffer::Duplicate: Failed to import duplicate native handle: %s", - strerror(-ret)); - native_handle_close(handle); - native_handle_delete(handle); - } - - return ret; -} - -int IonBuffer::Lock(uint32_t usage, int x, int y, int width, int height, - void** address) { - ATRACE_NAME("IonBuffer::Lock"); - ALOGD_IF(TRACE, - "IonBuffer::Lock: handle=%p usage=%d x=%d y=%d width=%d height=%d " - "address=%p", - handle(), usage, x, y, width, height, address); - - status_t err = - buffer_->lock(usage, Rect(x, y, x + width, y + height), address); - if (err != OK) - return -EINVAL; - else - return 0; -} - -int IonBuffer::LockYUV(uint32_t usage, int x, int y, int width, int height, - struct android_ycbcr* yuv) { - ATRACE_NAME("IonBuffer::LockYUV"); - ALOGD_IF(TRACE, - "IonBuffer::Lock: handle=%p usage=%d x=%d y=%d width=%d height=%d", - handle(), usage, x, y, width, height); - - status_t err = - buffer_->lockYCbCr(usage, Rect(x, y, x + width, y + height), yuv); - if (err != OK) - return -EINVAL; - else - return 0; -} - -int IonBuffer::Unlock() { - ATRACE_NAME("IonBuffer::Unlock"); - ALOGD_IF(TRACE, "IonBuffer::Unlock: handle=%p", handle()); - - status_t err = buffer_->unlock(); - if (err != OK) - return -EINVAL; - else - return 0; -} -} // namespace dvr -} // namespace android diff --git a/libs/vr/libbufferhub/producer_buffer.cpp b/libs/vr/libbufferhub/producer_buffer.cpp deleted file mode 100644 index aa9d07282b..0000000000 --- a/libs/vr/libbufferhub/producer_buffer.cpp +++ /dev/null @@ -1,296 +0,0 @@ -#include - -using android::pdx::LocalChannelHandle; -using android::pdx::LocalHandle; -using android::pdx::Status; - -namespace android { -namespace dvr { - -ProducerBuffer::ProducerBuffer(uint32_t width, uint32_t height, uint32_t format, - uint64_t usage, size_t user_metadata_size) - : BASE(BufferHubRPC::kClientPath) { - ATRACE_NAME("ProducerBuffer::ProducerBuffer"); - ALOGD_IF(TRACE, - "ProducerBuffer::ProducerBuffer: fd=%d width=%u height=%u format=%u " - "usage=%" PRIx64 " user_metadata_size=%zu", - event_fd(), width, height, format, usage, user_metadata_size); - - auto status = InvokeRemoteMethod( - width, height, format, usage, user_metadata_size); - if (!status) { - ALOGE( - "ProducerBuffer::ProducerBuffer: Failed to create producer buffer: %s", - status.GetErrorMessage().c_str()); - Close(-status.error()); - return; - } - - const int ret = ImportBuffer(); - if (ret < 0) { - ALOGE( - "ProducerBuffer::ProducerBuffer: Failed to import producer buffer: %s", - strerror(-ret)); - Close(ret); - } -} - -ProducerBuffer::ProducerBuffer(uint64_t usage, size_t size) - : BASE(BufferHubRPC::kClientPath) { - ATRACE_NAME("ProducerBuffer::ProducerBuffer"); - ALOGD_IF(TRACE, "ProducerBuffer::ProducerBuffer: usage=%" PRIx64 " size=%zu", - usage, size); - const int width = static_cast(size); - const int height = 1; - const int format = HAL_PIXEL_FORMAT_BLOB; - const size_t user_metadata_size = 0; - - auto status = InvokeRemoteMethod( - width, height, format, usage, user_metadata_size); - if (!status) { - ALOGE("ProducerBuffer::ProducerBuffer: Failed to create blob: %s", - status.GetErrorMessage().c_str()); - Close(-status.error()); - return; - } - - const int ret = ImportBuffer(); - if (ret < 0) { - ALOGE( - "ProducerBuffer::ProducerBuffer: Failed to import producer buffer: %s", - strerror(-ret)); - Close(ret); - } -} - -ProducerBuffer::ProducerBuffer(LocalChannelHandle channel) - : BASE(std::move(channel)) { - const int ret = ImportBuffer(); - if (ret < 0) { - ALOGE( - "ProducerBuffer::ProducerBuffer: Failed to import producer buffer: %s", - strerror(-ret)); - Close(ret); - } -} - -int ProducerBuffer::LocalPost(const DvrNativeBufferMetadata* meta, - const LocalHandle& ready_fence) { - if (const int error = CheckMetadata(meta->user_metadata_size)) - return error; - - // The buffer can be posted iff the buffer state for this client is gained. - uint32_t current_buffer_state = - buffer_state_->load(std::memory_order_acquire); - if (!BufferHubDefs::isClientGained(current_buffer_state, - client_state_mask())) { - ALOGE("%s: not gained, id=%d state=%" PRIx32 ".", __FUNCTION__, id(), - current_buffer_state); - return -EBUSY; - } - - // Set the producer client buffer state to released, that of all other clients - // (both existing and non-existing clients) to posted. - uint32_t updated_buffer_state = - (~client_state_mask()) & BufferHubDefs::kHighBitsMask; - while (!buffer_state_->compare_exchange_weak( - current_buffer_state, updated_buffer_state, std::memory_order_acq_rel, - std::memory_order_acquire)) { - if (!BufferHubDefs::isClientGained(current_buffer_state, - client_state_mask())) { - ALOGE( - "%s: Failed to post the buffer. The buffer is no longer gained, " - "id=%d state=%" PRIx32 ".", - __FUNCTION__, id(), current_buffer_state); - return -EBUSY; - } - } - - // Copy the canonical metadata. - void* metadata_ptr = reinterpret_cast(&metadata_header_->metadata); - memcpy(metadata_ptr, meta, sizeof(DvrNativeBufferMetadata)); - // Copy extra user requested metadata. - if (meta->user_metadata_ptr && meta->user_metadata_size) { - void* metadata_src = reinterpret_cast(meta->user_metadata_ptr); - memcpy(user_metadata_ptr_, metadata_src, meta->user_metadata_size); - } - - // Send out the acquire fence through the shared epoll fd. Note that during - // posting no consumer is not expected to be polling on the fence. - if (const int error = UpdateSharedFence(ready_fence, shared_acquire_fence_)) - return error; - - return 0; -} - -int ProducerBuffer::Post(const LocalHandle& ready_fence, const void* meta, - size_t user_metadata_size) { - ATRACE_NAME("ProducerBuffer::Post"); - - // Populate cononical metadata for posting. - DvrNativeBufferMetadata canonical_meta; - canonical_meta.user_metadata_ptr = reinterpret_cast(meta); - canonical_meta.user_metadata_size = user_metadata_size; - - if (const int error = LocalPost(&canonical_meta, ready_fence)) - return error; - - return ReturnStatusOrError(InvokeRemoteMethod( - BorrowedFence(ready_fence.Borrow()))); -} - -int ProducerBuffer::PostAsync(const DvrNativeBufferMetadata* meta, - const LocalHandle& ready_fence) { - ATRACE_NAME("ProducerBuffer::PostAsync"); - - if (const int error = LocalPost(meta, ready_fence)) - return error; - - return ReturnStatusOrError(SendImpulse(BufferHubRPC::ProducerPost::Opcode)); -} - -int ProducerBuffer::LocalGain(DvrNativeBufferMetadata* out_meta, - LocalHandle* out_fence, bool gain_posted_buffer) { - if (!out_meta) - return -EINVAL; - - uint32_t current_buffer_state = - buffer_state_->load(std::memory_order_acquire); - ALOGD_IF(TRACE, "%s: buffer=%d, state=%" PRIx32 ".", __FUNCTION__, id(), - current_buffer_state); - - if (BufferHubDefs::isClientGained(current_buffer_state, - client_state_mask())) { - ALOGV("%s: already gained id=%d.", __FUNCTION__, id()); - return 0; - } - if (BufferHubDefs::isAnyClientAcquired(current_buffer_state) || - BufferHubDefs::isAnyClientGained(current_buffer_state) || - (BufferHubDefs::isAnyClientPosted( - current_buffer_state & - active_clients_bit_mask_->load(std::memory_order_acquire)) && - !gain_posted_buffer)) { - ALOGE("%s: not released id=%d state=%" PRIx32 ".", __FUNCTION__, id(), - current_buffer_state); - return -EBUSY; - } - // Change the buffer state to gained state. - uint32_t updated_buffer_state = client_state_mask(); - while (!buffer_state_->compare_exchange_weak( - current_buffer_state, updated_buffer_state, std::memory_order_acq_rel, - std::memory_order_acquire)) { - if (BufferHubDefs::isAnyClientAcquired(current_buffer_state) || - BufferHubDefs::isAnyClientGained(current_buffer_state) || - (BufferHubDefs::isAnyClientPosted( - current_buffer_state & - active_clients_bit_mask_->load(std::memory_order_acquire)) && - !gain_posted_buffer)) { - ALOGE( - "%s: Failed to gain the buffer. The buffer is no longer released. " - "id=%d state=%" PRIx32 ".", - __FUNCTION__, id(), current_buffer_state); - return -EBUSY; - } - } - - // Canonical metadata is undefined on Gain. Except for user_metadata and - // release_fence_mask. Fill in the user_metadata_ptr in address space of the - // local process. - if (metadata_header_->metadata.user_metadata_size && user_metadata_ptr_) { - out_meta->user_metadata_size = - metadata_header_->metadata.user_metadata_size; - out_meta->user_metadata_ptr = - reinterpret_cast(user_metadata_ptr_); - } else { - out_meta->user_metadata_size = 0; - out_meta->user_metadata_ptr = 0; - } - - uint32_t current_fence_state = fence_state_->load(std::memory_order_acquire); - uint32_t current_active_clients_bit_mask = - active_clients_bit_mask_->load(std::memory_order_acquire); - // If there are release fence(s) from consumer(s), we need to return it to the - // consumer(s). - // TODO(b/112007999) add an atomic variable in metadata header in shared - // memory to indicate which client is the last producer of the buffer. - // Currently, assume the first client is the only producer to the buffer. - if (current_fence_state & current_active_clients_bit_mask & - (~BufferHubDefs::kFirstClientBitMask)) { - *out_fence = shared_release_fence_.Duplicate(); - out_meta->release_fence_mask = current_fence_state & - current_active_clients_bit_mask & - (~BufferHubDefs::kFirstClientBitMask); - } - - return 0; -} - -int ProducerBuffer::Gain(LocalHandle* release_fence, bool gain_posted_buffer) { - ATRACE_NAME("ProducerBuffer::Gain"); - - DvrNativeBufferMetadata meta; - if (const int error = LocalGain(&meta, release_fence, gain_posted_buffer)) - return error; - - auto status = InvokeRemoteMethod(); - if (!status) - return -status.error(); - return 0; -} - -int ProducerBuffer::GainAsync(DvrNativeBufferMetadata* out_meta, - LocalHandle* release_fence, - bool gain_posted_buffer) { - ATRACE_NAME("ProducerBuffer::GainAsync"); - - if (const int error = LocalGain(out_meta, release_fence, gain_posted_buffer)) - return error; - - return ReturnStatusOrError(SendImpulse(BufferHubRPC::ProducerGain::Opcode)); -} - -int ProducerBuffer::GainAsync() { - DvrNativeBufferMetadata meta; - LocalHandle fence; - return GainAsync(&meta, &fence); -} - -std::unique_ptr ProducerBuffer::Import( - LocalChannelHandle channel) { - ALOGD_IF(TRACE, "ProducerBuffer::Import: channel=%d", channel.value()); - return ProducerBuffer::Create(std::move(channel)); -} - -std::unique_ptr ProducerBuffer::Import( - Status status) { - return Import(status ? status.take() - : LocalChannelHandle{nullptr, -status.error()}); -} - -Status ProducerBuffer::Detach() { - // TODO(b/112338294) remove after migrate producer buffer to binder - ALOGW("ProducerBuffer::Detach: not supported operation during migration"); - return {}; - - // TODO(b/112338294) Keep here for reference. Remove it after new logic is - // written. - /* uint32_t buffer_state = buffer_state_->load(std::memory_order_acquire); - if (!BufferHubDefs::isClientGained( - buffer_state, BufferHubDefs::kFirstClientStateMask)) { - // Can only detach a ProducerBuffer when it's in gained state. - ALOGW("ProducerBuffer::Detach: The buffer (id=%d, state=0x%" PRIx32 - ") is not in gained state.", - id(), buffer_state); - return {}; - } - - Status status = - InvokeRemoteMethod(); - ALOGE_IF(!status, - "ProducerBuffer::Detach: Failed to detach buffer (id=%d): %s.", id(), - status.GetErrorMessage().c_str()); - return status; */ -} - -} // namespace dvr -} // namespace android diff --git a/libs/vr/libdvr/Android.bp b/libs/vr/libdvr/Android.bp deleted file mode 100644 index 9dbeacba94..0000000000 --- a/libs/vr/libdvr/Android.bp +++ /dev/null @@ -1,35 +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 { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_library_headers { - name: "libdvr_headers", - export_include_dirs: ["include"], - vendor_available: true, - apex_available: [ - "//apex_available:platform", - "com.android.media", - "com.android.media.swcodec", - ], - min_sdk_version: "29", -} diff --git a/libs/vr/libdvr/include/CPPLINT.cfg b/libs/vr/libdvr/include/CPPLINT.cfg deleted file mode 100644 index 2f8a3c018c..0000000000 --- a/libs/vr/libdvr/include/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-build/header_guard diff --git a/libs/vr/libdvr/include/dvr/dvr_api.h b/libs/vr/libdvr/include/dvr/dvr_api.h deleted file mode 100644 index b7abb99559..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_api.h +++ /dev/null @@ -1,503 +0,0 @@ -#ifndef ANDROID_DVR_API_H_ -#define ANDROID_DVR_API_H_ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __GNUC__ -#define ALIGNED_DVR_STRUCT(x) __attribute__((packed, aligned(x))) -#else -#define ALIGNED_DVR_STRUCT(x) -#endif - -typedef struct ANativeWindow ANativeWindow; - -typedef struct DvrPoseAsync DvrPoseAsync; - -typedef uint64_t DvrSurfaceUpdateFlags; -typedef struct DvrDisplayManager DvrDisplayManager; -typedef struct DvrSurfaceState DvrSurfaceState; -typedef struct DvrPoseClient DvrPoseClient; -typedef struct DvrPoseDataCaptureRequest DvrPoseDataCaptureRequest; -typedef struct DvrVSyncClient DvrVSyncClient; -typedef struct DvrVirtualTouchpad DvrVirtualTouchpad; - -typedef struct DvrBuffer DvrBuffer; -typedef struct DvrWriteBuffer DvrWriteBuffer; -typedef struct DvrReadBuffer DvrReadBuffer; -typedef struct AHardwareBuffer AHardwareBuffer; - -typedef struct DvrReadBufferQueue DvrReadBufferQueue; -typedef struct DvrWriteBufferQueue DvrWriteBufferQueue; -typedef struct DvrNativeBufferMetadata DvrNativeBufferMetadata; - -typedef struct DvrSurface DvrSurface; -typedef uint64_t DvrSurfaceAttributeType; -typedef int32_t DvrSurfaceAttributeKey; -typedef int32_t DvrGlobalBufferKey; - -typedef struct DvrSurfaceAttributeValue DvrSurfaceAttributeValue; -typedef struct DvrSurfaceAttribute DvrSurfaceAttribute; - -typedef struct DvrReadBuffer DvrReadBuffer; -typedef struct DvrTrackingCamera DvrTrackingCamera; -typedef struct DvrTrackingFeatureExtractor DvrTrackingFeatureExtractor; -typedef struct DvrTrackingSensors DvrTrackingSensors; -typedef struct DvrWriteBufferQueue DvrWriteBufferQueue; - -// Note: To avoid breaking others during active development, only modify this -// struct by appending elements to the end. -// If you do feel we should to re-arrange or remove elements, please make a -// note of it, and wait until we're about to finalize for an API release to do -// so. -typedef struct DvrNativeDisplayMetrics { - uint32_t display_width; - uint32_t display_height; - uint32_t display_x_dpi; - uint32_t display_y_dpi; - uint32_t vsync_period_ns; -} DvrNativeDisplayMetrics; - -// native_handle contains the fds for the underlying ION allocations inside -// the gralloc buffer. This is needed temporarily while GPU vendors work on -// better support for AHardwareBuffer via glBindSharedBuffer APIs. See -// b/37207909. For now we can declare the native_handle struct where it is -// used for GPU late latching. See cutils/native_handle.h for the struct layout. -struct native_handle; - -// Device metrics data type enums. -enum { - // Request the device lens metrics protobuf. This matches cardboard protos. - DVR_CONFIGURATION_DATA_LENS_METRICS = 0, - // Request the device metrics protobuf. - DVR_CONFIGURATION_DATA_DEVICE_METRICS = 1, - // Request the per device configuration data file. - DVR_CONFIGURATION_DATA_DEVICE_CONFIG = 2, - // Request the edid data for the display. - DVR_CONFIGURATION_DATA_DEVICE_EDID = 3, -}; - -// dvr_display_manager.h -typedef int (*DvrDisplayManagerCreatePtr)(DvrDisplayManager** client_out); -typedef void (*DvrDisplayManagerDestroyPtr)(DvrDisplayManager* client); -typedef int (*DvrDisplayManagerGetEventFdPtr)(DvrDisplayManager* client); -typedef int (*DvrDisplayManagerTranslateEpollEventMaskPtr)( - DvrDisplayManager* client, int in_events, int* out_events); -typedef int (*DvrDisplayManagerGetSurfaceStatePtr)( - DvrDisplayManager* client, DvrSurfaceState* surface_state); -typedef int (*DvrDisplayManagerGetReadBufferQueuePtr)( - DvrDisplayManager* client, int surface_id, int queue_id, - DvrReadBufferQueue** queue_out); -typedef int (*DvrConfigurationDataGetPtr)(int config_type, uint8_t** data, - size_t* data_size); -typedef void (*DvrConfigurationDataDestroyPtr)(uint8_t* data); -typedef int (*DvrSurfaceStateCreatePtr)(DvrSurfaceState** surface_state); -typedef void (*DvrSurfaceStateDestroyPtr)(DvrSurfaceState* surface_state); -typedef int (*DvrSurfaceStateGetSurfaceCountPtr)(DvrSurfaceState* surface_state, - size_t* count_out); -typedef int (*DvrSurfaceStateGetUpdateFlagsPtr)( - DvrSurfaceState* surface_state, size_t surface_index, - DvrSurfaceUpdateFlags* flags_out); -typedef int (*DvrSurfaceStateGetSurfaceIdPtr)(DvrSurfaceState* surface_state, - size_t surface_index, - int* surface_id_out); -typedef int (*DvrSurfaceStateGetProcessIdPtr)(DvrSurfaceState* surface_state, - size_t surface_index, - int* process_id_out); -typedef int (*DvrSurfaceStateGetQueueCountPtr)(DvrSurfaceState* surface_state, - size_t surface_index, - size_t* count_out); -typedef ssize_t (*DvrSurfaceStateGetQueueIdsPtr)(DvrSurfaceState* surface_state, - size_t surface_index, - int* queue_ids, - size_t max_count); -typedef int (*DvrSurfaceStateGetZOrderPtr)(DvrSurfaceState* surface_state, - size_t surface_index, - int* z_order_out); -typedef int (*DvrSurfaceStateGetVisiblePtr)(DvrSurfaceState* surface_state, - size_t surface_index, - bool* visible_out); -typedef int (*DvrSurfaceStateGetAttributeCountPtr)( - DvrSurfaceState* surface_state, size_t surface_index, size_t* count_out); -typedef ssize_t (*DvrSurfaceStateGetAttributesPtr)( - DvrSurfaceState* surface_state, size_t surface_index, - DvrSurfaceAttribute* attributes, size_t max_attribute_count); - -// dvr_buffer.h -typedef void (*DvrWriteBufferCreateEmptyPtr)(DvrWriteBuffer** write_buffer_out); -typedef void (*DvrWriteBufferDestroyPtr)(DvrWriteBuffer* write_buffer); -typedef int (*DvrWriteBufferIsValidPtr)(DvrWriteBuffer* write_buffer); -typedef int (*DvrWriteBufferClearPtr)(DvrWriteBuffer* write_buffer); -typedef int (*DvrWriteBufferGetIdPtr)(DvrWriteBuffer* write_buffer); -typedef int (*DvrWriteBufferGetAHardwareBufferPtr)( - DvrWriteBuffer* write_buffer, AHardwareBuffer** hardware_buffer); -typedef int (*DvrWriteBufferPostPtr)(DvrWriteBuffer* write_buffer, - int ready_fence_fd, const void* meta, - size_t meta_size_bytes); -typedef int (*DvrWriteBufferGainPtr)(DvrWriteBuffer* write_buffer, - int* release_fence_fd); -typedef int (*DvrWriteBufferGainAsyncPtr)(DvrWriteBuffer* write_buffer); -typedef const struct native_handle* (*DvrWriteBufferGetNativeHandlePtr)( - DvrWriteBuffer* write_buffer); - -typedef void (*DvrReadBufferCreateEmptyPtr)(DvrReadBuffer** read_buffer_out); -typedef void (*DvrReadBufferDestroyPtr)(DvrReadBuffer* read_buffer); -typedef int (*DvrReadBufferIsValidPtr)(DvrReadBuffer* read_buffer); -typedef int (*DvrReadBufferClearPtr)(DvrReadBuffer* read_buffer); -typedef int (*DvrReadBufferGetIdPtr)(DvrReadBuffer* read_buffer); -typedef int (*DvrReadBufferGetAHardwareBufferPtr)( - DvrReadBuffer* read_buffer, AHardwareBuffer** hardware_buffer); -typedef int (*DvrReadBufferAcquirePtr)(DvrReadBuffer* read_buffer, - int* ready_fence_fd, void* meta, - size_t meta_size_bytes); -typedef int (*DvrReadBufferReleasePtr)(DvrReadBuffer* read_buffer, - int release_fence_fd); -typedef int (*DvrReadBufferReleaseAsyncPtr)(DvrReadBuffer* read_buffer); -typedef const struct native_handle* (*DvrReadBufferGetNativeHandlePtr)( - DvrReadBuffer* read_buffer); - -typedef void (*DvrBufferDestroyPtr)(DvrBuffer* buffer); -typedef int (*DvrBufferGetAHardwareBufferPtr)( - DvrBuffer* buffer, AHardwareBuffer** hardware_buffer); -typedef int (*DvrBufferGlobalLayoutVersionGetPtr)(); -typedef const struct native_handle* (*DvrBufferGetNativeHandlePtr)( - DvrBuffer* buffer); - -// dvr_buffer_queue.h -typedef int (*DvrWriteBufferQueueCreatePtr)(uint32_t width, uint32_t height, - uint32_t format, - uint32_t layer_count, - uint64_t usage, size_t capacity, - size_t metadata_size, - DvrWriteBufferQueue** queue_out); -typedef void (*DvrWriteBufferQueueDestroyPtr)(DvrWriteBufferQueue* write_queue); -typedef ssize_t (*DvrWriteBufferQueueGetCapacityPtr)( - DvrWriteBufferQueue* write_queue); -typedef int (*DvrWriteBufferQueueGetIdPtr)(DvrWriteBufferQueue* write_queue); -typedef int (*DvrWriteBufferQueueGetExternalSurfacePtr)( - DvrWriteBufferQueue* write_queue, ANativeWindow** out_window); -typedef int (*DvrWriteBufferQueueGetANativeWindowPtr)( - DvrWriteBufferQueue* write_queue, ANativeWindow** out_window); -typedef int (*DvrWriteBufferQueueCreateReadQueuePtr)( - DvrWriteBufferQueue* write_queue, DvrReadBufferQueue** out_read_queue); -typedef int (*DvrWriteBufferQueueDequeuePtr)(DvrWriteBufferQueue* write_queue, - int timeout, - DvrWriteBuffer* out_buffer, - int* out_fence_fd); -typedef int (*DvrWriteBufferQueueGainBufferPtr)( - DvrWriteBufferQueue* write_queue, int timeout, - DvrWriteBuffer** out_write_buffer, DvrNativeBufferMetadata* out_meta, - int* out_fence_fd); -typedef int (*DvrWriteBufferQueuePostBufferPtr)( - DvrWriteBufferQueue* write_queue, DvrWriteBuffer* write_buffer, - const DvrNativeBufferMetadata* meta, int ready_fence_fd); -typedef int (*DvrWriteBufferQueueResizeBufferPtr)( - DvrWriteBufferQueue* write_queue, uint32_t width, uint32_t height); -typedef void (*DvrReadBufferQueueDestroyPtr)(DvrReadBufferQueue* read_queue); -typedef ssize_t (*DvrReadBufferQueueGetCapacityPtr)( - DvrReadBufferQueue* read_queue); -typedef int (*DvrReadBufferQueueGetIdPtr)(DvrReadBufferQueue* read_queue); -typedef int (*DvrReadBufferQueueGetEventFdPtr)(DvrReadBufferQueue* read_queue); -typedef int (*DvrReadBufferQueueCreateReadQueuePtr)( - DvrReadBufferQueue* read_queue, DvrReadBufferQueue** out_read_queue); -typedef int (*DvrReadBufferQueueDequeuePtr)(DvrReadBufferQueue* read_queue, - int timeout, - DvrReadBuffer* out_buffer, - int* out_fence_fd, void* out_meta, - size_t meta_size_bytes); -typedef int (*DvrReadBufferQueueAcquireBufferPtr)( - DvrReadBufferQueue* read_queue, int timeout, - DvrReadBuffer** out_read_buffer, DvrNativeBufferMetadata* out_meta, - int* out_fence_fd); -typedef int (*DvrReadBufferQueueReleaseBufferPtr)( - DvrReadBufferQueue* read_queue, DvrReadBuffer* read_buffer, - const DvrNativeBufferMetadata* meta, int release_fence_fd); -typedef void (*DvrReadBufferQueueBufferAvailableCallback)(void* context); -typedef int (*DvrReadBufferQueueSetBufferAvailableCallbackPtr)( - DvrReadBufferQueue* read_queue, - DvrReadBufferQueueBufferAvailableCallback callback, void* context); -typedef void (*DvrReadBufferQueueBufferRemovedCallback)(DvrReadBuffer* buffer, - void* context); -typedef int (*DvrReadBufferQueueSetBufferRemovedCallbackPtr)( - DvrReadBufferQueue* read_queue, - DvrReadBufferQueueBufferRemovedCallback callback, void* context); -typedef int (*DvrReadBufferQueueHandleEventsPtr)( - DvrReadBufferQueue* read_queue); - -// dvr_surface.h -typedef int (*DvrSetupGlobalBufferPtr)(DvrGlobalBufferKey key, size_t size, - uint64_t usage, DvrBuffer** buffer_out); -typedef int (*DvrDeleteGlobalBufferPtr)(DvrGlobalBufferKey key); -typedef int (*DvrGetGlobalBufferPtr)(DvrGlobalBufferKey key, - DvrBuffer** out_buffer); -typedef int (*DvrSurfaceCreatePtr)(const DvrSurfaceAttribute* attributes, - size_t attribute_count, - DvrSurface** surface_out); -typedef void (*DvrSurfaceDestroyPtr)(DvrSurface* surface); -typedef int (*DvrSurfaceGetIdPtr)(DvrSurface* surface); -typedef int (*DvrSurfaceSetAttributesPtr)(DvrSurface* surface, - const DvrSurfaceAttribute* attributes, - size_t attribute_count); -typedef int (*DvrSurfaceCreateWriteBufferQueuePtr)( - DvrSurface* surface, uint32_t width, uint32_t height, uint32_t format, - uint32_t layer_count, uint64_t usage, size_t capacity, size_t metadata_size, - DvrWriteBufferQueue** queue_out); -typedef int (*DvrGetNativeDisplayMetricsPtr)(size_t sizeof_metrics, - DvrNativeDisplayMetrics* metrics); - -// dvr_vsync.h -typedef int (*DvrVSyncClientCreatePtr)(DvrVSyncClient** client_out); -typedef void (*DvrVSyncClientDestroyPtr)(DvrVSyncClient* client); -typedef int (*DvrVSyncClientGetSchedInfoPtr)(DvrVSyncClient* client, - int64_t* vsync_period_ns, - int64_t* next_timestamp_ns, - uint32_t* next_vsync_count); - -// libs/vr/libvrsensor/include/dvr/pose_client.h -typedef DvrPoseClient* (*DvrPoseClientCreatePtr)(); -typedef void (*DvrPoseClientDestroyPtr)(DvrPoseClient* client); -typedef int (*DvrPoseClientGetPtr)(DvrPoseClient* client, uint32_t vsync_count, - DvrPoseAsync* out_pose); -typedef uint32_t (*DvrPoseClientGetVsyncCountPtr)(DvrPoseClient* client); -typedef int (*DvrPoseClientGetControllerPtr)(DvrPoseClient* client, - int32_t controller_id, - uint32_t vsync_count, - DvrPoseAsync* out_pose); -typedef int (*DvrPoseClientSensorsEnablePtr)(DvrPoseClient* client, - bool enabled); -typedef int (*DvrPoseClientDataCapturePtr)(DvrPoseClient* client, - const DvrPoseDataCaptureRequest* request); -typedef int (*DvrPoseClientDataReaderDestroyPtr)(DvrPoseClient* client, - uint64_t data_type); - -// dvr_pose.h -typedef int (*DvrPoseClientGetDataReaderPtr)(DvrPoseClient* client, - uint64_t data_type, - DvrReadBufferQueue** read_queue); - -// services/vr/virtual_touchpad/include/dvr/virtual_touchpad_client.h - -// Touchpad IDs for *Touch*() and *ButtonState*() calls. -enum { - DVR_VIRTUAL_TOUCHPAD_PRIMARY = 0, - DVR_VIRTUAL_TOUCHPAD_VIRTUAL = 1, -}; -typedef DvrVirtualTouchpad* (*DvrVirtualTouchpadCreatePtr)(); -typedef void (*DvrVirtualTouchpadDestroyPtr)(DvrVirtualTouchpad* client); -typedef int (*DvrVirtualTouchpadAttachPtr)(DvrVirtualTouchpad* client); -typedef int (*DvrVirtualTouchpadDetachPtr)(DvrVirtualTouchpad* client); -typedef int (*DvrVirtualTouchpadTouchPtr)(DvrVirtualTouchpad* client, - int touchpad, float x, float y, - float pressure); -typedef int (*DvrVirtualTouchpadButtonStatePtr)(DvrVirtualTouchpad* client, - int touchpad, int buttons); -typedef int (*DvrVirtualTouchpadScrollPtr)(DvrVirtualTouchpad* client, - int touchpad, float x, float y); - -// dvr_hardware_composer_client.h -typedef struct DvrHwcClient DvrHwcClient; -typedef struct DvrHwcFrame DvrHwcFrame; -typedef int (*DvrHwcOnFrameCallback)(void* client_state, DvrHwcFrame* frame); -typedef DvrHwcClient* (*DvrHwcClientCreatePtr)(DvrHwcOnFrameCallback callback, - void* client_state); -typedef void (*DvrHwcClientDestroyPtr)(DvrHwcClient* client); -typedef void (*DvrHwcFrameDestroyPtr)(DvrHwcFrame* frame); -typedef DvrHwcDisplay (*DvrHwcFrameGetDisplayIdPtr)(DvrHwcFrame* frame); -typedef int32_t (*DvrHwcFrameGetDisplayWidthPtr)(DvrHwcFrame* frame); -typedef int32_t (*DvrHwcFrameGetDisplayHeightPtr)(DvrHwcFrame* frame); -typedef bool (*DvrHwcFrameGetDisplayRemovedPtr)(DvrHwcFrame* frame); -typedef size_t (*DvrHwcFrameGetLayerCountPtr)(DvrHwcFrame* frame); -typedef DvrHwcLayer (*DvrHwcFrameGetLayerIdPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef uint32_t (*DvrHwcFrameGetActiveConfigPtr)(DvrHwcFrame* frame); -typedef uint32_t (*DvrHwcFrameGetColorModePtr)(DvrHwcFrame* frame); -typedef void (*DvrHwcFrameGetColorTransformPtr)(DvrHwcFrame* frame, - float* out_matrix, - int32_t* out_hint); -typedef uint32_t (*DvrHwcFrameGetPowerModePtr)(DvrHwcFrame* frame); -typedef uint32_t (*DvrHwcFrameGetVsyncEnabledPtr)(DvrHwcFrame* frame); -typedef AHardwareBuffer* (*DvrHwcFrameGetLayerBufferPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef int (*DvrHwcFrameGetLayerFencePtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef DvrHwcRecti (*DvrHwcFrameGetLayerDisplayFramePtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef DvrHwcRectf (*DvrHwcFrameGetLayerCropPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef DvrHwcBlendMode (*DvrHwcFrameGetLayerBlendModePtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef float (*DvrHwcFrameGetLayerAlphaPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef uint32_t (*DvrHwcFrameGetLayerTypePtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef uint32_t (*DvrHwcFrameGetLayerApplicationIdPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef uint32_t (*DvrHwcFrameGetLayerZOrderPtr)(DvrHwcFrame* frame, - size_t layer_index); - -typedef void (*DvrHwcFrameGetLayerCursorPtr)(DvrHwcFrame* frame, - size_t layer_index, int32_t* out_x, - int32_t* out_y); - -typedef uint32_t (*DvrHwcFrameGetLayerTransformPtr)(DvrHwcFrame* frame, - size_t layer_index); - -typedef uint32_t (*DvrHwcFrameGetLayerDataspacePtr)(DvrHwcFrame* frame, - size_t layer_index); - -typedef uint32_t (*DvrHwcFrameGetLayerColorPtr)(DvrHwcFrame* frame, - size_t layer_index); - -typedef uint32_t (*DvrHwcFrameGetLayerNumVisibleRegionsPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef DvrHwcRecti (*DvrHwcFrameGetLayerVisibleRegionPtr)(DvrHwcFrame* frame, - size_t layer_index, - size_t index); - -typedef uint32_t (*DvrHwcFrameGetLayerNumDamagedRegionsPtr)(DvrHwcFrame* frame, - size_t layer_index); -typedef DvrHwcRecti (*DvrHwcFrameGetLayerDamagedRegionPtr)(DvrHwcFrame* frame, - size_t layer_index, - size_t index); - -// dvr_performance.h -typedef int (*DvrPerformanceSetSchedulerPolicyPtr)( - pid_t task_id, const char* scheduler_policy); - -// dvr_tracking.h -typedef int (*DvrTrackingCameraCreatePtr)(DvrTrackingCamera** out_camera); -typedef void (*DvrTrackingCameraDestroyPtr)(DvrTrackingCamera* camera); -typedef int (*DvrTrackingCameraStartPtr)(DvrTrackingCamera* camera, - DvrWriteBufferQueue* write_queue); -typedef int (*DvrTrackingCameraStopPtr)(DvrTrackingCamera* camera); - -typedef int (*DvrTrackingFeatureExtractorCreatePtr)( - DvrTrackingFeatureExtractor** out_extractor); -typedef void (*DvrTrackingFeatureExtractorDestroyPtr)( - DvrTrackingFeatureExtractor* extractor); -typedef void (*DvrTrackingFeatureCallback)(void* context, - const DvrTrackingFeatures* event); -typedef int (*DvrTrackingFeatureExtractorStartPtr)( - DvrTrackingFeatureExtractor* extractor, - DvrTrackingFeatureCallback callback, void* context); -typedef int (*DvrTrackingFeatureExtractorStopPtr)( - DvrTrackingFeatureExtractor* extractor); -typedef int (*DvrTrackingFeatureExtractorProcessBufferPtr)( - DvrTrackingFeatureExtractor* extractor, DvrReadBuffer* buffer, - const DvrTrackingBufferMetadata* metadata, bool* out_skipped); - -typedef void (*DvrTrackingSensorEventCallback)(void* context, - DvrTrackingSensorEvent* event); -typedef int (*DvrTrackingSensorsCreatePtr)(DvrTrackingSensors** out_sensors, - const char* mode); -typedef void (*DvrTrackingSensorsDestroyPtr)(DvrTrackingSensors* sensors); -typedef int (*DvrTrackingSensorsStartPtr)( - DvrTrackingSensors* sensors, DvrTrackingSensorEventCallback callback, - void* context); -typedef int (*DvrTrackingSensorsStopPtr)(DvrTrackingSensors* sensors); - -// The buffer metadata that an Android Surface (a.k.a. ANativeWindow) -// will populate. A DvrWriteBufferQueue must be created with this metadata iff -// ANativeWindow access is needed. Please do not remove, modify, or reorder -// existing data members. If new fields need to be added, please take extra care -// to make sure that new data field is padded properly the size of the struct -// stays same. -// TODO(b/118893702): move the definition to libnativewindow or libui -struct ALIGNED_DVR_STRUCT(8) DvrNativeBufferMetadata { -#ifdef __cplusplus - DvrNativeBufferMetadata() - : timestamp(0), - is_auto_timestamp(0), - dataspace(0), - crop_left(0), - crop_top(0), - crop_right(0), - crop_bottom(0), - scaling_mode(0), - transform(0), - index(0), - user_metadata_size(0), - user_metadata_ptr(0), - release_fence_mask(0), - reserved{0} {} -#endif - // Timestamp of the frame. - int64_t timestamp; - - // Whether the buffer is using auto timestamp. - int32_t is_auto_timestamp; - - // Must be one of the HAL_DATASPACE_XXX value defined in system/graphics.h - int32_t dataspace; - - // Crop extracted from an ACrop or android::Crop object. - int32_t crop_left; - int32_t crop_top; - int32_t crop_right; - int32_t crop_bottom; - - // Must be one of the NATIVE_WINDOW_SCALING_MODE_XXX value defined in - // system/window.h. - int32_t scaling_mode; - - // Must be one of the ANATIVEWINDOW_TRANSFORM_XXX value defined in - // android/native_window.h - int32_t transform; - - // The index of the frame. - int64_t index; - - // Size of additional metadata requested by user. - uint64_t user_metadata_size; - - // Raw memory address of the additional user defined metadata. Only valid when - // user_metadata_size is non-zero. - uint64_t user_metadata_ptr; - - // Only applicable for metadata retrieved from GainAsync. This indicates which - // consumer has pending fence that producer should epoll on. - uint32_t release_fence_mask; - - // Reserved bytes for so that the struct is forward compatible and padding to - // 104 bytes so the size is a multiple of 8. - int32_t reserved[9]; -}; - -#ifdef __cplusplus -// Warning: DvrNativeBufferMetadata is part of the DVR API and changing its size -// will cause compatiblity issues between different DVR API releases. -static_assert(sizeof(DvrNativeBufferMetadata) == 104, - "Unexpected size for DvrNativeBufferMetadata"); -#endif - -struct DvrApi_v1 { -// Defines an API entry for V1 (no version suffix). -#define DVR_V1_API_ENTRY(name) Dvr##name##Ptr name -#define DVR_V1_API_ENTRY_DEPRECATED(name) Dvr##name##Ptr name - -#include "dvr_api_entries.h" - -// Undefine macro definitions to play nice with Google3 style rules. -#undef DVR_V1_API_ENTRY -#undef DVR_V1_API_ENTRY_DEPRECATED -}; - -int dvrGetApi(void* api, size_t struct_size, int version); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // ANDROID_DVR_API_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_api_entries.h b/libs/vr/libdvr/include/dvr/dvr_api_entries.h deleted file mode 100644 index 3006b61b81..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_api_entries.h +++ /dev/null @@ -1,200 +0,0 @@ -// dvr_api_entries.h -// -// Defines the DVR platform library API entries. -// -// Do not include this header directly. - -#ifndef DVR_V1_API_ENTRY -#error Do not include this header directly. -#endif - -#ifndef DVR_V1_API_ENTRY_DEPRECATED -#error Do not include this header directly. -#endif - -// Do not delete this line: BEGIN CODEGEN OUTPUT -// Display manager client -DVR_V1_API_ENTRY(DisplayManagerCreate); -DVR_V1_API_ENTRY(DisplayManagerDestroy); -DVR_V1_API_ENTRY(DisplayManagerGetEventFd); -DVR_V1_API_ENTRY(DisplayManagerTranslateEpollEventMask); -DVR_V1_API_ENTRY(DisplayManagerGetSurfaceState); -DVR_V1_API_ENTRY(DisplayManagerGetReadBufferQueue); -DVR_V1_API_ENTRY(ConfigurationDataGet); -DVR_V1_API_ENTRY(ConfigurationDataDestroy); -DVR_V1_API_ENTRY(SurfaceStateCreate); -DVR_V1_API_ENTRY(SurfaceStateDestroy); -DVR_V1_API_ENTRY(SurfaceStateGetSurfaceCount); -DVR_V1_API_ENTRY(SurfaceStateGetUpdateFlags); -DVR_V1_API_ENTRY(SurfaceStateGetSurfaceId); -DVR_V1_API_ENTRY(SurfaceStateGetProcessId); -DVR_V1_API_ENTRY(SurfaceStateGetQueueCount); -DVR_V1_API_ENTRY(SurfaceStateGetQueueIds); -DVR_V1_API_ENTRY(SurfaceStateGetZOrder); -DVR_V1_API_ENTRY(SurfaceStateGetVisible); -DVR_V1_API_ENTRY(SurfaceStateGetAttributeCount); -DVR_V1_API_ENTRY(SurfaceStateGetAttributes); - -// Write buffer -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferCreateEmpty); -DVR_V1_API_ENTRY(WriteBufferDestroy); -DVR_V1_API_ENTRY(WriteBufferIsValid); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferClear); -DVR_V1_API_ENTRY(WriteBufferGetId); -DVR_V1_API_ENTRY(WriteBufferGetAHardwareBuffer); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferPost); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferGain); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferGainAsync); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferGetNativeHandle); - -// Read buffer -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferCreateEmpty); -DVR_V1_API_ENTRY(ReadBufferDestroy); -DVR_V1_API_ENTRY(ReadBufferIsValid); -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferClear); -DVR_V1_API_ENTRY(ReadBufferGetId); -DVR_V1_API_ENTRY(ReadBufferGetAHardwareBuffer); -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferAcquire); -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferRelease); -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferReleaseAsync); -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferGetNativeHandle); - -// Buffer -DVR_V1_API_ENTRY(BufferDestroy); -DVR_V1_API_ENTRY(BufferGetAHardwareBuffer); -DVR_V1_API_ENTRY_DEPRECATED(BufferGetNativeHandle); -DVR_V1_API_ENTRY(BufferGlobalLayoutVersionGet); - -// Write buffer queue -DVR_V1_API_ENTRY(WriteBufferQueueDestroy); -DVR_V1_API_ENTRY(WriteBufferQueueGetCapacity); -DVR_V1_API_ENTRY(WriteBufferQueueGetId); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferQueueGetExternalSurface); -DVR_V1_API_ENTRY(WriteBufferQueueCreateReadQueue); -DVR_V1_API_ENTRY_DEPRECATED(WriteBufferQueueDequeue); -DVR_V1_API_ENTRY(WriteBufferQueueResizeBuffer); - -// Read buffer queue -DVR_V1_API_ENTRY(ReadBufferQueueDestroy); -DVR_V1_API_ENTRY(ReadBufferQueueGetCapacity); -DVR_V1_API_ENTRY(ReadBufferQueueGetId); -DVR_V1_API_ENTRY(ReadBufferQueueCreateReadQueue); -DVR_V1_API_ENTRY_DEPRECATED(ReadBufferQueueDequeue); -DVR_V1_API_ENTRY(ReadBufferQueueSetBufferAvailableCallback); -DVR_V1_API_ENTRY(ReadBufferQueueSetBufferRemovedCallback); -DVR_V1_API_ENTRY(ReadBufferQueueHandleEvents); - -// V-Sync client -DVR_V1_API_ENTRY_DEPRECATED(VSyncClientCreate); -DVR_V1_API_ENTRY_DEPRECATED(VSyncClientDestroy); -DVR_V1_API_ENTRY_DEPRECATED(VSyncClientGetSchedInfo); - -// Display surface -DVR_V1_API_ENTRY(SurfaceCreate); -DVR_V1_API_ENTRY(SurfaceDestroy); -DVR_V1_API_ENTRY(SurfaceGetId); -DVR_V1_API_ENTRY(SurfaceSetAttributes); -DVR_V1_API_ENTRY(SurfaceCreateWriteBufferQueue); -DVR_V1_API_ENTRY(SetupGlobalBuffer); -DVR_V1_API_ENTRY(DeleteGlobalBuffer); -DVR_V1_API_ENTRY(GetGlobalBuffer); - -// Pose client -DVR_V1_API_ENTRY(PoseClientCreate); -DVR_V1_API_ENTRY(PoseClientDestroy); -DVR_V1_API_ENTRY(PoseClientGet); -DVR_V1_API_ENTRY(PoseClientGetVsyncCount); -DVR_V1_API_ENTRY(PoseClientGetController); - -// Virtual touchpad client -DVR_V1_API_ENTRY(VirtualTouchpadCreate); -DVR_V1_API_ENTRY(VirtualTouchpadDestroy); -DVR_V1_API_ENTRY(VirtualTouchpadAttach); -DVR_V1_API_ENTRY(VirtualTouchpadDetach); -DVR_V1_API_ENTRY(VirtualTouchpadTouch); -DVR_V1_API_ENTRY(VirtualTouchpadButtonState); - -// VR HWComposer client -DVR_V1_API_ENTRY(HwcClientCreate); -DVR_V1_API_ENTRY(HwcClientDestroy); -DVR_V1_API_ENTRY(HwcFrameDestroy); -DVR_V1_API_ENTRY(HwcFrameGetDisplayId); -DVR_V1_API_ENTRY(HwcFrameGetDisplayWidth); -DVR_V1_API_ENTRY(HwcFrameGetDisplayHeight); -DVR_V1_API_ENTRY(HwcFrameGetDisplayRemoved); -DVR_V1_API_ENTRY(HwcFrameGetActiveConfig); -DVR_V1_API_ENTRY(HwcFrameGetColorMode); -DVR_V1_API_ENTRY(HwcFrameGetColorTransform); -DVR_V1_API_ENTRY(HwcFrameGetPowerMode); -DVR_V1_API_ENTRY(HwcFrameGetVsyncEnabled); -DVR_V1_API_ENTRY(HwcFrameGetLayerCount); -DVR_V1_API_ENTRY(HwcFrameGetLayerId); -DVR_V1_API_ENTRY(HwcFrameGetLayerBuffer); -DVR_V1_API_ENTRY(HwcFrameGetLayerFence); -DVR_V1_API_ENTRY(HwcFrameGetLayerDisplayFrame); -DVR_V1_API_ENTRY(HwcFrameGetLayerCrop); -DVR_V1_API_ENTRY(HwcFrameGetLayerBlendMode); -DVR_V1_API_ENTRY(HwcFrameGetLayerAlpha); -DVR_V1_API_ENTRY(HwcFrameGetLayerType); -DVR_V1_API_ENTRY(HwcFrameGetLayerApplicationId); -DVR_V1_API_ENTRY(HwcFrameGetLayerZOrder); -DVR_V1_API_ENTRY(HwcFrameGetLayerCursor); -DVR_V1_API_ENTRY(HwcFrameGetLayerTransform); -DVR_V1_API_ENTRY(HwcFrameGetLayerDataspace); -DVR_V1_API_ENTRY(HwcFrameGetLayerColor); -DVR_V1_API_ENTRY(HwcFrameGetLayerNumVisibleRegions); -DVR_V1_API_ENTRY(HwcFrameGetLayerVisibleRegion); -DVR_V1_API_ENTRY(HwcFrameGetLayerNumDamagedRegions); -DVR_V1_API_ENTRY(HwcFrameGetLayerDamagedRegion); - -// New entries added at the end to allow the DVR platform library API -// to be updated before updating VrCore. - -// Virtual touchpad client -DVR_V1_API_ENTRY(VirtualTouchpadScroll); - -// Read the native display metrics from the hardware composer -DVR_V1_API_ENTRY(GetNativeDisplayMetrics); - -// Performance -DVR_V1_API_ENTRY(PerformanceSetSchedulerPolicy); - -// Pose client -DVR_V1_API_ENTRY(PoseClientSensorsEnable); - -// Read buffer queue -DVR_V1_API_ENTRY(ReadBufferQueueGetEventFd); - -// Create write buffer queue locally -DVR_V1_API_ENTRY(WriteBufferQueueCreate); - -// Gets an ANativeWindow from DvrWriteBufferQueue. -DVR_V1_API_ENTRY(WriteBufferQueueGetANativeWindow); - -// Dvr{Read,Write}BufferQueue API for asynchronous IPC. -DVR_V1_API_ENTRY(WriteBufferQueueGainBuffer); -DVR_V1_API_ENTRY(WriteBufferQueuePostBuffer); -DVR_V1_API_ENTRY(ReadBufferQueueAcquireBuffer); -DVR_V1_API_ENTRY(ReadBufferQueueReleaseBuffer); - -// Pose client -DVR_V1_API_ENTRY(PoseClientGetDataReader); -DVR_V1_API_ENTRY(PoseClientDataCapture); -DVR_V1_API_ENTRY(PoseClientDataReaderDestroy); - -// Tracking -DVR_V1_API_ENTRY(TrackingCameraCreate); -DVR_V1_API_ENTRY(TrackingCameraDestroy); -DVR_V1_API_ENTRY(TrackingCameraStart); -DVR_V1_API_ENTRY(TrackingCameraStop); - -DVR_V1_API_ENTRY(TrackingFeatureExtractorCreate); -DVR_V1_API_ENTRY(TrackingFeatureExtractorDestroy); -DVR_V1_API_ENTRY(TrackingFeatureExtractorStart); -DVR_V1_API_ENTRY(TrackingFeatureExtractorStop); -DVR_V1_API_ENTRY(TrackingFeatureExtractorProcessBuffer); - -DVR_V1_API_ENTRY(TrackingSensorsCreate); -DVR_V1_API_ENTRY(TrackingSensorsDestroy); -DVR_V1_API_ENTRY(TrackingSensorsStart); -DVR_V1_API_ENTRY(TrackingSensorsStop); diff --git a/libs/vr/libdvr/include/dvr/dvr_buffer.h b/libs/vr/libdvr/include/dvr/dvr_buffer.h deleted file mode 100644 index 4234844c0f..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_buffer.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef ANDROID_DVR_BUFFER_H_ -#define ANDROID_DVR_BUFFER_H_ - -#include -#include -#include -#include - -__BEGIN_DECLS - -typedef struct DvrWriteBuffer DvrWriteBuffer; -typedef struct DvrReadBuffer DvrReadBuffer; -typedef struct DvrBuffer DvrBuffer; -typedef struct AHardwareBuffer AHardwareBuffer; -struct native_handle; - -// Destroys the write buffer. -void dvrWriteBufferDestroy(DvrWriteBuffer* write_buffer); - -// Returns 1 if the given write buffer object contains a buffer, 0 otherwise. -int dvrWriteBufferIsValid(DvrWriteBuffer* write_buffer); - -// Returns the global BufferHub id of this buffer. -int dvrWriteBufferGetId(DvrWriteBuffer* write_buffer); - -// Returns an AHardwareBuffer for the underlying buffer. -// Caller must call AHardwareBuffer_release on hardware_buffer. -int dvrWriteBufferGetAHardwareBuffer(DvrWriteBuffer* write_buffer, - AHardwareBuffer** hardware_buffer); - -// Destroys the read buffer. -void dvrReadBufferDestroy(DvrReadBuffer* read_buffer); - -// Returns 1 if the given write buffer object contains a buffer, 0 otherwise. -int dvrReadBufferIsValid(DvrReadBuffer* read_buffer); - -// Returns the global BufferHub id of this buffer. -int dvrReadBufferGetId(DvrReadBuffer* read_buffer); - -// Returns an AHardwareBuffer for the underlying buffer. -// Caller must call AHardwareBuffer_release on hardware_buffer. -int dvrReadBufferGetAHardwareBuffer(DvrReadBuffer* read_buffer, - AHardwareBuffer** hardware_buffer); - -// Destroys the buffer. -void dvrBufferDestroy(DvrBuffer* buffer); - -// Gets an AHardwareBuffer from the buffer. -// Caller must call AHardwareBuffer_release on hardware_buffer. -int dvrBufferGetAHardwareBuffer(DvrBuffer* buffer, - AHardwareBuffer** hardware_buffer); - -// Retrieve the shared buffer layout version defined in dvr_shared_buffers.h. -int dvrBufferGlobalLayoutVersionGet(); - -__END_DECLS - -#endif // ANDROID_DVR_BUFFER_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_buffer_queue.h b/libs/vr/libdvr/include/dvr/dvr_buffer_queue.h deleted file mode 100644 index ac789daf3d..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_buffer_queue.h +++ /dev/null @@ -1,263 +0,0 @@ -#ifndef ANDROID_DVR_BUFFER_QUEUE_H_ -#define ANDROID_DVR_BUFFER_QUEUE_H_ - -#include - -#include - -__BEGIN_DECLS - -typedef struct ANativeWindow ANativeWindow; - -typedef struct DvrWriteBufferQueue DvrWriteBufferQueue; -typedef struct DvrReadBufferQueue DvrReadBufferQueue; - -// Creates a write buffer queue to be used locally. -// -// Note that this API is mostly for testing purpose. For now there is no -// mechanism to send a DvrWriteBufferQueue cross process. Use -// dvrSurfaceCreateWriteBufferQueue if cross-process buffer transport is -// intended. -// -// @param width The width of the buffers that this queue will produce. -// @param height The height of buffers that this queue will produce. -// @param format The format of the buffers that this queue will produce. This -// must be one of the AHARDWAREBUFFER_FORMAT_XXX enums. -// @param layer_count The number of layers of the buffers that this queue will -// produce. -// @param usage The usage of the buffers that this queue will produce. This -// must a combination of the AHARDWAREBUFFER_USAGE_XXX flags. -// @param capacity The number of buffer that this queue will allocate. Note that -// all buffers will be allocated on create. Currently, the number of buffers -// is the queue cannot be changed after creation though DVR API. However, -// ANativeWindow can choose to reallocate, attach, or detach buffers from -// a DvrWriteBufferQueue through Android platform logic. -// @param metadata_size The size of metadata in bytes. -// @param out_write_queue The pointer of a DvrWriteBufferQueue will be filled -// here if the method call succeeds. The metadata size must match -// the metadata size in dvrWriteBufferPost/dvrReadBufferAcquire. -// @return Zero on success, or negative error code. -int dvrWriteBufferQueueCreate(uint32_t width, uint32_t height, uint32_t format, - uint32_t layer_count, uint64_t usage, - size_t capacity, size_t metadata_size, - DvrWriteBufferQueue** out_write_queue); - -// Destroy a write buffer queue. -// -// @param write_queue The DvrWriteBufferQueue of interest. -void dvrWriteBufferQueueDestroy(DvrWriteBufferQueue* write_queue); - -// Get the total number of buffers in a write buffer queue. -// -// @param write_queue The DvrWriteBufferQueue of interest. -// @return The capacity on success; or negative error code. -ssize_t dvrWriteBufferQueueGetCapacity(DvrWriteBufferQueue* write_queue); - -// Get the system unique queue id of a write buffer queue. -// -// @param write_queue The DvrWriteBufferQueue of interest. -// @return Queue id on success; or negative error code. -int dvrWriteBufferQueueGetId(DvrWriteBufferQueue* write_queue); - -// Gets an ANativeWindow backed by the DvrWriteBufferQueue -// -// Can be casted to a Java Surface using ANativeWindow_toSurface NDK API. Note -// that the native window is lazily created at the first time |GetNativeWindow| -// is called, and the created ANativeWindow will be cached so that multiple -// calls to this method will return the same object. Also note that this method -// does not acquire an additional reference to the ANativeWindow returned, don't -// call ANativeWindow_release on it. -// -// @param write_queue The DvrWriteBufferQueue of interest. -// @param out_window The pointer of an ANativeWindow will be filled here if -// the method call succeeds. -// @return Zero on success; or -EINVAL if this DvrWriteBufferQueue does not -// support being used as an android Surface. -int dvrWriteBufferQueueGetANativeWindow(DvrWriteBufferQueue* write_queue, - ANativeWindow** out_window); - -// Create a read buffer queue from an existing write buffer queue. -// -// @param write_queue The DvrWriteBufferQueue of interest. -// @param out_read_queue The pointer of a DvrReadBufferQueue will be filled here -// if the method call succeeds. -// @return Zero on success, or negative error code. -int dvrWriteBufferQueueCreateReadQueue(DvrWriteBufferQueue* write_queue, - DvrReadBufferQueue** out_read_queue); - -// Gains a buffer to write into. -// -// @param write_queue The DvrWriteBufferQueue to gain buffer from. -// @param timeout Specifies the number of milliseconds that the method will -// block. Specifying a timeout of -1 causes it to block indefinitely, -// while specifying a timeout equal to zero cause it to return immediately, -// even if no buffers are available. -// @param out_buffer A targeting DvrWriteBuffer object to hold the output of the -// dequeue operation. -// @param out_meta A DvrNativeBufferMetadata object populated by the -// corresponding dvrReadBufferQueueReleaseBuffer API. -// @param out_fence_fd A sync fence fd defined in NDK's sync.h API, which -// signals the release of underlying buffer. The producer should wait until -// this fence clears before writing data into it. -// @return Zero on success, or negative error code. -int dvrWriteBufferQueueGainBuffer(DvrWriteBufferQueue* write_queue, int timeout, - DvrWriteBuffer** out_write_buffer, - DvrNativeBufferMetadata* out_meta, - int* out_fence_fd); - -// Posts a buffer and signals its readiness to be read from. -// -// @param write_queue The DvrWriteBufferQueue to post buffer into. -// @param write_buffer The buffer to be posted. -// @param meta The buffer metadata describing the buffer. -// @param ready_fence_fd A sync fence fd defined in NDK's sync.h API, which -// signals the readdiness of underlying buffer. When a valid fence gets -// passed in, the consumer will wait the fence to be ready before it starts -// to ready from the buffer. -// @return Zero on success, or negative error code. -int dvrWriteBufferQueuePostBuffer(DvrWriteBufferQueue* write_queue, - DvrWriteBuffer* write_buffer, - const DvrNativeBufferMetadata* meta, - int ready_fence_fd); - -// Overrides buffer dimension with new width and height. -// -// After the call successfully returns, each |dvrWriteBufferQueueDequeue| call -// will return buffer with newly assigned |width| and |height|. When necessary, -// old buffer will be removed from the buffer queue and replaced with new buffer -// matching the new buffer size. -// -// @param write_queue The DvrWriteBufferQueue of interest. -// @param width Desired width, cannot be Zero. -// @param height Desired height, cannot be Zero. -// @return Zero on success, or negative error code. -int dvrWriteBufferQueueResizeBuffer(DvrWriteBufferQueue* write_queue, - uint32_t width, uint32_t height); - -// Destroy a read buffer queue. -// -// @param read_queue The DvrReadBufferQueue of interest. -void dvrReadBufferQueueDestroy(DvrReadBufferQueue* read_queue); - -// Get the total number of buffers in a read buffer queue. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @return The capacity on success; or negative error code. -ssize_t dvrReadBufferQueueGetCapacity(DvrReadBufferQueue* read_queue); - -// Get the system unique queue id of a read buffer queue. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @return Queue id on success; or negative error code. -int dvrReadBufferQueueGetId(DvrReadBufferQueue* read_queue); - -// Get the event fd that signals when queue updates occur. -// -// Use ReadBufferQueueHandleEvents to trigger registered event callbacks. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @return Fd on success; or negative error code. -int dvrReadBufferQueueGetEventFd(DvrReadBufferQueue* read_queue); - -// Create a read buffer queue from an existing read buffer queue. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @param out_read_queue The pointer of a DvrReadBufferQueue will be filled here -// if the method call succeeds. -// @return Zero on success, or negative error code. -int dvrReadBufferQueueCreateReadQueue(DvrReadBufferQueue* read_queue, - DvrReadBufferQueue** out_read_queue); - -// Dequeues a buffer to read from. -// -// @param read_queue The DvrReadBufferQueue to acquire buffer from. -// @param timeout Specifies the number of milliseconds that the method will -// block. Specifying a timeout of -1 causes it to block indefinitely, -// while specifying a timeout equal to zero cause it to return immediately, -// even if no buffers are available. -// @param out_buffer A targeting DvrReadBuffer object to hold the output of the -// dequeue operation. Must be created by |dvrReadBufferCreateEmpty|. -// @param out_meta A DvrNativeBufferMetadata object populated by the -// corresponding dvrWriteBufferQueuePostBuffer API. -// @param out_fence_fd A sync fence fd defined in NDK's sync.h API, which -// signals the release of underlying buffer. The consumer should wait until -// this fence clears before reading data from it. -// @return Zero on success, or negative error code. -int dvrReadBufferQueueAcquireBuffer(DvrReadBufferQueue* read_queue, int timeout, - DvrReadBuffer** out_read_buffer, - DvrNativeBufferMetadata* out_meta, - int* out_fence_fd); - -// Releases a buffer and signals its readiness to be written into. -// -// @param read_queue The DvrReadBufferQueue to release buffer into. -// @param read_buffer The buffer to be released. -// @param meta The buffer metadata describing the buffer. -// @param release_fence_fd A sync fence fd defined in NDK's sync.h API, which -// signals the readdiness of underlying buffer. When a valid fence gets -// passed in, the producer will wait the fence to be ready before it starts -// to write into the buffer again. -// @return Zero on success, or negative error code. -int dvrReadBufferQueueReleaseBuffer(DvrReadBufferQueue* read_queue, - DvrReadBuffer* read_buffer, - const DvrNativeBufferMetadata* meta, - int release_fence_fd); - -// Callback function which will be called when a buffer is avaiable. -// -// Note that there is no guarantee of thread safety and on which thread the -// callback will be fired. -// -// @param context User provided opaque pointer. -typedef void (*DvrReadBufferQueueBufferAvailableCallback)(void* context); - -// Set buffer avaiable callback. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @param callback The callback function. Set this to NULL if caller no longer -// needs to listen to new buffer available events. -// @param context User provided opaque pointer, will be passed back during -// callback. The caller is responsible for ensuring the validity of the -// context through the life cycle of the DvrReadBufferQueue. -// @return Zero on success, or negative error code. -int dvrReadBufferQueueSetBufferAvailableCallback( - DvrReadBufferQueue* read_queue, - DvrReadBufferQueueBufferAvailableCallback callback, void* context); - -// Callback function which will be called when a buffer is about to be removed. -// -// Note that there is no guarantee of thread safety and on which thread the -// callback will be fired. -// -// @param buffer The buffer being removed. Once the callbacks returns, this -// buffer will be dereferenced from the buffer queue. If user has ever -// cached other DvrReadBuffer/AHardwareBuffer/EglImageKHR objects derived -// from this buffer, it's the user's responsibility to clean them up. -// Note that the ownership of the read buffer is not passed to this -// callback, so it should call dvrReadBufferDestroy on the buffer. -// @param context User provided opaque pointer. -typedef void (*DvrReadBufferQueueBufferRemovedCallback)(DvrReadBuffer* buffer, - void* context); - -// Set buffer removed callback. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @param callback The callback function. Set this to NULL if caller no longer -// needs to listen to buffer removed events. -// @param context User provided opaque pointer, will be passed back during -// callback. The caller is responsible for ensuring the validity of the -// context through the life cycle of the DvrReadBufferQueue. -// @return Zero on success, or negative error code. -int dvrReadBufferQueueSetBufferRemovedCallback( - DvrReadBufferQueue* read_queue, - DvrReadBufferQueueBufferRemovedCallback callback, void* context); - -// Handle all pending events on the read queue. -// -// @param read_queue The DvrReadBufferQueue of interest. -// @return Zero on success, or negative error code. -int dvrReadBufferQueueHandleEvents(DvrReadBufferQueue* read_queue); - -__END_DECLS - -#endif // ANDROID_DVR_BUFFER_QUEUE_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_config.h b/libs/vr/libdvr/include/dvr/dvr_config.h deleted file mode 100644 index 3d2c0668da..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_config.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef ANDROID_DVR_CONFIG_H -#define ANDROID_DVR_CONFIG_H - -// This header is shared by VrCore and Android and must be kept in sync. - -#include -#include - -__BEGIN_DECLS - -// This is a shared memory buffer for passing config data from VrCore to -// libvrflinger in SurfaceFlinger. -struct __attribute__((packed, aligned(16))) DvrConfig { - // Offset before vsync to submit frames to hardware composer. - int32_t frame_post_offset_ns{4000000}; - - // If the number of pending fences goes over this count at the point when we - // are about to submit a new frame to HWC, we will drop the frame. This - // should be a signal that the display driver has begun queuing frames. Note - // that with smart displays (with RAM), the fence is signaled earlier than - // the next vsync, at the point when the DMA to the display completes. - // Currently we use a smart display and the EDS timing coincides with zero - // pending fences, so this is 0. - int32_t allowed_pending_fence_count{0}; - - // New fields should always be added to the end for backwards compat. - - // Reserved padding to 16 bytes. - uint8_t pad[8]; -}; - -__END_DECLS - -#endif // ANDROID_DVR_CONFIG_H diff --git a/libs/vr/libdvr/include/dvr/dvr_configuration_data.h b/libs/vr/libdvr/include/dvr/dvr_configuration_data.h deleted file mode 100644 index 22a509f6eb..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_configuration_data.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef DVR_CONFIGURATION_DATA_H_ -#define DVR_CONFIGURATION_DATA_H_ - -#include -#include -#include -#include - -#include -#include - -__BEGIN_DECLS - -// Loads device configuration data of DVR_CONFIGURATION_DATA_*. -// @return 0 on success. Otherwise returns a negative error value. -int dvrConfigurationDataGet(int config_type, - uint8_t** data, size_t* data_size); - -// Destroy the configuration data returned from dvrGetConfigurationData. -void dvrConfigurationDataDestroy(uint8_t* data); - -__END_DECLS - -#endif // DVR_CONFIGURATION_DATA_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_deleter.h b/libs/vr/libdvr/include/dvr/dvr_deleter.h deleted file mode 100644 index fe59d1ffba..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_deleter.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef ANDROID_DVR_DELETER_H_ -#define ANDROID_DVR_DELETER_H_ - -#include - -#include - -// Header-only C++ helper to delete opaque DVR objects. - -__BEGIN_DECLS - -// Use forward declarations to avoid dependency on other headers. -typedef struct DvrBuffer DvrBuffer; -typedef struct DvrReadBuffer DvrReadBuffer; -typedef struct DvrWriteBuffer DvrWriteBuffer; -typedef struct DvrReadBufferQueue DvrReadBufferQueue; -typedef struct DvrWriteBufferQueue DvrWriteBufferQueue; -typedef struct DvrDisplayManager DvrDisplayManager; -typedef struct DvrSurfaceState DvrSurfaceState; -typedef struct DvrSurface DvrSurface; -typedef struct DvrHwcClient DvrHwcClient; -typedef struct DvrHwcFrame DvrHwcFrame; - -void dvrBufferDestroy(DvrBuffer* buffer); -void dvrReadBufferDestroy(DvrReadBuffer* read_buffer); -void dvrWriteBufferDestroy(DvrWriteBuffer* write_buffer); -void dvrReadBufferQueueDestroy(DvrReadBufferQueue* read_queue); -void dvrWriteBufferQueueDestroy(DvrWriteBufferQueue* write_queue); -void dvrDisplayManagerDestroy(DvrDisplayManager* client); -void dvrSurfaceStateDestroy(DvrSurfaceState* surface_state); -void dvrSurfaceDestroy(DvrSurface* surface); -void dvrHwcClientDestroy(DvrHwcClient* client); -void dvrHwcFrameDestroy(DvrHwcFrame* frame); - -__END_DECLS - -// Avoid errors if this header is included in C code. -#if defined(__cplusplus) - -namespace android { -namespace dvr { - -// Universal DVR object deleter. May be passed to smart pointer types to handle -// deletion of DVR API objects. -struct DvrObjectDeleter { - void operator()(DvrBuffer* p) { dvrBufferDestroy(p); } - void operator()(DvrReadBuffer* p) { dvrReadBufferDestroy(p); } - void operator()(DvrWriteBuffer* p) { dvrWriteBufferDestroy(p); } - void operator()(DvrReadBufferQueue* p) { dvrReadBufferQueueDestroy(p); } - void operator()(DvrWriteBufferQueue* p) { dvrWriteBufferQueueDestroy(p); } - void operator()(DvrDisplayManager* p) { dvrDisplayManagerDestroy(p); } - void operator()(DvrSurfaceState* p) { dvrSurfaceStateDestroy(p); } - void operator()(DvrSurface* p) { dvrSurfaceDestroy(p); } - void operator()(DvrHwcClient* p) { dvrHwcClientDestroy(p); } - void operator()(DvrHwcFrame* p) { dvrHwcFrameDestroy(p); } -}; - -// Helper to define unique pointers for DVR object types. -template -using MakeUniqueDvrPointer = std::unique_ptr; - -// Unique pointer types for DVR objects. -using UniqueDvrBuffer = MakeUniqueDvrPointer; -using UniqueDvrReadBuffer = MakeUniqueDvrPointer; -using UniqueDvrWriteBuffer = MakeUniqueDvrPointer; -using UniqueDvrReadBufferQueue = MakeUniqueDvrPointer; -using UniqueDvrWriteBufferQueue = MakeUniqueDvrPointer; -using UniqueDvrDisplayManager = MakeUniqueDvrPointer; -using UniqueDvrSurfaceState = MakeUniqueDvrPointer; -using UniqueDvrSurface = MakeUniqueDvrPointer; -using UniqueDvrHwcClient = MakeUniqueDvrPointer; -using UniqueDvrHwcFrame = MakeUniqueDvrPointer; - -// TODO(eieio): Add an adapter for std::shared_ptr that injects the deleter into -// the relevant constructors. - -} // namespace dvr -} // namespace android - -#endif // defined(__cplusplus) - -#endif // ANDROID_DVR_DELETER_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_display_manager.h b/libs/vr/libdvr/include/dvr/dvr_display_manager.h deleted file mode 100644 index f910d610f5..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_display_manager.h +++ /dev/null @@ -1,133 +0,0 @@ -#ifndef ANDROID_DVR_DISPLAY_MANAGER_H_ -#define ANDROID_DVR_DISPLAY_MANAGER_H_ - -#include -#include -#include -#include - -#include -#include - -__BEGIN_DECLS - -typedef struct DvrBuffer DvrBuffer; -typedef struct DvrDisplayManager DvrDisplayManager; -typedef struct DvrSurfaceState DvrSurfaceState; -typedef struct DvrReadBufferQueue DvrReadBufferQueue; - -typedef uint64_t DvrSurfaceUpdateFlags; - -// Attempts to connect to the display manager service. -// @return 0 on success. Otherwise returns a negative error value. -int dvrDisplayManagerCreate(DvrDisplayManager** client_out); - -// Destroys the display manager client object. -void dvrDisplayManagerDestroy(DvrDisplayManager* client); - -// Returns an fd used to signal when surface updates occur. Note that depending -// on the underlying transport, only a subset of the real event bits may be -// supported. Use dvrDisplayManagerClientTranslateEpollEventMask to get the real -// event flags. -// @return the fd on success. Otherwise returns a negative error value. -int dvrDisplayManagerGetEventFd(DvrDisplayManager* client); - -// @param in_events pass in the epoll revents that were initially returned by -// poll/epoll. -// @param on success, this value will be overwritten with the true poll/epoll -// values. -// @return 0 on success. Otherwise returns a negative error value. -int dvrDisplayManagerTranslateEpollEventMask(DvrDisplayManager* client, - int in_events, int* out_events); - -// Queries the display manager service for the current state of the display -// surfaces and stores the results in the given surface state object. -// @return 0 on success. Otherwise returns a negative error value. -int dvrDisplayManagerGetSurfaceState(DvrDisplayManager* client, - DvrSurfaceState* surface_state); - -// Gets a read buffer queue from the surface |surface_id| named |queue_id|. Each -// call returns a different read buffer queue connected to the same write buffer -// queue. Callers should cache these instead of requesting new ones when -// possible. -int dvrDisplayManagerGetReadBufferQueue(DvrDisplayManager* client, - int surface_id, int queue_id, - DvrReadBufferQueue** queue_out); - -// Creates a new surface state object. This object may be used to receive the -// results of a surface state query. More than one state object may be created -// to keep multiple snapshots, if desired. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateCreate(DvrSurfaceState** surface_state); - -// Destorys the surface state object. -void dvrSurfaceStateDestroy(DvrSurfaceState* surface_state); - -// Writes the number of surfaces described in the state object into |count_out|. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateGetSurfaceCount(DvrSurfaceState* surface_state, - size_t* count_out); - -// Returns the update flags for the surface at |surface_index| in the state -// object. The flags may be used to determine what changes, if any, occurred to -// the surface since the last state update. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateGetUpdateFlags(DvrSurfaceState* surface_state, - size_t surface_index, - DvrSurfaceUpdateFlags* flags_out); - -// Returns the unique identifier of surface at |surface_index| in the state -// object. The identifier may be used to distinguish between surfaces. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateGetSurfaceId(DvrSurfaceState* surface_state, - size_t surface_index, int* surface_id_out); - -// Returns the process id of surface at |surface_index| in the state object. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateGetProcessId(DvrSurfaceState* surface_state, - size_t surface_index, int* process_id_out); - -// Writes the number of queues in the surface at |surface_index| in the state -// object into |count_out|. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateGetQueueCount(DvrSurfaceState* surface_state, - size_t surface_index, size_t* count_out); - -// Returns up to |max_count| queue ids for the queues belonging to the surface -// at |surface_index| in the state object. -// @return The number of queue ids written on success. Otherwise returns a -// negative error value. -ssize_t dvrSurfaceStateGetQueueIds(DvrSurfaceState* surface_state, - size_t surface_index, int* queue_ids, - size_t max_count); - -// Writes the z-order of the surface at |surface_index| in surface state object -// into |z_order_out|. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceStateGetZOrder(DvrSurfaceState* surface_state, - size_t surface_index, int* z_order_out); - -// Writes the visible state of the surface at |surface_index| in the surface -// state object into |visible_out|. -// @return 0 on success. Otherwise it returns a negative error value. -int dvrSurfaceStateGetVisible(DvrSurfaceState* surface_state, - size_t surface_index, bool* visible_out); - -// Writes the number of attributes on the surface at |surface_index| in the -// state object into |count_out|. -// @return 0 on success. Otherwise it returns a negative error value. -int dvrSurfaceStateGetAttributeCount(DvrSurfaceState* surface_state, - size_t surface_index, size_t* count_out); - -// Writes the list of attribute key/value pairs for the surface at -// |surface_index| in the surface state object into |attributes|. -// @return The number of attributes written on success. Otherwise returns a -// negative error value. -ssize_t dvrSurfaceStateGetAttributes(DvrSurfaceState* surface_state, - size_t surface_index, - DvrSurfaceAttribute* attributes, - size_t max_count); - -__END_DECLS - -#endif // ANDROID_DVR_DISPLAY_MANAGER_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_display_types.h b/libs/vr/libdvr/include/dvr/dvr_display_types.h deleted file mode 100644 index fd69843292..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_display_types.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef ANDROID_DVR_DISPLAY_TYPES_H_ -#define ANDROID_DVR_DISPLAY_TYPES_H_ - -#include - -__BEGIN_DECLS - -// Define types used in pose buffer fields. These types have atomicity -// guarantees that are useful in lock-free shared memory ring buffers. -#ifdef __ARM_NEON -#include -#else -#ifndef __FLOAT32X4T_86 -#define __FLOAT32X4T_86 -typedef float float32x4_t __attribute__((__vector_size__(16))); -typedef struct float32x4x4_t { float32x4_t val[4]; } float32x4x4_t; -#endif -#endif - -// VrFlinger display manager surface state snapshots per surface flags -// indicating what changed since the last snapshot. -enum { - // No changes. - DVR_SURFACE_UPDATE_FLAGS_NONE = 0, - // This surface is new. - DVR_SURFACE_UPDATE_FLAGS_NEW_SURFACE = (1 << 0), - // Buffer queues added/removed. - DVR_SURFACE_UPDATE_FLAGS_BUFFERS_CHANGED = (1 << 1), - // Visibility/z-order changed. - DVR_SURFACE_UPDATE_FLAGS_VISIBILITY_CHANGED = (1 << 2), - // Generic attributes changed. - DVR_SURFACE_UPDATE_FLAGS_ATTRIBUTES_CHANGED = (1 << 3), -}; - -// Surface attribute keys. VrFlinger defines keys in the negative integer space. -// The compositor is free to use keys in the positive integer space for -// implementation-defined purposes. -enum { - // DIRECT: bool - // Determines whether a direct surface is created (compositor output) or an - // application surface. Defaults to false (application surface). May only be - // set to true by a process with either UID=root or UID validated with - // IsTrustedUid() (VrCore). - DVR_SURFACE_ATTRIBUTE_DIRECT = -3, - // Z_ORDER: int32_t - // Interpreted by VrFlinger only on direct surfaces to order the corresponding - // hardware layers. More positive values render on top of more negative - // values. - DVR_SURFACE_ATTRIBUTE_Z_ORDER = -2, - // VISIBLE: bool - // Interpreted by VrFlinger only on direct surfaces to determine whether a - // surface is assigned to a hardware layer or ignored. - DVR_SURFACE_ATTRIBUTE_VISIBLE = -1, - // INVALID - // Invalid key. No attributes should have this key. - DVR_SURFACE_ATTRIBUTE_INVALID = 0, - // FIRST_USER_KEY - // VrFlinger ingores any keys with this value or greater, passing them to the - // compositor through surface state query results. - DVR_SURFACE_ATTRIBUTE_FIRST_USER_KEY = 1, -}; - -__END_DECLS - -#endif // ANDROID_DVR_DISPLAY_TYPES_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_hardware_composer_client.h b/libs/vr/libdvr/include/dvr/dvr_hardware_composer_client.h deleted file mode 100644 index 0ba76e267d..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_hardware_composer_client.h +++ /dev/null @@ -1,199 +0,0 @@ -#ifndef ANDROID_DVR_HARDWARE_COMPOSER_CLIENT_H -#define ANDROID_DVR_HARDWARE_COMPOSER_CLIENT_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct AHardwareBuffer AHardwareBuffer; -typedef struct DvrHwcClient DvrHwcClient; -typedef struct DvrHwcFrame DvrHwcFrame; - -// Called when a new frame has arrived. -// -// @param client_state Pointer to client state passed in |dvrHwcCreateClient()|. -// @param frame New frame. Owned by the client. -// @return fence FD for the release of the last frame. -typedef int(*DvrHwcOnFrameCallback)(void* client_state, DvrHwcFrame* frame); - -// @param callback Called when a new frame is available. -// @param client_state Pointer to client state passed back in the callback. -DvrHwcClient* dvrHwcClientCreate(DvrHwcOnFrameCallback callback, - void* client_state); - -// Called to free the DvrHwcClient pointer. -void dvrHwcClientDestroy(DvrHwcClient* client); - -// Called to free the frame information. -// @param frame Pointer for the valid frame used for the query. -void dvrHwcFrameDestroy(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return Identifier for the display associated by the frame. -DvrHwcDisplay dvrHwcFrameGetDisplayId(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return width of the physical display associated with |frame|. This does not -// take into account any orientation changes. -int32_t dvrHwcFrameGetDisplayWidth(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return height of the physical display associated with |frame|. This does not -// take into account any orientation changes. -int32_t dvrHwcFrameGetDisplayHeight(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return True if the display has been removed. In this case the current frame -// does not contain any valid layers to display. It is a signal to clean up any -// display related state. -bool dvrHwcFrameGetDisplayRemoved(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return Number of layers in the frame. -size_t dvrHwcFrameGetLayerCount(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return The ID of the currently active display configuration. -uint32_t dvrHwcFrameGetActiveConfig(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return The ID of the current color mode. See HAL_COLOR_MODE_* for valid -// values. -uint32_t dvrHwcFrameGetColorMode(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @param out_matrix Output parameter for a float[16] array which will be filled -// with the color transform matrix. -// @param out_hint Output parameter which will contain the color transform hint. -// See HAL_COLOR_TRANSFORM_* for valid values. -void dvrHwcFrameGetColorTransform(DvrHwcFrame* frame, float* out_matrix, - int32_t* out_hint); - -// @param frame Pointer for the valid frame used for the query. -// @return The current power mode for the display. See HWC2_POWER_MODE_* for -// valid values. -uint32_t dvrHwcFrameGetPowerMode(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @return The current state of vsync. See HWC2_VSYNC_* for valid values. -uint32_t dvrHwcFrameGetVsyncEnabled(DvrHwcFrame* frame); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return A unique ID for the layer. -DvrHwcLayer dvrHwcFrameGetLayerId(DvrHwcFrame* frame, size_t layer_index); - -// Return the graphic buffer associated with the layer at |layer_index| in -// |frame|. -// -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return Graphic buffer. Caller owns the buffer and is responsible for freeing -// it. (see AHardwareBuffer_release()) -AHardwareBuffer* dvrHwcFrameGetLayerBuffer(DvrHwcFrame* frame, - size_t layer_index); - -// Returns the fence FD for the layer at index |layer_index| in |frame|. -// -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return Fence FD. Caller owns the FD and is responsible for closing it. -int dvrHwcFrameGetLayerFence(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return describing the portion of the display covered by the layer. Will -// not exceed the display dimensions. -DvrHwcRecti dvrHwcFrameGetLayerDisplayFrame(DvrHwcFrame* frame, - size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return describing the portion of the layer that will fill the display -// frame. Will not exceed the layer dimensions. -DvrHwcRectf dvrHwcFrameGetLayerCrop(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The blend mode of the layer. -DvrHwcBlendMode dvrHwcFrameGetLayerBlendMode(DvrHwcFrame* frame, - size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The alpha value to be applied to the whole layer. Will be in the -// [0.0, 1.0] range. -float dvrHwcFrameGetLayerAlpha(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The type of the layer assigned by the window manager. -uint32_t dvrHwcFrameGetLayerType(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The application id the layer belongs to. -uint32_t dvrHwcFrameGetLayerApplicationId(DvrHwcFrame* frame, - size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The z-order for the layer. -uint32_t dvrHwcFrameGetLayerZOrder(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @param out_x Output parameter for the x coordinate of the cursor location. -// @param out_y Output parameter for the y coordinate of the cursor location. -void dvrHwcFrameGetLayerCursor(DvrHwcFrame* frame, size_t layer_index, - int32_t* out_x, int32_t* out_y); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The transformation that needs to be applied to the layer before -// presenting it. See DVR_HWC_TRANSFORM_* for valid values. -uint32_t dvrHwcFrameGetLayerTransform(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The dataspace which represents how the pixel values should be -// interpreted. See HAL_DATASPACE_* for valid values. -uint32_t dvrHwcFrameGetLayerDataspace(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The color of the layer if layer composition is SOLID_COLOR. -uint32_t dvrHwcFrameGetLayerColor(DvrHwcFrame* frame, size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The number of visible regions. -uint32_t dvrHwcFrameGetLayerNumVisibleRegions(DvrHwcFrame* frame, - size_t layer_index); -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @param index The index of the visible region for the layer. -// @return The rectangle describing the visible region. -DvrHwcRecti dvrHwcFrameGetLayerVisibleRegion(DvrHwcFrame* frame, - size_t layer_index, size_t index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @return The number of damanged regions. -uint32_t dvrHwcFrameGetLayerNumDamagedRegions(DvrHwcFrame* frame, - size_t layer_index); - -// @param frame Pointer for the valid frame used for the query. -// @param layer_index The index of the layer in the frame. -// @param index The index of the damanged region for the layer. -// @return The rectangle describing the damaged region. -DvrHwcRecti dvrHwcFrameGetLayerDamagedRegion(DvrHwcFrame* frame, - size_t layer_index, size_t index); -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // ANDROID_DVR_HARDWARE_COMPOSER_CLIENT_H diff --git a/libs/vr/libdvr/include/dvr/dvr_hardware_composer_types.h b/libs/vr/libdvr/include/dvr/dvr_hardware_composer_types.h deleted file mode 100644 index 1d5eda614b..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_hardware_composer_types.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef ANDROID_VR_HARDWARE_COMPOSER_DEFS_H -#define ANDROID_VR_HARDWARE_COMPOSER_DEFS_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// NOTE: These definitions must match the ones in -// //hardware/libhardware/include/hardware/hwcomposer2.h. They are used by the -// client side which does not have access to hwc2 headers. -enum DvrHwcBlendMode { - DVR_HWC_BLEND_MODE_INVALID = 0, - DVR_HWC_BLEND_MODE_NONE = 1, - DVR_HWC_BLEND_MODE_PREMULTIPLIED = 2, - DVR_HWC_BLEND_MODE_COVERAGE = 3, -}; - -enum DvrHwcComposition { - DVR_HWC_COMPOSITION_INVALID = 0, - DVR_HWC_COMPOSITION_CLIENT = 1, - DVR_HWC_COMPOSITION_DEVICE = 2, - DVR_HWC_COMPOSITION_SOLID_COLOR = 3, - DVR_HWC_COMPOSITION_CURSOR = 4, - DVR_HWC_COMPOSITION_SIDEBAND = 5, -}; - -enum DvrHwcTransform { - DVR_HWC_TRANSFORM_NONE = 0, - DVR_HWC_TRANSFORM_FLIP_H = 1, - DVR_HWC_TRANSFORM_FLIP_V = 2, - DVR_HWC_TRANSFORM_ROT_90 = 4, - DVR_HWC_TRANSFORM_ROT_180 = 3, - DVR_HWC_TRANSFORM_ROT_270 = 7, -}; - -typedef uint64_t DvrHwcDisplay; -typedef uint64_t DvrHwcLayer; - -struct DvrHwcRecti { - int32_t left; - int32_t top; - int32_t right; - int32_t bottom; -}; - -struct DvrHwcRectf { - float left; - float top; - float right; - float bottom; -}; - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // ANDROID_DVR_HARDWARE_COMPOSER_DEFS_H diff --git a/libs/vr/libdvr/include/dvr/dvr_performance.h b/libs/vr/libdvr/include/dvr/dvr_performance.h deleted file mode 100644 index 5df35ad9d9..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_performance.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef ANDROID_DVR_PERFORMANCE_H_ -#define ANDROID_DVR_PERFORMANCE_H_ - -#include -#include - -__BEGIN_DECLS - -/// Sets the scheduler policy for a task. -/// -/// Sets the scheduler policy for a task to the class described by a semantic -/// string. -/// -/// Supported policies are device-specific. -/// -/// @param task_id The task id of task to set the policy for. When task_id is 0 -/// the current task id is substituted. -/// @param scheduler_policy NULL-terminated ASCII string containing the desired -/// scheduler policy. -/// @returns Returns 0 on success or a negative errno error code on error. -int dvrPerformanceSetSchedulerPolicy(pid_t task_id, const char* scheduler_policy); - -__END_DECLS - -#endif // ANDROID_DVR_PERFORMANCE_H_ - diff --git a/libs/vr/libdvr/include/dvr/dvr_pose.h b/libs/vr/libdvr/include/dvr/dvr_pose.h deleted file mode 100644 index 87527515b4..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_pose.h +++ /dev/null @@ -1,154 +0,0 @@ -#ifndef ANDROID_DVR_PUBLIC_POSE_H_ -#define ANDROID_DVR_PUBLIC_POSE_H_ - -#include -#include - -__BEGIN_DECLS - -#ifdef __ARM_NEON -#include -#else -#ifndef __FLOAT32X4T_86 -#define __FLOAT32X4T_86 -typedef float float32x4_t __attribute__((__vector_size__(16))); -#endif -#endif - -typedef struct DvrPoseClient DvrPoseClient; -typedef struct DvrReadBufferQueue DvrReadBufferQueue; - -// Represents an estimated pose, accessed asynchronously through a shared ring -// buffer. No assumptions should be made about the data in padding space. -// The size of this struct is 128 bytes. -typedef struct __attribute__((packed, aligned(16))) DvrPoseAsync { - // Left eye head-from-start orientation quaternion x,y,z,w. - float32x4_t orientation; - // Left eye head-from-start position x,y,z,pad in meters. - float32x4_t position; - // Right eye head-from-start orientation quaternion x,y,z,w. - float32x4_t right_orientation; - // Right eye head-from-start position x,y,z,pad in meters. - float32x4_t right_position; - // Start-space angular velocity x,y,z,pad in radians per second. - float32x4_t angular_velocity; - // Start-space positional velocity x,y,z,pad in meters per second. - float32x4_t velocity; - // Timestamp of when this pose is predicted for, typically halfway through - // scanout. - int64_t timestamp_ns; - // Bitmask of DVR_POSE_FLAG_* constants that apply to this pose. - // - // If DVR_POSE_FLAG_INVALID is set, the pose is indeterminate. - uint64_t flags; - // Reserved padding to 128 bytes. - uint8_t pad[16]; -} DvrPoseAsync; - -enum { - DVR_POSE_FLAG_INVALID = (1ULL << 0), // This pose is invalid. - DVR_POSE_FLAG_INITIALIZING = (1ULL << 1), // The pose delivered during - // initialization and it may not be - // correct. - DVR_POSE_FLAG_3DOF = - (1ULL << 2), // This pose is derived from 3Dof sensors. If - // this is not set, pose is derived using - // 3Dof and 6Dof sensors. - DVR_POSE_FLAG_FLOOR_HEIGHT_INVALID = - (1ULL << 3), // If set the floor height is invalid. - - // Bits that indicate the tracking system state. - DVR_POSE_FLAG_SERVICE_EXCEPTION = (1ULL << 32), - DVR_POSE_FLAG_FISHEYE_OVER_EXPOSED = (1ULL << 33), - DVR_POSE_FLAG_FISHEYE_UNDER_EXPOSED = (1ULL << 34), - DVR_POSE_FLAG_COLOR_OVER_EXPOSED = (1ULL << 35), - DVR_POSE_FLAG_COLOR_UNDER_EXPOSED = (1ULL << 36), - DVR_POSE_FLAG_TOO_FEW_FEATURES_TRACKED = (1ULL << 37) -}; - -// Represents a sensor pose sample. -typedef struct __attribute__((packed, aligned(16))) DvrPose { - // Head-from-start orientation quaternion x,y,z,w. - float32x4_t orientation; - - // The angular velocity where the x,y,z is the rotation axis and the - // magnitude is the radians / second in the same coordinate frame as - // orientation. - float32x4_t angular_velocity; - - // Head-from-start position x,y,z,pad in meters. - float32x4_t position; - - // In meters / second in the same coordinate frame as position. - float32x4_t velocity; - - // In meters / second ^ 2 in the same coordinate frame as position. - float32x4_t acceleration; - - // Timestamp for the measurement in nanoseconds. - int64_t timestamp_ns; - - // The combination of flags above. - uint64_t flags; - - // The current floor height. May be updated at a lower cadence than pose. - float floor_height; - - // Padding to 112 bytes so the size is a multiple of 16. - uint8_t padding[12]; -} DvrPose; - -// Represents a data type that can be streamed from pose service. -enum { - DVR_POSE_RAW_DATA_STEREO_IMAGE = (1ULL << 0), - DVR_POSE_RAW_DATA_POINT_CLOUD = (1ULL << 1), - DVR_POSE_RAW_DATA_FEATURES = (1ULL << 2), - - // Always last. - DVR_POSE_RAW_DATA_COUNT = (1ULL << 3), -}; - -// A request to retrieve data from the pose service. Expects that a buffer -// queue has been initialized through dvrPoseClientGetDataReader(). -typedef struct DvrPoseDataCaptureRequest { - // The type of data to capture. Refer to enum DVR_POSE_RAW_DATA_* for types. - uint64_t data_type; - // The sample interval. This can be used to skip samples. For example, a - // value of 5 will capture every fifth frame and discard the 4 frames in - // between. Set to 1 to capture all frames. - uint32_t sample_interval; - // The length of time to capture samples in milliseconds. Set to 0 to capture - // indefinitely. - uint32_t capture_time_ms; - // Reserved fields. - uint32_t reserved0; - uint32_t reserved1; - uint32_t reserved2; - uint32_t reserved3; - uint32_t reserved4; -} DvrPoseDataCaptureRequest; - -// Gets a read buffer queue for the data type |data_type|. Each call returns a -// different read buffer queue connected to the same write buffer queue. A -// separate write buffer queue exists for each |data_type|. -// -// PoseService supports a single consumer per write buffer queue. The consumer -// is expected to hold a single DvrReadBufferQueue at a time. Callers should -// cache these instead of requesting new ones when possible. If the consumer -// disconnects from the queue, it can regain a read buffer queue for the same -// producer by calling this function. -// -// For data_type DVR_POSE_RAW_DATA_STEREO_IMAGE, each buffer consists of two -// images formatted as a AHARDWAREBUFFER_FORMAT_BLOB, where height is 1 and -// width is the total size of both images. The size of an individual image can -// be found in the metadata struct DvrNativeBufferMetadata, where width is -// |crop_right| and height is |crop_bottom|/2. Each image is contiguous in -// memory with stride equal to width. -int dvrPoseClientGetDataReader(DvrPoseClient* client, uint64_t data_type, - DvrReadBufferQueue** queue_out); - -// TODO(b/65067592): Move pose api's from pose_client.h to here. - -__END_DECLS - -#endif // ANDROID_DVR_PUBLIC_POSE_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_shared_buffers.h b/libs/vr/libdvr/include/dvr/dvr_shared_buffers.h deleted file mode 100644 index 63c73855f4..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_shared_buffers.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef ANDROID_DVR_SHARED_BUFFERS_H_ -#define ANDROID_DVR_SHARED_BUFFERS_H_ - -#include -#include -#include -#include - -// This header is shared by VrCore and Android and must be kept in sync. -namespace android { -namespace dvr { - -// Increment when the layout for the buffers change. -enum : uint32_t { kSharedBufferLayoutVersion = 2 }; - -// Note: These buffers will be mapped from various system processes as well -// as VrCore and the application processes in a r/w manner. -// -// Therefore it is possible for the application to mess with the contents of -// these buffers. -// -// While using them, assume garbage memory: Your logic must not crash or lead -// to execution of unsafe code as a function of the contents of these buffers. - -// Sanity check for basic type sizes. -static_assert(sizeof(DvrPoseAsync) == 128, "Unexpected size for DvrPoseAsync"); -static_assert(sizeof(DvrPose) == 112, "Unexpected size for DvrPose"); -static_assert(sizeof(DvrVsync) == 32, "Unexpected size for DvrVsync"); -static_assert(sizeof(DvrConfig) == 16, "Unexpected size for DvrConfig"); - -// A helper class that provides compile time sized traits for the BroadcastRing. -template -class DvrRingBufferTraits { - public: - using Record = DvrType; - static constexpr bool kUseStaticRecordSize = false; - static constexpr uint32_t kStaticRecordCount = StaticCount; - static constexpr int kMaxReservedRecords = 1; - static constexpr int kMinAvailableRecords = 1; -}; - -// Traits classes. -using DvrPoseTraits = DvrRingBufferTraits; -using DvrVsyncTraits = DvrRingBufferTraits; -using DvrConfigTraits = DvrRingBufferTraits; - -// The broadcast ring classes that will expose the data. -using DvrPoseRing = BroadcastRing; -using DvrVsyncRing = BroadcastRing; -using DvrConfigRing = BroadcastRing; - -// This is a shared memory buffer for passing pose data estimated at vsyncs. -// -// This will be primarily used for late latching and EDS where we bind this -// buffer in a shader and extract the right vsync-predicted pose. -struct __attribute__((packed, aligned(16))) DvrVsyncPoseBuffer { - enum : int { - // The number vsync predicted poses to keep in the ring buffer. - // Must be a power of 2. - kSize = 8, - kIndexMask = kSize - 1, - - // The number of vsyncs (from the current vsync) we predict in vsync buffer. - // The other poses are left alone. - kMinFutureCount = 4 - }; - - // The vsync predicted poses. - // The pose for the vsync n is: - // vsync_poses[n % kSize] - // - // This buffer is unsynchronized: It is possible to get torn reads as the - // sensor service updates the predictions as new sensor measurements come - // in. In particular, it is possible to get the position and an updated - // orientation while reading. - DvrPoseAsync vsync_poses[kSize]; - - // The latest sensor pose for GPU usage. - DvrPose current_pose; - - // Current vsync_count (where sensord is writing poses from). - uint32_t vsync_count; - - // For 16 byte alignment. - uint8_t padding[12]; -}; - -static_assert(sizeof(DvrVsyncPoseBuffer) == 1152, - "Unexpected size for DvrVsyncPoseBuffer"); - -// The keys for the dvr global buffers. -enum DvrGlobalBuffers : int32_t { - kVsyncPoseBuffer = 1, - kVsyncBuffer = 2, - kSensorPoseBuffer = 3, - kVrFlingerConfigBufferKey = 4 -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_SHARED_BUFFERS_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_surface.h b/libs/vr/libdvr/include/dvr/dvr_surface.h deleted file mode 100644 index 74a68a16ee..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_surface.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef ANDROID_DVR_SURFACE_H_ -#define ANDROID_DVR_SURFACE_H_ - -#include -#include -#include -#include - -#include -#include -#include -#include - -__BEGIN_DECLS - -// Attribute types. The values are one-hot encoded to support singluar types or -// masks of supported types. -enum { - DVR_SURFACE_ATTRIBUTE_TYPE_NONE = 0, - DVR_SURFACE_ATTRIBUTE_TYPE_INT32 = (1 << 0), - DVR_SURFACE_ATTRIBUTE_TYPE_INT64 = (1 << 1), - DVR_SURFACE_ATTRIBUTE_TYPE_BOOL = (1 << 2), - DVR_SURFACE_ATTRIBUTE_TYPE_FLOAT = (1 << 3), - DVR_SURFACE_ATTRIBUTE_TYPE_FLOAT2 = (1 << 4), - DVR_SURFACE_ATTRIBUTE_TYPE_FLOAT3 = (1 << 5), - DVR_SURFACE_ATTRIBUTE_TYPE_FLOAT4 = (1 << 6), - DVR_SURFACE_ATTRIBUTE_TYPE_FLOAT8 = (1 << 7), - DVR_SURFACE_ATTRIBUTE_TYPE_FLOAT16 = (1 << 8), -}; - -typedef uint64_t DvrSurfaceAttributeType; -typedef int32_t DvrSurfaceAttributeKey; - -typedef struct DvrSurfaceAttributeValue { - DvrSurfaceAttributeType type; - union { - int32_t int32_value; - int64_t int64_value; - bool bool_value; - float float_value; - float float2_value[2]; - float float3_value[3]; - float float4_value[4]; - float float8_value[8]; - float float16_value[16]; - }; -} DvrSurfaceAttributeValue; - -typedef struct DvrSurfaceAttribute { - DvrSurfaceAttributeKey key; - DvrSurfaceAttributeValue value; -} DvrSurfaceAttribute; - -// Creates a new display surface with the given attributes. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceCreate(const DvrSurfaceAttribute* attributes, - size_t attribute_count, DvrSurface** surface_out); - -// Destroys the display surface. -void dvrSurfaceDestroy(DvrSurface* surface); - -// Gets the DisplayService global id for this surface. -int dvrSurfaceGetId(DvrSurface* surface); - -// Sets attributes on the given display surface. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceSetAttributes(DvrSurface* surface, - const DvrSurfaceAttribute* attributes, - size_t attribute_count); - -// Creates a new write-side buffer queue on the given surface. Direct surfaces -// may only have one queue, the latest call replacing any prior queue. Replaced -// queues are still referenced and should be destryoed using the queue destroy -// API. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSurfaceCreateWriteBufferQueue(DvrSurface* surface, uint32_t width, - uint32_t height, uint32_t format, - uint32_t layer_count, uint64_t usage, - size_t capacity, size_t metadata_size, - DvrWriteBufferQueue** queue_out); - -// Sets up a named buffer for shared memory data transfer between display -// clients and the system. Protected API that may only be called with sufficient -// privilege. -// @return 0 on success. Otherwise returns a negative error value. -int dvrSetupGlobalBuffer(DvrGlobalBufferKey key, size_t size, uint64_t usage, - DvrBuffer** buffer_out); - -// Deletes a named buffer. WARNING: This is dangerous because any existing -// clients of this buffer will not be notified and will remain attached to -// the old buffer. This is useful for tests, but probably not for production -// code. -// @return 0 on success. Otherwise returns a negative error value. -int dvrDeleteGlobalBuffer(DvrGlobalBufferKey key); - -// Get a global buffer from the display service. -// @return 0 on success. Otherwise returns a negative error value. -int dvrGetGlobalBuffer(DvrGlobalBufferKey key, DvrBuffer** out_buffer); - -// Read the native device display metrics as reported by the hardware composer. -// This is useful as otherwise the device metrics are only reported as -// relative to the current device orientation. -// @param sizeof_metrics the size of the passed in metrics struct. This is used -// to ensure we don't break each other during active development. -// @param metrics on success holds the retrieved device metrics. -// @return 0 on success. Otherwise returns a negative error value (typically -// this means the display service is not available). -int dvrGetNativeDisplayMetrics(size_t metrics_struct_size, - DvrNativeDisplayMetrics* metrics); - -__END_DECLS - -#endif // ANDROID_DVR_SURFACE_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_tracking.h b/libs/vr/libdvr/include/dvr/dvr_tracking.h deleted file mode 100644 index 5e388f391a..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_tracking.h +++ /dev/null @@ -1,185 +0,0 @@ -#ifndef ANDROID_DVR_TRACKING_H_ -#define ANDROID_DVR_TRACKING_H_ - -#include -#include - -#include - -__BEGIN_DECLS - -typedef struct DvrReadBuffer DvrReadBuffer; -typedef struct DvrTrackingCamera DvrTrackingCamera; -typedef struct DvrTrackingFeatureExtractor DvrTrackingFeatureExtractor; -typedef struct DvrTrackingSensors DvrTrackingSensors; -typedef struct DvrWriteBufferQueue DvrWriteBufferQueue; - -// The callback for DvrTrackingFeatureExtractor that will deliver the feature -// events. This callback is passed to dvrTrackingFeatureExtractorStart. -typedef void (*DvrTrackingFeatureCallback)(void* context, - const DvrTrackingFeatures* event); - -// The callback for DvrTrackingSensors session that will deliver the events. -// This callback is passed to dvrTrackingSensorsStart. -typedef void (*DvrTrackingSensorEventCallback)(void* context, - DvrTrackingSensorEvent* event); - -// Creates a DvrTrackingCamera session. -// -// On creation, the session is not in operating mode. Client code must call -// dvrTrackingCameraStart to bootstrap the underlying camera stack. -// -// There is no plan to expose camera configuration through this API. All camera -// parameters are determined by the system optimized for better tracking -// results. See b/78662281 for detailed deprecation plan of this API and the -// Stage 2 of VR tracking data source refactoring. -// -// @param out_camera The pointer of a DvrTrackingCamera will be filled here if -// the method call succeeds. -// @return Zero on success, or negative error code. -int dvrTrackingCameraCreate(DvrTrackingCamera** out_camera); - -// Destroys a DvrTrackingCamera handle. -// -// @param camera The DvrTrackingCamera of interest. -void dvrTrackingCameraDestroy(DvrTrackingCamera* camera); - -// Starts the DvrTrackingCamera. -// -// On successful return, all DvrReadBufferQueue's associated with the given -// write_queue will start to receive buffers from the camera stack. Note that -// clients of this API should not assume the buffer dimension, format, and/or -// usage of the outcoming buffers, as they are governed by the underlying camera -// logic. Also note that it's the client's responsibility to consume buffers -// from DvrReadBufferQueue on time and return them back to the producer; -// otherwise the camera stack might be blocked. -// -// @param camera The DvrTrackingCamera of interest. -// @param write_queue A DvrWriteBufferQueue that the camera stack can use to -// populate the buffer into. The queue must be empty and the camera stack -// will request buffer allocation with proper buffer dimension, format, and -// usage. Note that the write queue must be created with user_metadata_size -// set to sizeof(DvrTrackingBufferMetadata). On success, the write_queue -// handle will become invalid and the ownership of the queue handle will be -// transferred into the camera; otherwise, the write_queue handle will keep -// untouched and the caller still has the ownership. -// @return Zero on success, or negative error code. -int dvrTrackingCameraStart(DvrTrackingCamera* camera, - DvrWriteBufferQueue* write_queue); - -// Stops the DvrTrackingCamera. -// -// On successful return, the DvrWriteBufferQueue set during -// dvrTrackingCameraStart will stop getting new buffers from the camera stack. -// -// @param camera The DvrTrackingCamera of interest. -// @return Zero on success, or negative error code. -int dvrTrackingCameraStop(DvrTrackingCamera* camera); - -// Creates a DvrTrackingSensors session. -// -// This will initialize but not start device sensors (gyro / accel). Upon -// successfull creation, the clients can call dvrTrackingSensorsStart to start -// receiving sensor events. -// -// @param out_sensors The pointer of a DvrTrackingSensors will be filled here if -// the method call succeeds. -// @param mode The sensor mode. -// mode="ndk": Use the Android NDK. -// mode="direct": Use direct mode sensors (lower latency). -// @return Zero on success, or negative error code. -int dvrTrackingSensorsCreate(DvrTrackingSensors** out_sensors, - const char* mode); - -// Destroys a DvrTrackingSensors session. -// -// @param sensors The DvrTrackingSensors struct to destroy. -void dvrTrackingSensorsDestroy(DvrTrackingSensors* sensors); - -// Starts the tracking sensor session. -// -// This will start the device sensors and start pumping the feature and sensor -// events as they arrive. -// -// @param client A tracking client created by dvrTrackingSensorsCreate. -// @param context A client supplied pointer that will be passed to the callback. -// @param callback A callback that will receive the sensor events on an -// arbitrary thread. -// @return Zero on success, or negative error code. -int dvrTrackingSensorsStart(DvrTrackingSensors* sensors, - DvrTrackingSensorEventCallback callback, - void* context); - -// Stops a DvrTrackingSensors session. -// -// This will stop the device sensors. dvrTrackingSensorsStart can be called to -// restart them again. -// -// @param client A tracking client created by dvrTrackingClientCreate. -// @return Zero on success, or negative error code. -int dvrTrackingSensorsStop(DvrTrackingSensors* sensors); - -// Creates a tracking feature extractor. -// -// This will initialize but not start the feature extraction session. Upon -// successful creation, the client can call dvrTrackingFeatureExtractorStart to -// start receiving features. -// -// @param out_extractor The pointer of a DvrTrackingFeatureExtractor will be -// filled here if the method call succeeds. -int dvrTrackingFeatureExtractorCreate( - DvrTrackingFeatureExtractor** out_extractor); - -// Destroys a tracking feature extractor. -// -// @param extractor The DvrTrackingFeatureExtractor to destroy. -void dvrTrackingFeatureExtractorDestroy(DvrTrackingFeatureExtractor* extractor); - -// Starts the tracking feature extractor. -// -// This will start the extractor and start pumping the output feature events to -// the registered callback. Note that this method will create one or more -// threads to handle feature processing. -// -// @param extractor The DvrTrackingFeatureExtractor to destroy. -int dvrTrackingFeatureExtractorStart(DvrTrackingFeatureExtractor* extractor, - DvrTrackingFeatureCallback callback, - void* context); - -// Stops the tracking feature extractor. -// -// This will stop the extractor session and clean up all internal resourcse -// related to this extractor. On succssful return, all internal therad started -// by dvrTrackingFeatureExtractorStart should be stopped. -// -// @param extractor The DvrTrackingFeatureExtractor to destroy. -int dvrTrackingFeatureExtractorStop(DvrTrackingFeatureExtractor* extractor); - -// Processes one buffer to extract features from. -// -// The buffer will be sent over to DSP for feature extraction. Once the process -// is done, the processing thread will invoke DvrTrackingFeatureCallback with -// newly extracted features. Note that not all buffers will be processed, as the -// underlying DSP can only process buffers at a certain framerate. If a buffer -// needs to be skipped, out_skipped filed will be set to true. Also note that -// for successfully processed stereo buffer, two callbacks (one for each eye) -// will be fired. -// -// @param extractor The DvrTrackingFeatureExtractor to destroy. -// @param buffer The buffer to extract features from. Note that the buffer must -// be in acquired state for the buffer to be processed. Also note that the -// buffer will be released back to its producer on successful return of the -// method. -// @param metadata The metadata associated with the buffer. Should be populated -// by DvrTrackingCamera session as user defined metadata. -// @param out_skipped On successful return, the field will be set to true iff -// the buffer was skipped; and false iff the buffer was processed. This -// field is optional and nullptr can be passed here to ignore the field. -// @return Zero on success, or negative error code. -int dvrTrackingFeatureExtractorProcessBuffer( - DvrTrackingFeatureExtractor* extractor, DvrReadBuffer* buffer, - const DvrTrackingBufferMetadata* metadata, bool* out_skipped); - -__END_DECLS - -#endif // ANDROID_DVR_TRACKING_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_tracking_types.h b/libs/vr/libdvr/include/dvr/dvr_tracking_types.h deleted file mode 100644 index 81310d2303..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_tracking_types.h +++ /dev/null @@ -1,104 +0,0 @@ -#ifndef ANDROID_DVR_TRACKING_TYPES_H_ -#define ANDROID_DVR_TRACKING_TYPES_H_ - -#include -#include - -__BEGIN_DECLS - -typedef struct DvrTrackingBufferMetadata { - // Specifies the source of this image. - uint32_t camera_mask; - // Specifies the memory format of this image. - uint32_t format; - /// The width of the image data. - uint32_t width; - /// The height of the image data. - uint32_t height; - /// The number of bytes per scanline of image data. - uint32_t stride; - /// The frame number of this image. - int32_t frame_number; - /// The timestamp of this image in nanoseconds. Taken in the middle of the - /// exposure interval. - int64_t timestamp_ns; - // This is the timestamp for recording when the system using the HAL - // received the callback. It will not be populated by the HAL. - int64_t callback_timestamp_ns; - /// The exposure duration of this image in nanoseconds. - int64_t exposure_duration_ns; -} DvrTrackingBufferMetadata; - -// Represents a set of features extracted from a camera frame. Note that this -// should be in sync with TangoHalCallbacks defined in tango-hal.h. -typedef struct DvrTrackingFeatures { - // Specifies the source of the features. - uint32_t camera_mask; - - // This is unused. - uint32_t unused; - - // The timestamp in nanoseconds from the image that generated the features. - // Taken in the middle of the exposure interval. - int64_t timestamp_ns; - - // This is the timestamp for recording when the system using the HAL - // received the callback. It will not be populated by the HAL. - int64_t callback_timestamp_ns; - - // The frame number from the image that generated the features. - int64_t frame_number; - - // The number of features. - int count; - - // An array of 2D image points for each feature in the current image. - // This is sub-pixel refined extremum location at the fine resolution. - float (*positions)[2]; - - // The id of these measurements. - int32_t* ids; - - // The feature descriptors. - uint64_t (*descriptors)[8]; - - // Laplacian scores for each feature. - float* scores; - - // Is this feature a minimum or maximum in the Laplacian image. - // 0 if the feature is a maximum, 1 if it is a minimum. - int32_t* is_minimum; - - // This corresponds to the sub-pixel index of the laplacian image - // that the extremum was found. - float* scales; - - // Computed orientation of keypoint as part of FREAK extraction, except - // it's represented in radians and measured anti-clockwise. - float* angles; - - // Edge scores for each feature. - float* edge_scores; -} DvrTrackingFeatures; - -// Represents a sensor event. -typedef struct DvrTrackingSensorEvent { - // The sensor type. - int32_t sensor; - - // Event type. - int32_t type; - - // This is the timestamp recorded from the device. Taken in the middle - // of the integration interval and adjusted for any low pass filtering. - int64_t timestamp_ns; - - // The event data. - float x; - float y; - float z; -} DvrTrackingSensorEvent; - -__END_DECLS - -#endif // ANDROID_DVR_TRACKING_TYPES_H_ diff --git a/libs/vr/libdvr/include/dvr/dvr_vsync.h b/libs/vr/libdvr/include/dvr/dvr_vsync.h deleted file mode 100644 index 498bb5cc6e..0000000000 --- a/libs/vr/libdvr/include/dvr/dvr_vsync.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef ANDROID_DVR_VSYNC_H_ -#define ANDROID_DVR_VSYNC_H_ - -#include -#include - -__BEGIN_DECLS - -// Represents a vsync sample. The size of this struct is 32 bytes. -typedef struct __attribute__((packed, aligned(16))) DvrVsync { - // The timestamp for the last vsync in nanoseconds. - uint64_t vsync_timestamp_ns; - - // The index of the last vsync. - uint32_t vsync_count; - - // Scan out for the left eye = vsync_timestamp_ns + vsync_left_eye_offset_ns. - int32_t vsync_left_eye_offset_ns; - - // Scan out for the right eye = vsync_timestamp_ns + vsync_right_eye_offset_ns - int32_t vsync_right_eye_offset_ns; - - // The period of a vsync in nanoseconds. - uint32_t vsync_period_ns; - - // Padding to 32 bytes so the size is a multiple of 16. - uint8_t padding[8]; -} DvrVsync; - -__END_DECLS - -#endif // ANDROID_DVR_VSYNC_H_ diff --git a/libs/vr/libdvrcommon/Android.bp b/libs/vr/libdvrcommon/Android.bp deleted file mode 100644 index fe4dfc792a..0000000000 --- a/libs/vr/libdvrcommon/Android.bp +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (C) 2016 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 { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -localIncludeFiles = [ - "include", -] - -sharedLibraries = [ - "libbase", - "libcutils", - "liblog", - "libutils", - "libEGL", - "libGLESv2", - "libui", - "libgui", - "libhardware", - "libpdx_default_transport", -] - -staticLibraries = ["libbroadcastring"] - -headerLibraries = [ - "libeigen", -] - -cc_library { - local_include_dirs: localIncludeFiles, - - cflags: [ - "-DLOG_TAG=\"libdvrcommon\"", - "-DTRACE=0", - "-Wall", - "-Werror", - ], - export_include_dirs: localIncludeFiles, - - header_libs: headerLibraries, - export_header_lib_headers: headerLibraries, - - name: "libdvrcommon", -} - -testFiles = [ - "tests/numeric_test.cpp", - "tests/pose_test.cpp", -] - -cc_test { - name: "libdvrcommon_test", - - srcs: testFiles, - cflags: [ - "-Wall", - "-Werror", - "-Wno-unused-parameter", - ], - - shared_libs: sharedLibraries, - - static_libs: [ - "libgmock_main", - "libgmock", - "libgtest", - "libdvrcommon", - ] + staticLibraries, -} diff --git a/libs/vr/libdvrcommon/include/private/dvr/benchmark.h b/libs/vr/libdvrcommon/include/private/dvr/benchmark.h deleted file mode 100644 index 7eeab16030..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/benchmark.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef ANDROID_DVR_BENCHMARK_H_ -#define ANDROID_DVR_BENCHMARK_H_ - -#include -#include - -#include - -#include - -// Set benchmark traces, using Android systrace. -// -// The simplest one-parameter version of btrace automatically sets the -// timestamp with the system clock. The other versions can optionally set the -// timestamp manually, or pass additional data to be written to the log line. -// -// Example: -// Btrace("Start execution"); -// ... code to benchmark ... -// Btrace("End execution"); -// -// Use compute_benchmarks.py -// with the trace path "Start execution,End execution", -// to report the elapsed time between the two calls. -// -// Btrace will either output to standard atrace, or to a file if specified. -// The versions BtraceData also allow an int64_t to be included in the trace. - -// Btrace without data payload. -static inline void Btrace(const char* name, int64_t nanoseconds_monotonic); -static inline void Btrace(const char* name); -static inline void Btrace(FILE* file, const char* name, - int64_t nanoseconds_monotonic); -static inline void Btrace(FILE* file, const char* name); - -// Btrace with data payload. -static inline void BtraceData(const char* name, int64_t nanoseconds_monotonic, - int64_t data); -static inline void BtraceData(const char* name, int64_t data); -static inline void BtraceData(FILE* file, const char* name, - int64_t nanoseconds_monotonic, int64_t data); -static inline void BtraceData(FILE* file, const char* name, int64_t data); - -static inline void Btrace(const char* name, int64_t nanoseconds_monotonic) { - const int kLogMessageLength = 256; - char log_message[kLogMessageLength]; - snprintf(log_message, kLogMessageLength, "#btrace#%s", name); - atrace_int64(ATRACE_TAG_WEBVIEW, log_message, nanoseconds_monotonic); -} - -static inline void Btrace(const char* name) { - Btrace(name, android::dvr::GetSystemClockNs()); -} - -static inline void Btrace(FILE* file, const char* name, - int64_t nanoseconds_monotonic) { - fprintf(file, "#btrace#%s|%" PRId64 "\n", name, nanoseconds_monotonic); -} - -static inline void Btrace(FILE* file, const char* name) { - Btrace(file, name, android::dvr::GetSystemClockNs()); -} - -static inline void BtraceData(const char* name, int64_t nanoseconds_monotonic, - int64_t data) { - const int kLogMessageLength = 256; - char log_message[kLogMessageLength]; - snprintf(log_message, kLogMessageLength, "#btrace#%s|%" PRId64, name, data); - atrace_int64(ATRACE_TAG_WEBVIEW, log_message, nanoseconds_monotonic); -} - -static inline void BtraceData(const char* name, int64_t data) { - BtraceData(name, android::dvr::GetSystemClockNs(), data); -} - -static inline void BtraceData(FILE* file, const char* name, - int64_t nanoseconds_monotonic, int64_t data) { - fprintf(file, "#btrace#%s|%" PRId64 "|%" PRId64 "\n", name, data, - nanoseconds_monotonic); -} - -static inline void BtraceData(FILE* file, const char* name, int64_t data) { - BtraceData(file, name, android::dvr::GetSystemClockNs(), data); -} - -#endif // ANDROID_DVR_BENCHMARK_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/clock_ns.h b/libs/vr/libdvrcommon/include/private/dvr/clock_ns.h deleted file mode 100644 index 8e777edf6d..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/clock_ns.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef ANDROID_DVR_CLOCK_NS_H_ -#define ANDROID_DVR_CLOCK_NS_H_ - -#include -#include - -namespace android { -namespace dvr { - -constexpr int64_t kNanosPerSecond = 1000000000ll; - -// Returns the standard Dream OS monotonic system time that corresponds with all -// timestamps found in Dream OS APIs. -static inline timespec GetSystemClock() { - timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - return t; -} - -static inline timespec GetSystemClockRaw() { - timespec t; - clock_gettime(CLOCK_MONOTONIC_RAW, &t); - return t; -} - -static inline int64_t GetSystemClockNs() { - timespec t = GetSystemClock(); - int64_t ns = kNanosPerSecond * (int64_t)t.tv_sec + (int64_t)t.tv_nsec; - return ns; -} - -static inline int64_t GetSystemClockRawNs() { - timespec t = GetSystemClockRaw(); - int64_t ns = kNanosPerSecond * (int64_t)t.tv_sec + (int64_t)t.tv_nsec; - return ns; -} - -static inline double NsToSec(int64_t nanoseconds) { - return nanoseconds / static_cast(kNanosPerSecond); -} - -static inline double GetSystemClockSec() { return NsToSec(GetSystemClockNs()); } - -static inline double GetSystemClockMs() { return GetSystemClockSec() * 1000.0; } - -// Converts a nanosecond timestamp to a timespec. Based on the kernel function -// of the same name. -static inline timespec NsToTimespec(int64_t ns) { - timespec t; - int32_t remainder; - - t.tv_sec = ns / kNanosPerSecond; - remainder = ns % kNanosPerSecond; - if (remainder < 0) { - t.tv_nsec--; - remainder += kNanosPerSecond; - } - t.tv_nsec = remainder; - - return t; -} - -// Timestamp comparison functions that handle wrapping values correctly. -static inline bool TimestampLT(int64_t a, int64_t b) { - return static_cast(static_cast(a) - - static_cast(b)) < 0; -} -static inline bool TimestampLE(int64_t a, int64_t b) { - return static_cast(static_cast(a) - - static_cast(b)) <= 0; -} -static inline bool TimestampGT(int64_t a, int64_t b) { - return static_cast(static_cast(a) - - static_cast(b)) > 0; -} -static inline bool TimestampGE(int64_t a, int64_t b) { - return static_cast(static_cast(a) - - static_cast(b)) >= 0; -} - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_CLOCK_NS_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/debug.h b/libs/vr/libdvrcommon/include/private/dvr/debug.h deleted file mode 100644 index c31a385ffb..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/debug.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef ANDROID_DVR_DEBUG_H_ -#define ANDROID_DVR_DEBUG_H_ - -#include -#include - -#include - -#ifndef NDEBUG -#define CHECK_GL() \ - do { \ - const GLenum err = glGetError(); \ - if (err != GL_NO_ERROR) { \ - ALOGE("OpenGL error %d", err); \ - } \ - } while (0) - -#define CHECK_GL_FBO() \ - do { \ - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); \ - switch (status) { \ - case GL_FRAMEBUFFER_COMPLETE: \ - break; \ - case GL_FRAMEBUFFER_UNSUPPORTED: \ - ALOGE("GL_FRAMEBUFFER_UNSUPPORTED"); \ - break; \ - default: \ - ALOGE("FBO user error: %d", status); \ - break; \ - } \ - } while (0) -#else -#define CHECK_GL() -#define CHECK_GL_FBO() -#endif - -#endif // ANDROID_DVR_DEBUG_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/eigen.h b/libs/vr/libdvrcommon/include/private/dvr/eigen.h deleted file mode 100644 index defaf583c4..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/eigen.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef ANDROID_DVR_EIGEN_H_ -#define ANDROID_DVR_EIGEN_H_ - -#include -#include - -namespace Eigen { - -// Eigen doesn't take advantage of C++ template typedefs, but we can -template -using Vector = Matrix; - -template -using Vector2 = Vector; - -template -using Vector3 = Vector; - -template -using Vector4 = Vector; - -template -using RowVector = Matrix; - -template -using RowVector2 = RowVector; - -template -using RowVector3 = RowVector; - -template -using RowVector4 = RowVector; - -// In Eigen, the type you should be using for transformation matrices is the -// `Transform` class, instead of a raw `Matrix`. -// The `Projective` option means this will not make any assumptions about the -// last row of the object, making this suitable for use as general OpenGL -// projection matrices (which is the most common use-case). The one caveat -// is that in order to apply this transformation to non-homogeneous vectors -// (e.g., vec3), you must use the `.linear()` method to get the affine part of -// the matrix. -// -// Example: -// mat4 transform; -// vec3 position; -// vec3 transformed = transform.linear() * position; -// -// Note, the use of N-1 is because the parameter passed to Eigen is the ambient -// dimension of the transformation, not the size of the matrix iself. -// However graphics programmers sometimes get upset when they see a 3 next -// to a matrix when they expect a 4, so I'm hoping this will avoid that. -template -using AffineMatrix = Transform; - -} // namespace Eigen - -#endif // ANDROID_DVR_EIGEN_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/field_of_view.h b/libs/vr/libdvrcommon/include/private/dvr/field_of_view.h deleted file mode 100644 index d0ee69c770..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/field_of_view.h +++ /dev/null @@ -1,95 +0,0 @@ -#ifndef ANDROID_DVR_FIELD_OF_VIEW_H_ -#define ANDROID_DVR_FIELD_OF_VIEW_H_ - -#include - -#include - -namespace android { -namespace dvr { - -// Encapsulates a generalized, asymmetric field of view with four half angles. -// Each half angle denotes the angle between the corresponding frustum plane. -// Together with a near and far plane, a FieldOfView forms the frustum of an -// off-axis perspective projection. -class FieldOfView { - public: - // The default constructor sets an angle of 0 (in any unit) for all four - // half-angles. - FieldOfView() : left_(0.0f), right_(0.0f), bottom_(0.0f), top_(0.0f) {} - - // Constructs a FieldOfView from four angles. - FieldOfView(float left, float right, float bottom, float top) - : left_(left), right_(right), bottom_(bottom), top_(top) {} - - explicit FieldOfView(const float* fov) - : FieldOfView(fov[0], fov[1], fov[2], fov[3]) {} - - // Accessors for all four half-angles. - float GetLeft() const { return left_; } - float GetRight() const { return right_; } - float GetBottom() const { return bottom_; } - float GetTop() const { return top_; } - - // Setters for all four half-angles. - void SetLeft(float left) { left_ = left; } - void SetRight(float right) { right_ = right; } - void SetBottom(float bottom) { bottom_ = bottom; } - void SetTop(float top) { top_ = top; } - - Eigen::AffineMatrix GetProjectionMatrix(float z_near, - float z_far) const { - float x_left = -std::tan(left_) * z_near; - float x_right = std::tan(right_) * z_near; - float y_bottom = -std::tan(bottom_) * z_near; - float y_top = std::tan(top_) * z_near; - - float zero = 0.0f; - if (x_left == x_right || y_bottom == y_top || z_near == z_far || - z_near <= zero || z_far <= zero) { - return Eigen::AffineMatrix::Identity(); - } - - float x = (2 * z_near) / (x_right - x_left); - float y = (2 * z_near) / (y_top - y_bottom); - float a = (x_right + x_left) / (x_right - x_left); - float b = (y_top + y_bottom) / (y_top - y_bottom); - float c = (z_near + z_far) / (z_near - z_far); - float d = (2 * z_near * z_far) / (z_near - z_far); - - // Note: Eigen matrix initialization syntax is always 'column-major' - // even if the storage is row-major. Or in other words, just write the - // matrix like you'd see in a math textbook. - Eigen::AffineMatrix result; - result.matrix() << x, 0, a, 0, - 0, y, b, 0, - 0, 0, c, d, - 0, 0, -1, 0; - return result; - } - - static FieldOfView FromProjectionMatrix( - const Eigen::AffineMatrix& m) { - // Compute tangents. - float tan_vert_fov = 1.0f / m(1, 1); - float tan_horz_fov = 1.0f / m(0, 0); - float t = (m(1, 2) + 1.0f) * tan_vert_fov; - float b = (m(1, 2) - 1.0f) * tan_vert_fov; - float l = (m(0, 2) - 1.0f) * tan_horz_fov; - float r = (m(0, 2) + 1.0f) * tan_horz_fov; - - return FieldOfView(std::atan(-l), std::atan(r), std::atan(-b), - std::atan(t)); - } - - private: - float left_; - float right_; - float bottom_; - float top_; -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_FIELD_OF_VIEW_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/log_helpers.h b/libs/vr/libdvrcommon/include/private/dvr/log_helpers.h deleted file mode 100644 index 12ef622aaa..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/log_helpers.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef ANDROID_DVR_LOG_HELPERS_H_ -#define ANDROID_DVR_LOG_HELPERS_H_ - -#include -#include - -#include -#include - -namespace android { -namespace dvr { - -template -inline std::ostream& operator<<(std::ostream& out, - const Eigen::Vector& vec) { - return out << "vec2(" << vec.x() << ',' << vec.y() << ')'; -} - -template -inline std::ostream& operator<<(std::ostream& out, - const Eigen::Vector& vec) { - return out << "vec3(" << vec.x() << ',' << vec.y() << ',' << vec.z() << ')'; -} - -template -inline std::ostream& operator<<(std::ostream& out, - const Eigen::Vector& vec) { - return out << "vec4(" << vec.x() << ',' << vec.y() << ',' << vec.z() << ',' - << vec.w() << ')'; -} - -template -inline std::ostream& operator<<(std::ostream& out, - const Eigen::AffineMatrix& mat) { - out << std::setfill(' ') << std::setprecision(4) << std::fixed - << std::showpos; - out << "\nmat4["; - out << std::setw(10) << mat(0, 0) << " " << std::setw(10) << mat(0, 1) << " " - << std::setw(10) << mat(0, 2) << " " << std::setw(10) << mat(0, 3); - out << "]\n ["; - out << std::setw(10) << mat(1, 0) << " " << std::setw(10) << mat(1, 1) << " " - << std::setw(10) << mat(1, 2) << " " << std::setw(10) << mat(1, 3); - out << "]\n ["; - out << std::setw(10) << mat(2, 0) << " " << std::setw(10) << mat(2, 1) << " " - << std::setw(10) << mat(2, 2) << " " << std::setw(10) << mat(2, 3); - out << "]\n ["; - out << std::setw(10) << mat(3, 0) << " " << std::setw(10) << mat(3, 1) << " " - << std::setw(10) << mat(3, 2) << " " << std::setw(10) << mat(3, 3); - out << "]\n"; - - return out; -} - -inline std::ostream& operator<<(std::ostream& out, const FieldOfView& fov) { - return out << "fov(" << (fov.GetLeft() * 180.0f / M_PI) << ',' - << (fov.GetRight() * 180.0f / M_PI) << ',' - << (fov.GetBottom() * 180.0f / M_PI) << ',' - << (fov.GetTop() * 180.0f / M_PI) << ')'; -} - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_LOG_HELPERS_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/matrix_helpers.h b/libs/vr/libdvrcommon/include/private/dvr/matrix_helpers.h deleted file mode 100644 index aef7146e22..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/matrix_helpers.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef ANDROID_DVR_MATRIX_HELPERS_H_ -#define ANDROID_DVR_MATRIX_HELPERS_H_ - -#include -#include - -namespace android { -namespace dvr { - -// A helper function for creating a mat4 directly. -inline mat4 MakeMat4(float m00, float m01, float m02, float m03, float m10, - float m11, float m12, float m13, float m20, float m21, - float m22, float m23, float m30, float m31, float m32, - float m33) { - Eigen::Matrix4f matrix; - - matrix << m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, - m31, m32, m33; - - return mat4(matrix); -} - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_LOG_HELPERS_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/numeric.h b/libs/vr/libdvrcommon/include/private/dvr/numeric.h deleted file mode 100644 index 45458939c7..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/numeric.h +++ /dev/null @@ -1,175 +0,0 @@ -#ifndef ANDROID_DVR_NUMERIC_H_ -#define ANDROID_DVR_NUMERIC_H_ - -#include -#include -#include -#include - -#include -#include - -namespace android { -namespace dvr { - -template -static inline FT ToDeg(FT f) { - return f * static_cast(180.0 / M_PI); -} - -template -static inline FT ToRad(FT f) { - return f * static_cast(M_PI / 180.0); -} - -// Adjusts `x` to the periodic range `[lo, hi]` (to normalize angle values -// for example). -template -T NormalizePeriodicRange(T x, T lo, T hi) { - T range_size = hi - lo; - - while (x < lo) { - x += range_size; - } - - while (x > hi) { - x -= range_size; - } - - return x; -} - -// Normalizes a measurement in radians. -// @param x the angle to be normalized -// @param centre the point around which to normalize the range -// @return the value of x, normalized to the range [centre - 180, centre + 180] -template -T NormalizeDegrees(T x, T centre = static_cast(180.0)) { - return NormalizePeriodicRange(x, centre - static_cast(180.0), - centre + static_cast(180.0)); -} - -// Normalizes a measurement in radians. -// @param x the angle to be normalized -// @param centre the point around which to normalize the range -// @return the value of x, normalized to the range -// [centre - M_PI, centre + M_PI] -// @remark the centre parameter is to make it possible to specify a different -// periodic range. This is useful if you are planning on comparing two -// angles close to 0 or M_PI, so that one might not accidentally end -// up on the other side of the range -template -T NormalizeRadians(T x, T centre = static_cast(M_PI)) { - return NormalizePeriodicRange(x, centre - static_cast(M_PI), - centre + static_cast(M_PI)); -} - -static inline vec2i Round(const vec2& v) { - return vec2i(roundf(v.x()), roundf(v.y())); -} - -static inline vec2i Scale(const vec2i& v, float scale) { - return vec2i(roundf(static_cast(v.x()) * scale), - roundf(static_cast(v.y()) * scale)); -} - -// Re-maps `x` from `[lba,uba]` to `[lbb,ubb]`. -template -T ConvertRange(T x, T lba, T uba, T lbb, T ubb) { - return (((x - lba) * (ubb - lbb)) / (uba - lba)) + lbb; -} - -template -static inline vec2 MapPoint(const vec2& pt, const R1& from, const R2& to) { - vec2 normalized((pt - vec2(from.p1)).array() / vec2(from.GetSize()).array()); - return (normalized * vec2(to.GetSize())) + vec2(to.p1); -} - -template -inline bool IsZero(const T& v, - const T& tol = std::numeric_limits::epsilon()) { - return std::abs(v) <= tol; -} - -template -inline bool IsEqual(const T& a, const T& b, - const T& tol = std::numeric_limits::epsilon()) { - return std::abs(b - a) <= tol; -} - -template -T Square(const T& x) { - return x * x; -} - -template -T RandomInRange(T lo, T hi, - typename - std::enable_if::value>::type* = 0) { - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_real_distribution distro(lo, hi); - return distro(gen); -} - -template -T RandomInRange(T lo, T hi, - typename - std::enable_if::value>::type* = 0) { - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_int_distribution distro(lo, hi); - return distro(gen); -} - -template -Derived1 RandomInRange( - const Eigen::MatrixBase& lo, - const Eigen::MatrixBase& hi) { - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived1, Derived2); - - Derived1 result = Eigen::MatrixBase::Zero(); - - for (int row = 0; row < result.rows(); ++row) { - for (int col = 0; col < result.cols(); ++col) { - result(row, col) = RandomInRange(lo(row, col), hi(row, col)); - } - } - - return result; -} - -template -T RandomRange(T x) { - return RandomInRange(-x, x); -} - -template -T Clamp(T x, T lo, T hi) { - return std::min(std::max(x, lo), hi); -} - -inline mat3 ScaleMatrix(const vec2& scale_xy) { - return mat3(Eigen::Scaling(scale_xy[0], scale_xy[1], 1.0f)); -} - -inline mat3 TranslationMatrix(const vec2& translation) { - return mat3(Eigen::Translation2f(translation)); -} - -inline mat4 TranslationMatrix(const vec3& translation) { - return mat4(Eigen::Translation3f(translation)); -} - -inline vec2 TransformPoint(const mat3& m, const vec2& p) { - return m.linear() * p + m.translation(); -} - -inline vec2 TransformVector(const mat3& m, const vec2& p) { - return m.linear() * p; -} - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_NUMERIC_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/ortho.h b/libs/vr/libdvrcommon/include/private/dvr/ortho.h deleted file mode 100644 index fc0bce3792..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/ortho.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef ANDROID_DVR_ORTHO_H_ -#define ANDROID_DVR_ORTHO_H_ - -#include - -namespace android { -namespace dvr { - -template -Eigen::AffineMatrix OrthoMatrix(T left, T right, T bottom, T top, - T znear, T zfar) { - Eigen::AffineMatrix result; - const T t2 = static_cast(2); - const T a = t2 / (right - left); - const T b = t2 / (top - bottom); - const T c = t2 / (zfar - znear); - const T xoff = -(right + left) / (right - left); - const T yoff = -(top + bottom) / (top - bottom); - const T zoff = -(zfar + znear) / (zfar - znear); - const T t1 = static_cast(1); - result.matrix() << a, 0, 0, xoff, - 0, b, 0, yoff, - 0, 0, c, zoff, - 0, 0, 0, t1; - return result; -} - -} // namespace android -} // namespace dvr - -#endif // ANDROID_DVR_ORTHO_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/pose.h b/libs/vr/libdvrcommon/include/private/dvr/pose.h deleted file mode 100644 index 97944e8928..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/pose.h +++ /dev/null @@ -1,118 +0,0 @@ -#ifndef ANDROID_DVR_POSE_H_ -#define ANDROID_DVR_POSE_H_ - -#include - -namespace android { -namespace dvr { - -// Encapsulates a 3D pose (rotation and position). -// -// @tparam T Data type for storing the position coordinate and rotation -// quaternion. -template -class Pose { - public: - // Creates identity pose. - Pose() - : rotation_(Eigen::Quaternion::Identity()), - position_(Eigen::Vector3::Zero()) {} - - // Initializes a pose with given rotation and position. - // - // rotation Initial rotation. - // position Initial position. - Pose(Eigen::Quaternion rotation, Eigen::Vector3 position) - : rotation_(rotation), position_(position) {} - - void Invert() { - rotation_ = rotation_.inverse(); - position_ = rotation_ * -position_; - } - - Pose Inverse() const { - Pose result(*this); - result.Invert(); - return result; - } - - // Compute the composition of this pose with another, storing the result - // in the current object - void ComposeInPlace(const Pose& other) { - position_ = position_ + rotation_ * other.position_; - rotation_ = rotation_ * other.rotation_; - } - - // Computes the composition of this pose with another, and returns the result - Pose Compose(const Pose& other) const { - Pose result(*this); - result.ComposeInPlace(other); - return result; - } - - Eigen::Vector3 TransformPoint(const Eigen::Vector3& v) const { - return rotation_ * v + position_; - } - - Eigen::Vector3 Transform(const Eigen::Vector3& v) const { - return rotation_ * v; - } - - Pose& operator*=(const Pose& other) { - ComposeInPlace(other); - return *this; - } - - Pose operator*(const Pose& other) const { return Compose(other); } - - // Gets the rotation of the 3D pose. - Eigen::Quaternion GetRotation() const { return rotation_; } - - // Gets the position of the 3D pose. - Eigen::Vector3 GetPosition() const { return position_; } - - // Sets the rotation of the 3D pose. - void SetRotation(Eigen::Quaternion rotation) { rotation_ = rotation; } - - // Sets the position of the 3D pose. - void SetPosition(Eigen::Vector3 position) { position_ = position; } - - // Gets a 4x4 matrix representing a transform from the reference space (that - // the rotation and position of the pose are relative to) to the object space. - Eigen::AffineMatrix GetObjectFromReferenceMatrix() const; - - // Gets a 4x4 matrix representing a transform from the object space to the - // reference space (that the rotation and position of the pose are relative - // to). - Eigen::AffineMatrix GetReferenceFromObjectMatrix() const; - - private: - Eigen::Quaternion rotation_; - Eigen::Vector3 position_; -}; - -template -Eigen::AffineMatrix Pose::GetObjectFromReferenceMatrix() const { - // The transfrom from the reference is the inverse of the pose. - Eigen::AffineMatrix matrix(rotation_.inverse().toRotationMatrix()); - return matrix.translate(-position_); -} - -template -Eigen::AffineMatrix Pose::GetReferenceFromObjectMatrix() const { - // The transfrom to the reference. - Eigen::AffineMatrix matrix(rotation_.toRotationMatrix()); - return matrix.pretranslate(position_); -} - -//------------------------------------------------------------------------------ -// Type-specific typedefs. -//------------------------------------------------------------------------------ - -using Posef = Pose; -using Posed = Pose; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_POSE_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/range.h b/libs/vr/libdvrcommon/include/private/dvr/range.h deleted file mode 100644 index 1d06c96ec5..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/range.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef ANDROID_DVR_RANGE_H_ -#define ANDROID_DVR_RANGE_H_ - -#include - -namespace android { -namespace dvr { - -// TODO(skiazyk): Replace all instances of this with Eigen::AlignedBox - -// Container of two points that define a 2D range. -template -struct Range { - // Construct an uninitialized Range. - Range() {} - Range(Eigen::Vector p1, Eigen::Vector p2) : p1(p1), p2(p2) {} - - static Range FromSize(Eigen::Vector p1, - Eigen::Vector size) { - return Range(p1, p1 + size); - } - - bool operator==(const Range& rhs) const { - return p1 == rhs.p1 && p2 == rhs.p2; - } - - Eigen::Vector GetMinPoint() const { return p1; } - - Eigen::Vector GetMaxPoint() const { return p2; } - - Eigen::Vector GetSize() const { return p2 - p1; } - - Eigen::Vector p1; - Eigen::Vector p2; -}; - -typedef Range Range2i; -typedef Range Range2f; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_RANGE_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/ring_buffer.h b/libs/vr/libdvrcommon/include/private/dvr/ring_buffer.h deleted file mode 100644 index 18242411b9..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/ring_buffer.h +++ /dev/null @@ -1,99 +0,0 @@ -#ifndef ANDROID_DVR_RING_BUFFER_H_ -#define ANDROID_DVR_RING_BUFFER_H_ - -#include -#include - -namespace android { -namespace dvr { - -// A simple ring buffer implementation. -// -// A vector works but you either have to keep track of start_ and size_ yourself -// or erase() from the front which is inefficient. -// -// A deque works but the common usage pattern of Append() PopFront() Append() -// PopFront() looks like it allocates each time size goes from 0 --> 1, which we -// don't want. This class allocates only once. -template -class RingBuffer { - public: - RingBuffer() { Reset(0); } - - explicit RingBuffer(size_t capacity) { Reset(capacity); } - - RingBuffer(const RingBuffer& other) = default; - RingBuffer(RingBuffer&& other) noexcept = default; - RingBuffer& operator=(const RingBuffer& other) = default; - RingBuffer& operator=(RingBuffer&& other) noexcept = default; - - void Append(const T& val) { - if (IsFull()) - PopFront(); - Get(size_) = val; - size_++; - } - - void Append(T&& val) { - if (IsFull()) - PopFront(); - Get(size_) = std::move(val); - size_++; - } - - bool IsEmpty() const { return size_ == 0; } - - bool IsFull() const { return size_ == buffer_.size(); } - - size_t GetSize() const { return size_; } - - size_t GetCapacity() const { return buffer_.size(); } - - T& Get(size_t i) { return buffer_[(start_ + i) % buffer_.size()]; } - - const T& Get(size_t i) const { - return buffer_[(start_ + i) % buffer_.size()]; - } - - const T& Back() const { return Get(size_ - 1); } - - T& Back() { return Get(size_ - 1); } - - const T& Front() const { return Get(0); } - - T& Front() { return Get(0); } - - void PopBack() { - if (size_ != 0) { - Get(size_ - 1) = T(); - size_--; - } - } - - void PopFront() { - if (size_ != 0) { - Get(0) = T(); - start_ = (start_ + 1) % buffer_.size(); - size_--; - } - } - - void Clear() { Reset(GetCapacity()); } - - void Reset(size_t capacity) { - start_ = size_ = 0; - buffer_.clear(); - buffer_.resize(capacity); - } - - private: - // Ideally we'd allocate our own memory and use placement new to instantiate - // instances of T instead of using a vector, but the vector is simpler. - std::vector buffer_; - size_t start_, size_; -}; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_RING_BUFFER_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/test/test_macros.h b/libs/vr/libdvrcommon/include/private/dvr/test/test_macros.h deleted file mode 100644 index 6048652f92..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/test/test_macros.h +++ /dev/null @@ -1,124 +0,0 @@ -#ifndef LIBS_VR_LIBDVRCOMMON_INCLUDE_PRIVATE_DVR_TEST_TEST_MACROS_H_ -#define LIBS_VR_LIBDVRCOMMON_INCLUDE_PRIVATE_DVR_TEST_TEST_MACROS_H_ - -#include - -#include - -#include - -namespace android { -namespace dvr { - -template -::testing::AssertionResult CmpArrayLikeFloatEq( - const char* expectedStr, const char* actualStr, const char* toleranceStr, - const A& expected, const B& actual, const T& tolerance) { - for (int i = 0; i < N; ++i) { - if (!IsEqual(expected[i], actual[i], tolerance)) { - return ::testing::AssertionFailure() - << "\"" << expectedStr << "\" and \"" << actualStr - << "\" differ at element " << i << " by at least " << tolerance - << " : " - << " Expected \"" << expected[i] << "\", was \"" << actual[i] - << "\"."; - } - } - - return ::testing::AssertionSuccess(); -} - -template -::testing::AssertionResult CmpMatrixLikeFloatEq( - const char* expectedStr, const char* actualStr, const char* toleranceStr, - const A& expected, const B& actual, const T& tolerance) { - for (int r = 0; r < N; ++r) { - for (int c = 0; c < N; ++c) { - if (!IsEqual(expected(r, c), actual(r, c), tolerance)) { - return ::testing::AssertionFailure() - << "\"" << expectedStr << "\" and \"" << actualStr - << "\" differ at (" << r << "," << c << ")" - << " by at least " << tolerance << " : " - << " Expected \"" << expected(r, c) << "\", was \"" - << actual(r, c) << "\"."; - } - } - } - - return ::testing::AssertionSuccess(); -} - -template -::testing::AssertionResult CmpArrayLikeFloatNe( - const char* expectedStr, const char* actualStr, const char* toleranceStr, - const A& expected, const B& actual, const T& tolerance) { - for (int i = 0; i < N; ++i) { - if (!IsEqual(expected[i], actual[i], tolerance)) { - return ::testing::AssertionSuccess(); - } - } - - ::testing::Message message; - message << "Expected \"" << expectedStr - << "\" to differ from provided value \"" << actualStr - << "\" by at least " << tolerance << "."; - - return ::testing::AssertionFailure(message); -} - -template -::testing::AssertionResult CmpMatrixLikeFloatNe( - const char* expectedStr, const char* actualStr, const char* toleranceStr, - const A& expected, const B& actual, const T& tolerance) { - for (int r = 0; r < N; ++r) { - for (int c = 0; c < N; ++c) { - if (!IsEqual(expected(r, c), actual(r, c), tolerance)) { - return ::testing::AssertionSuccess(); - } - } - } - - ::testing::Message message; - message << "Expected \"" << expectedStr - << "\" to differ from provided value \"" << actualStr - << "\" by at least " << tolerance << "."; - - return ::testing::AssertionFailure(message); -} - -} // namespace dvr -} // namespace android - -#define EXPECT_VEC3_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpArrayLikeFloatEq<3>, expected, actual, \ - tol) - -#define EXPECT_VEC3_NOT_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpArrayLikeFloatNe<3>, expected, actual, \ - tol) - -#define EXPECT_QUAT_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpArrayLikeFloatEq<3>, expected.coeffs(), \ - actual.coeffs(), tol) - -#define EXPECT_QUAT_NOT_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpArrayLikeFloatNe<3>, expected.coeffs(), \ - actual.coeffs(), tol) - -#define EXPECT_MAT4_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpMatrixLikeFloatEq<4>, expected, actual, \ - tol) - -#define EXPECT_MAT4_NOT_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpMatrixLikeFloatNe<4>, expected, actual, \ - tol) - -#define EXPECT_MAT3_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr \ - : CmpMatrixLikeFloatEq<3>, expected, actual, tol) - -#define EXPECT_MAT3_NOT_NEAR(expected, actual, tol) \ - EXPECT_PRED_FORMAT3(android::dvr::CmpMatrixLikeFloatNe<3>, expected, actual, \ - tol) - -#endif // LIBS_VR_LIBDVRCOMMON_INCLUDE_PRIVATE_DVR_TEST_TEST_MACROS_H_ diff --git a/libs/vr/libdvrcommon/include/private/dvr/types.h b/libs/vr/libdvrcommon/include/private/dvr/types.h deleted file mode 100644 index 1fa54afe92..0000000000 --- a/libs/vr/libdvrcommon/include/private/dvr/types.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef ANDROID_DVR_TYPES_H_ -#define ANDROID_DVR_TYPES_H_ - -// All basic types used by VR code. - -#include -#include -#include -#include - -namespace android { -namespace dvr { - -enum RgbColorChannel { kRed, kGreen, kBlue }; - -// EyeType: 0 for left, 1 for right. -enum EyeType { kLeftEye = 0, kRightEye = 1 }; - -// In the context of VR, vector types are used as much as base types. - -using vec2f = Eigen::Vector2f; -using vec2d = Eigen::Vector2d; -using vec2i = Eigen::Vector2i; -using vec2 = vec2f; - -using vec3f = Eigen::Vector3f; -using vec3d = Eigen::Vector3d; -using vec3i = Eigen::Vector3i; -using vec3 = vec3f; - -using vec4f = Eigen::Vector4f; -using vec4d = Eigen::Vector4d; -using vec4i = Eigen::Vector4i; -using vec4 = vec4f; - -using mat3f = Eigen::AffineMatrix; -using mat3d = Eigen::AffineMatrix; -using mat3 = mat3f; - -using mat4f = Eigen::AffineMatrix; -using mat4d = Eigen::AffineMatrix; -using mat4 = mat4f; - -using quatf = Eigen::Quaternionf; -using quatd = Eigen::Quaterniond; -using quat = quatf; - -} // namespace dvr -} // namespace android - -#endif // ANDROID_DVR_TYPES_H_ diff --git a/libs/vr/libdvrcommon/tests/numeric_test.cpp b/libs/vr/libdvrcommon/tests/numeric_test.cpp deleted file mode 100644 index 1ee1447703..0000000000 --- a/libs/vr/libdvrcommon/tests/numeric_test.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include - -#include - -using TestTypes = ::testing::Types; - -using android::dvr::RandomInRange; - -template -class NumericTest : public ::testing::TestWithParam { - public: - using FT = T; -}; - -TYPED_TEST_CASE(NumericTest, TestTypes); - -TYPED_TEST(NumericTest, RandomInRange) { - using FT = typename TestFixture::FT; - - const int kNumTrials = 50; - const FT kLowRange = static_cast(-100); - const FT kHighRange = static_cast(100); - - for (int i = 0; i < kNumTrials; ++i) { - FT value = RandomInRange(kLowRange, kHighRange); - - EXPECT_LE(kLowRange, value); - EXPECT_GE(kHighRange, value); - } -} - -TEST(RandomInRange, TestIntVersion) { - // This checks specifically that the function does not always give the lo - // value (this was previously a bug) - - const int kNumTrials = 50; - const int kLowRange = -100; - const int kHighRange = 100; - - for (int i = 0; i < kNumTrials; ++i) { - int value = RandomInRange(kLowRange, kHighRange); - - if (value != kLowRange) { - SUCCEED(); - return; - } - } - - FAIL() << "Did not produce a value other than the range minimum for " - << "integers."; -} - -TEST(RandomInRange, TestVectorVersion) { - Eigen::Vector3d lo(-3.0, -4.0, -5.0); - Eigen::Vector3d hi(5.0, 4.0, 3.0); - - const int kNumTrials = 50; - - for (int i = 0; i < kNumTrials; ++i) { - Eigen::Vector3d result = RandomInRange(lo, hi); - - for (int j = 0; j < 3; ++j) { - EXPECT_LE(lo[j], result[j]); - EXPECT_GE(hi[j], result[j]); - } - } -} diff --git a/libs/vr/libdvrcommon/tests/pose_test.cpp b/libs/vr/libdvrcommon/tests/pose_test.cpp deleted file mode 100644 index aa1896da15..0000000000 --- a/libs/vr/libdvrcommon/tests/pose_test.cpp +++ /dev/null @@ -1,154 +0,0 @@ -#include - -#include -#include -#include - -using PoseTypes = ::testing::Types; - -template -class PoseTest : public ::testing::TestWithParam { - public: - using FT = T; - using Pose_t = android::dvr::Pose; - using quat_t = Eigen::Quaternion; - using vec3_t = Eigen::Vector3; - using mat4_t = Eigen::AffineMatrix; -}; - -TYPED_TEST_CASE(PoseTest, PoseTypes); - -// Check that the two matrix methods are inverses of each other -TYPED_TEST(PoseTest, SelfInverse) { - using quat_t = typename TestFixture::quat_t; - using vec3_t = typename TestFixture::vec3_t; - using Pose_t = typename TestFixture::Pose_t; - using mat4_t = typename TestFixture::mat4_t; - using FT = typename TestFixture::FT; - - const auto tolerance = FT(0.0001); - - const quat_t initial_rotation(Eigen::AngleAxis( - FT(M_PI / 3.0), vec3_t(FT(3.0), FT(4.0), FT(5.0)).normalized())); - const vec3_t initial_position = vec3_t(FT(2.0), FT(10.0), FT(-4.0)); - const Pose_t initial_pose(initial_rotation, initial_position); - - auto result_pose = initial_pose.GetReferenceFromObjectMatrix() * - initial_pose.GetObjectFromReferenceMatrix(); - - EXPECT_MAT4_NEAR(result_pose, mat4_t::Identity(), tolerance); -} - -TYPED_TEST(PoseTest, TransformPoint) { - using quat_t = typename TestFixture::quat_t; - using vec3_t = typename TestFixture::vec3_t; - using Pose_t = typename TestFixture::Pose_t; - using FT = typename TestFixture::FT; - - const auto tolerance = FT(0.0001); - - const quat_t pose_rotation( - Eigen::AngleAxis(FT(M_PI / 2.0), vec3_t(FT(0.0), FT(0.0), FT(1.0)))); - const auto pose_position = vec3_t(FT(1.0), FT(1.0), FT(2.0)); - - const Pose_t test_pose(pose_rotation, pose_position); - - for (int axis = 0; axis < 3; ++axis) { - vec3_t start_position = vec3_t::Zero(); - start_position[axis] = FT(1.0); - const vec3_t expected_transformed = - (pose_rotation * start_position) + pose_position; - const vec3_t actual_transformed = test_pose.TransformPoint(start_position); - EXPECT_VEC3_NEAR(expected_transformed, actual_transformed, tolerance); - } -} - -TYPED_TEST(PoseTest, TransformVector) { - using quat_t = typename TestFixture::quat_t; - using vec3_t = typename TestFixture::vec3_t; - using Pose_t = typename TestFixture::Pose_t; - using FT = typename TestFixture::FT; - - const auto tolerance = FT(0.0001); - - const quat_t pose_rotation(Eigen::AngleAxis( - FT(M_PI / 6.0), vec3_t(FT(3.0), FT(4.0), FT(5.0)).normalized())); - - const auto pose_position = vec3_t(FT(500.0), FT(-500.0), FT(300.0)); - - const Pose_t test_pose(pose_rotation, pose_position); - - for (int axis = 0; axis < 3; ++axis) { - vec3_t start_position = vec3_t::Zero(); - start_position[axis] = FT(1.0); - const vec3_t expected_rotated = pose_rotation * start_position; - const vec3_t actual_rotated = test_pose.Transform(start_position); - EXPECT_VEC3_NEAR(expected_rotated, actual_rotated, tolerance); - } -} - -TYPED_TEST(PoseTest, Composition) { - using quat_t = typename TestFixture::quat_t; - using Pose_t = typename TestFixture::Pose_t; - using vec3_t = typename TestFixture::vec3_t; - using FT = typename TestFixture::FT; - - const auto tolerance = FT(0.0001); - - const quat_t first_rotation( - Eigen::AngleAxis(FT(M_PI / 2.0), vec3_t(FT(0.0), FT(0.0), FT(1.0)))); - const auto first_offset = vec3_t(FT(-3.0), FT(2.0), FT(-1.0)); - const quat_t second_rotation(Eigen::AngleAxis( - FT(M_PI / 3.0), vec3_t(FT(1.0), FT(-1.0), FT(0.0)).normalized())); - const auto second_offset = vec3_t(FT(6.0), FT(-7.0), FT(-8.0)); - - const Pose_t first_pose(first_rotation, first_offset); - const Pose_t second_pose(second_rotation, second_offset); - - const auto combined_pose(second_pose.Compose(first_pose)); - - for (int axis = 0; axis < 3; ++axis) { - vec3_t start_position = vec3_t::Zero(); - start_position[axis] = FT(1.0); - const vec3_t expected_transformed = - second_pose.TransformPoint(first_pose.TransformPoint(start_position)); - const vec3_t actual_transformed = - combined_pose.TransformPoint(start_position); - EXPECT_VEC3_NEAR(expected_transformed, actual_transformed, tolerance); - } -} - -TYPED_TEST(PoseTest, Inverse) { - using quat_t = typename TestFixture::quat_t; - using vec3_t = typename TestFixture::vec3_t; - using Pose_t = typename TestFixture::Pose_t; - using FT = typename TestFixture::FT; - - const auto tolerance = FT(0.0001); - - const quat_t pose_rotation(Eigen::AngleAxis( - FT(M_PI / 2.0), vec3_t(FT(4.0), FT(-2.0), FT(-1.0)).normalized())); - const auto pose_position = vec3_t(FT(-1.0), FT(2.0), FT(-4.0)); - - Pose_t pose(pose_rotation, pose_position); - const Pose_t pose_inverse = pose.Inverse(); - - for (int axis = 0; axis < 3; ++axis) { - vec3_t start_position = vec3_t::Zero(); - start_position[axis] = FT(1.0); - const vec3_t transformed = pose.Transform(start_position); - const vec3_t inverted = pose_inverse.Transform(transformed); - EXPECT_VEC3_NEAR(start_position, inverted, tolerance); - } - - Pose_t nullified_pose[2] = { - pose.Compose(pose_inverse), pose_inverse.Compose(pose), - }; - - for (int i = 0; i < 2; ++i) { - EXPECT_QUAT_NEAR(quat_t::Identity(), nullified_pose[i].GetRotation(), - tolerance); - EXPECT_VEC3_NEAR(vec3_t::Zero(), nullified_pose[i].GetPosition(), - tolerance); - } -} diff --git a/libs/vr/libpdx/Android.bp b/libs/vr/libpdx/Android.bp deleted file mode 100644 index c95603bcf7..0000000000 --- a/libs/vr/libpdx/Android.bp +++ /dev/null @@ -1,85 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_library_headers { - name: "libpdx_headers", - export_include_dirs: ["private"], - vendor_available: true, - min_sdk_version: "29", -} - -cc_library_static { - name: "libpdx", - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-DLOG_TAG=\"libpdx\"", - "-DTRACE=0", - ], - header_libs: ["libpdx_headers"], - export_header_lib_headers: ["libpdx_headers"], - srcs: [ - "client.cpp", - "service.cpp", - "service_dispatcher.cpp", - "status.cpp", - ], - shared_libs: [ - "libbinder", - "libcutils", - "libutils", - "liblog", - ], -} - -cc_test { - name: "pdx_tests", - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - ], - srcs: [ - "client_tests.cpp", - "mock_tests.cpp", - "serialization_tests.cpp", - "service_tests.cpp", - "status_tests.cpp", - "thread_local_buffer_tests.cpp", - "variant_tests.cpp", - ], - static_libs: [ - "libcutils", - "libgmock", - "libpdx", - "liblog", - "libutils", - ], - shared_libs: [ - "libvndksupport", - ], -} - -// Code analysis target. -cc_test { - name: "pdx_encoder_performance_test", - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-O2", - ], - srcs: [ - "encoder_performance_test.cpp", - ], - static_libs: [ - "libpdx", - ], -} diff --git a/libs/vr/libpdx/client.cpp b/libs/vr/libpdx/client.cpp deleted file mode 100644 index 3c66a40a1b..0000000000 --- a/libs/vr/libpdx/client.cpp +++ /dev/null @@ -1,290 +0,0 @@ -#include "pdx/client.h" - -#include - -#include - -namespace android { -namespace pdx { - -void Client::EnableAutoReconnect(int64_t reconnect_timeout_ms) { - if (channel_factory_) { - reconnect_timeout_ms_ = reconnect_timeout_ms; - auto_reconnect_enabled_ = true; - } -} - -void Client::DisableAutoReconnect() { auto_reconnect_enabled_ = false; } - -bool Client::IsConnected() const { return channel_.get() != nullptr; } - -Status Client::CheckReconnect() { - Status ret; - bool was_disconnected = !IsConnected(); - if (auto_reconnect_enabled_ && was_disconnected && channel_factory_) { - auto status = channel_factory_->Connect(reconnect_timeout_ms_); - if (!status) { - error_ = -status.error(); - ret.SetError(status.error()); - return ret; - } - channel_ = status.take(); - } - - if (!IsConnected()) { - ret.SetError(ESHUTDOWN); - } else { - // Call the subclass OnConnect handler. The subclass may choose to close the - // connection in the handler, in which case error_ will be non-zero. - if (was_disconnected) - OnConnect(); - if (!IsConnected()) - ret.SetError(-error_); - else - ret.SetValue(); - } - - return ret; -} - -bool Client::NeedToDisconnectChannel(int error) const { - return error == ESHUTDOWN && auto_reconnect_enabled_; -} - -void Client::CheckDisconnect(int error) { - if (NeedToDisconnectChannel(error)) - Close(error); -} - -Client::Client(std::unique_ptr channel) - : channel_{std::move(channel)} {} - -Client::Client(std::unique_ptr channel_factory, - int64_t timeout_ms) - : channel_factory_{std::move(channel_factory)} { - auto status = channel_factory_->Connect(timeout_ms); - if (!status) { - ALOGE("Client::Client: Failed to connect to service because: %s", - status.GetErrorMessage().c_str()); - error_ = -status.error(); - } else { - channel_ = status.take(); - } -} - -bool Client::IsInitialized() const { - return IsConnected() || (channel_factory_ && auto_reconnect_enabled_); -} - -void Client::OnConnect() {} - -int Client::error() const { return error_; } - -Status Client::SendImpulse(int opcode) { - PDX_TRACE_NAME("Client::SendImpulse"); - - auto status = CheckReconnect(); - if (!status) - return status; - - status = channel_->SendImpulse(opcode, nullptr, 0); - CheckDisconnect(status); - return status; -} - -Status Client::SendImpulse(int opcode, const void* buffer, - size_t length) { - PDX_TRACE_NAME("Client::SendImpulse"); - - auto status = CheckReconnect(); - if (!status) - return status; - - status = channel_->SendImpulse(opcode, buffer, length); - CheckDisconnect(status); - return status; -} - -void Client::Close(int error) { - channel_.reset(); - // Normalize error codes to negative integer space. - error_ = error <= 0 ? error : -error; -} - -int Client::event_fd() const { - return IsConnected() ? channel_->event_fd() : -1; -} - -LocalChannelHandle& Client::GetChannelHandle() { - return channel_->GetChannelHandle(); -} - -const LocalChannelHandle& Client::GetChannelHandle() const { - return channel_->GetChannelHandle(); -} - -///////////////////////////// Transaction implementation ////////////////////// - -Transaction::Transaction(Client& client) : client_{client} {} - -Transaction::~Transaction() { - if (state_allocated_ && client_.GetChannel()) - client_.GetChannel()->FreeTransactionState(state_); -} - -bool Transaction::EnsureStateAllocated() { - if (!state_allocated_ && client_.GetChannel()) { - state_ = client_.GetChannel()->AllocateTransactionState(); - state_allocated_ = true; - } - return state_allocated_; -} - -void Transaction::SendTransaction(int opcode, Status* ret, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, - size_t receive_count) { - *ret = client_.CheckReconnect(); - if (!*ret) - return; - - if (!EnsureStateAllocated()) { - ret->SetError(ESHUTDOWN); - return; - } - - auto status = client_.GetChannel()->SendWithInt( - state_, opcode, send_vector, send_count, receive_vector, receive_count); - - if (status) { - ret->SetValue(); - } else { - ret->SetError(status.error()); - } - CheckDisconnect(status); -} - -void Transaction::SendTransaction(int opcode, Status* ret, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, - size_t receive_count) { - auto status = client_.CheckReconnect(); - if (!status) { - ret->SetError(status.error()); - return; - } - - if (!EnsureStateAllocated()) { - ret->SetError(ESHUTDOWN); - return; - } - - *ret = client_.GetChannel()->SendWithInt( - state_, opcode, send_vector, send_count, receive_vector, receive_count); - - CheckDisconnect(*ret); -} - -void Transaction::SendTransaction(int opcode, Status* ret, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, - size_t receive_count) { - auto status = client_.CheckReconnect(); - if (!status) { - ret->SetError(status.error()); - return; - } - - if (!EnsureStateAllocated()) { - ret->SetError(ESHUTDOWN); - return; - } - - *ret = client_.GetChannel()->SendWithFileHandle( - state_, opcode, send_vector, send_count, receive_vector, receive_count); - - CheckDisconnect(*ret); -} - -void Transaction::SendTransaction(int opcode, Status* ret, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, - size_t receive_count) { - auto status = client_.CheckReconnect(); - if (!status) { - ret->SetError(status.error()); - return; - } - - if (!EnsureStateAllocated()) { - ret->SetError(ESHUTDOWN); - return; - } - - *ret = client_.GetChannel()->SendWithChannelHandle( - state_, opcode, send_vector, send_count, receive_vector, receive_count); - - CheckDisconnect(*ret); -} - -Status Transaction::PushFileHandle(const LocalHandle& handle) { - if (client_.CheckReconnect() && EnsureStateAllocated()) - return client_.GetChannel()->PushFileHandle(state_, handle); - return ErrorStatus{ESHUTDOWN}; -} - -Status Transaction::PushFileHandle( - const BorrowedHandle& handle) { - if (client_.CheckReconnect() && EnsureStateAllocated()) - return client_.GetChannel()->PushFileHandle(state_, handle); - return ErrorStatus{ESHUTDOWN}; -} - -Status Transaction::PushFileHandle(const RemoteHandle& handle) { - return handle.Get(); -} - -Status Transaction::PushChannelHandle( - const LocalChannelHandle& handle) { - if (client_.CheckReconnect() && EnsureStateAllocated()) - return client_.GetChannel()->PushChannelHandle(state_, handle); - return ErrorStatus{ESHUTDOWN}; -} - -Status Transaction::PushChannelHandle( - const BorrowedChannelHandle& handle) { - if (client_.CheckReconnect() && EnsureStateAllocated()) - return client_.GetChannel()->PushChannelHandle(state_, handle); - return ErrorStatus{ESHUTDOWN}; -} - -Status Transaction::PushChannelHandle( - const RemoteChannelHandle& handle) { - return handle.value(); -} - -bool Transaction::GetFileHandle(FileReference ref, LocalHandle* handle) { - return client_.CheckReconnect() && EnsureStateAllocated() && - client_.GetChannel()->GetFileHandle(state_, ref, handle); -} - -bool Transaction::GetChannelHandle(ChannelReference ref, - LocalChannelHandle* handle) { - return client_.CheckReconnect() && EnsureStateAllocated() && - client_.GetChannel()->GetChannelHandle(state_, ref, handle); -} - -void Transaction::CheckDisconnect(int error) { - if (client_.NeedToDisconnectChannel(error)) { - if (state_allocated_) { - if (client_.GetChannel()) - client_.GetChannel()->FreeTransactionState(state_); - state_ = nullptr; - state_allocated_ = false; - } - client_.Close(error); - } -} - -} // namespace pdx -} // namespace android diff --git a/libs/vr/libpdx/client_tests.cpp b/libs/vr/libpdx/client_tests.cpp deleted file mode 100644 index 99ccc698c4..0000000000 --- a/libs/vr/libpdx/client_tests.cpp +++ /dev/null @@ -1,567 +0,0 @@ -#include - -#include -#include - -#include -#include -#include - -using android::pdx::BorrowedChannelHandle; -using android::pdx::BorrowedHandle; -using android::pdx::ClientBase; -using android::pdx::ClientChannel; -using android::pdx::ClientChannelFactory; -using android::pdx::ErrorStatus; -using android::pdx::LocalChannelHandle; -using android::pdx::LocalHandle; -using android::pdx::MockClientChannel; -using android::pdx::MockClientChannelFactory; -using android::pdx::RemoteChannelHandle; -using android::pdx::RemoteHandle; -using android::pdx::Status; -using android::pdx::Transaction; -using android::pdx::rpc::Void; - -using testing::A; -using testing::AnyNumber; -using testing::ByMove; -using testing::Invoke; -using testing::Ne; -using testing::Return; -using testing::_; - -namespace { - -inline void* IntToPtr(intptr_t addr) { return reinterpret_cast(addr); } -inline const void* IntToConstPtr(intptr_t addr) { - return reinterpret_cast(addr); -} - -struct TestInterface final { - // Op codes. - enum { - kOpAdd = 0, - kOpSendFile, - kOpGetFile, - kOpPushChannel, - }; - - // Methods. - PDX_REMOTE_METHOD(Add, kOpAdd, int(int, int)); - PDX_REMOTE_METHOD(SendFile, kOpSendFile, void(const LocalHandle& fd)); - PDX_REMOTE_METHOD(GetFile, kOpGetFile, LocalHandle(const std::string&, int)); - PDX_REMOTE_METHOD(PushChannel, kOpPushChannel, LocalChannelHandle(Void)); - - PDX_REMOTE_API(API, Add, SendFile, GetFile, PushChannel); -}; - -class SimpleClient : public ClientBase { - public: - explicit SimpleClient(std::unique_ptr channel) - : BASE{std::move(channel)} {} - SimpleClient(std::unique_ptr channel_factory, - int64_t timeout_ms) - : BASE{std::move(channel_factory), timeout_ms} { - EnableAutoReconnect(timeout_ms); - } - - using BASE::SendImpulse; - using BASE::InvokeRemoteMethod; - using BASE::InvokeRemoteMethodInPlace; - using BASE::Close; - using BASE::IsConnected; - using BASE::EnableAutoReconnect; - using BASE::DisableAutoReconnect; - using BASE::event_fd; - using BASE::GetChannel; - - MOCK_METHOD0(OnConnect, void()); -}; - -class FailingClient : public ClientBase { - public: - explicit FailingClient(std::unique_ptr channel, int error_code) - : BASE{std::move(channel)} { - Close(error_code); - } -}; - -class ClientChannelTest : public testing::Test { - public: - ClientChannelTest() - : client_{SimpleClient::Create( - std::make_unique>())} {} - - MockClientChannel* mock_channel() { - return static_cast(client_->GetChannel()); - } - - std::unique_ptr client_; -}; - -class ClientChannelFactoryTest : public testing::Test { - public: - ClientChannelFactoryTest() { - auto factory = - std::make_unique>(); - ON_CALL(*factory, Connect(kTimeout)) - .WillByDefault(Invoke(this, &ClientChannelFactoryTest::OnConnect)); - client_ = SimpleClient::Create(std::move(factory), kTimeout); - } - - MockClientChannel* mock_channel() { - return static_cast(client_->GetChannel()); - } - - Status> OnConnect(int64_t /*timeout_ms*/) { - if (on_connect_error_) - return ErrorStatus(on_connect_error_); - std::unique_ptr channel = - std::make_unique>(); - if (on_connect_callback_) - on_connect_callback_(channel.get()); - return Status>{std::move(channel)}; - } - - void OnConnectCallback(std::function callback) { - on_connect_callback_ = callback; - } - void SetOnConnectError(int error) { on_connect_error_ = error; } - void ResetOnConnectError() { on_connect_error_ = 0; } - - constexpr static int64_t kTimeout = 123; - std::unique_ptr client_; - std::function on_connect_callback_; - int on_connect_error_{0}; -}; - -constexpr int64_t ClientChannelFactoryTest::kTimeout; - -class ClientTransactionTest : public ClientChannelTest { - public: - ClientTransactionTest() : transaction_{*client_} {} - - Transaction transaction_; -}; - -} // anonymous namespace - -TEST_F(ClientChannelTest, IsInitialized) { - ASSERT_NE(client_.get(), nullptr); - EXPECT_TRUE(client_->IsInitialized()); - EXPECT_TRUE(client_->IsConnected()); -} - -TEST_F(ClientChannelTest, CloseOnConstruction) { - FailingClient failed_client1{std::make_unique(), EACCES}; - ASSERT_FALSE(failed_client1.IsInitialized()); - EXPECT_EQ(-EACCES, failed_client1.error()); - - FailingClient failed_client2{std::make_unique(), -EACCES}; - ASSERT_FALSE(failed_client2.IsInitialized()); - EXPECT_EQ(-EACCES, failed_client2.error()); - - auto failed_client3 = - FailingClient::Create(std::make_unique(), EIO); - ASSERT_EQ(failed_client3.get(), nullptr); -} - -TEST_F(ClientChannelTest, IsConnected) { - EXPECT_TRUE(client_->IsConnected()); - EXPECT_EQ(0, client_->error()); - client_->Close(-EINVAL); - EXPECT_FALSE(client_->IsConnected()); - EXPECT_EQ(-EINVAL, client_->error()); -} - -TEST_F(ClientChannelTest, event_fd) { - EXPECT_CALL(*mock_channel(), event_fd()).WillOnce(Return(12)); - EXPECT_EQ(12, client_->event_fd()); -} - -TEST_F(ClientChannelTest, SendImpulse) { - EXPECT_CALL(*mock_channel(), SendImpulse(123, nullptr, 0)) - .WillOnce(Return(Status{})); - EXPECT_TRUE(client_->SendImpulse(123)); - - EXPECT_CALL(*mock_channel(), SendImpulse(17, nullptr, 0)) - .WillOnce(Return(ErrorStatus{EIO})); - auto status = client_->SendImpulse(17); - ASSERT_FALSE(status); - EXPECT_EQ(EIO, status.error()); - - const void* const kTestPtr = IntToConstPtr(1234); - EXPECT_CALL(*mock_channel(), SendImpulse(1, kTestPtr, 17)) - .WillOnce(Return(Status{})); - EXPECT_TRUE(client_->SendImpulse(1, kTestPtr, 17)); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodNullTransactionState) { - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(nullptr)); - EXPECT_CALL(*mock_channel(), - SendWithInt(nullptr, TestInterface::kOpAdd, _, _, nullptr, 0)) - .WillOnce(Return(9)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(nullptr)); - EXPECT_TRUE(client_->InvokeRemoteMethod(4, 5)); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodAddSuccess) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL( - *mock_channel(), - SendWithInt(kTransactionState, TestInterface::kOpAdd, _, _, nullptr, 0)) - .WillOnce(Return(3)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - Status status = client_->InvokeRemoteMethod(1, 2); - ASSERT_TRUE(status); - EXPECT_EQ(3, status.get()); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodAddFailure) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL( - *mock_channel(), - SendWithInt(kTransactionState, TestInterface::kOpAdd, _, _, nullptr, 0)) - .WillOnce(Return(ErrorStatus{EIO})); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - Status status = client_->InvokeRemoteMethod(1, 2); - ASSERT_FALSE(status); - EXPECT_EQ(EIO, status.error()); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodGetFileSuccess) { - void* const kTransactionState = IntToPtr(123); - int fd = eventfd(0, 0); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), - SendWithFileHandle(kTransactionState, TestInterface::kOpGetFile, - _, _, nullptr, 0)) - .WillOnce(Return(ByMove(LocalHandle{fd}))); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - Status status = - client_->InvokeRemoteMethod(); - ASSERT_TRUE(status); - EXPECT_EQ(fd, status.get().Get()); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodGetFileFailure) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), - SendWithFileHandle(kTransactionState, TestInterface::kOpGetFile, - _, _, nullptr, 0)) - .WillOnce(Return(ByMove(ErrorStatus{EACCES}))); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - Status status = - client_->InvokeRemoteMethod("file", 0); - ASSERT_FALSE(status); - EXPECT_EQ(EACCES, status.error()); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodPushChannelSuccess) { - void* const kTransactionState = IntToPtr(123); - const int32_t kHandleValue = 17; - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL( - *mock_channel(), - SendWithChannelHandle(kTransactionState, TestInterface::kOpPushChannel, _, - _, nullptr, 0)) - .WillOnce(Return(ByMove(LocalChannelHandle{nullptr, kHandleValue}))); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - Status status = - client_->InvokeRemoteMethod(); - ASSERT_TRUE(status); - EXPECT_EQ(kHandleValue, status.get().value()); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodPushChannelFailure) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL( - *mock_channel(), - SendWithChannelHandle(kTransactionState, TestInterface::kOpPushChannel, _, - _, nullptr, 0)) - .WillOnce(Return(ByMove(ErrorStatus{EACCES}))); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - Status status = - client_->InvokeRemoteMethod(); - ASSERT_FALSE(status); - EXPECT_EQ(EACCES, status.error()); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodSendFileSuccess) { - void* const kTransactionState = IntToPtr(123); - LocalHandle fd{eventfd(0, 0)}; - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), - PushFileHandle(kTransactionState, A())) - .WillOnce(Return(1)); - EXPECT_CALL(*mock_channel(), - SendWithInt(kTransactionState, TestInterface::kOpSendFile, _, _, - nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - EXPECT_TRUE(client_->InvokeRemoteMethod(fd)); -} - -TEST_F(ClientChannelTest, InvokeRemoteMethodSendFileFailure) { - void* const kTransactionState = IntToPtr(123); - LocalHandle fd{eventfd(0, 0)}; - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), - PushFileHandle(kTransactionState, A())) - .WillOnce(Return(1)); - EXPECT_CALL(*mock_channel(), - SendWithInt(kTransactionState, TestInterface::kOpSendFile, _, _, - nullptr, 0)) - .WillOnce(Return(ErrorStatus{EACCES})); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - EXPECT_FALSE(client_->InvokeRemoteMethod(fd)); -} - -TEST_F(ClientChannelFactoryTest, IsInitialized) { - ASSERT_NE(client_.get(), nullptr); - EXPECT_TRUE(client_->IsInitialized()); - EXPECT_TRUE(client_->IsConnected()); -} - -TEST_F(ClientChannelFactoryTest, NotConnectedButInitialized) { - auto factory = - std::make_unique>(); - EXPECT_CALL(*factory, Connect(kTimeout)) - .WillOnce(Return(ByMove(ErrorStatus(ESHUTDOWN)))) - .WillOnce(Invoke(this, &ClientChannelFactoryTest::OnConnect)); - client_ = SimpleClient::Create(std::move(factory), kTimeout); - ASSERT_NE(client_.get(), nullptr); - EXPECT_TRUE(client_->IsInitialized()); - EXPECT_FALSE(client_->IsConnected()); - client_->DisableAutoReconnect(); - ASSERT_FALSE(client_->SendImpulse(17)); - EXPECT_FALSE(client_->IsConnected()); - client_->EnableAutoReconnect(kTimeout); - EXPECT_CALL(*client_, OnConnect()); - OnConnectCallback([](auto* mock) { - EXPECT_CALL(*mock, SendImpulse(17, nullptr, 0)) - .WillOnce(Return(Status{})); - }); - ASSERT_TRUE(client_->SendImpulse(17)); - EXPECT_TRUE(client_->IsConnected()); -} - -TEST_F(ClientChannelFactoryTest, CheckDisconnect) { - EXPECT_CALL(*mock_channel(), SendImpulse(17, nullptr, 0)) - .WillOnce(Return(ErrorStatus{ESHUTDOWN})); - ASSERT_FALSE(client_->SendImpulse(17)); - EXPECT_FALSE(client_->IsConnected()); - EXPECT_EQ(-ESHUTDOWN, client_->error()); -} - -TEST_F(ClientChannelFactoryTest, CheckReconnect) { - client_->Close(ESHUTDOWN); - ASSERT_FALSE(client_->IsConnected()); - - EXPECT_CALL(*client_, OnConnect()); - OnConnectCallback([](auto* mock) { - EXPECT_CALL(*mock, SendImpulse(17, nullptr, 0)) - .WillOnce(Return(Status{})); - }); - ASSERT_TRUE(client_->SendImpulse(17)); - EXPECT_TRUE(client_->IsConnected()); -} - -TEST_F(ClientChannelFactoryTest, CloseOnConnect) { - client_->Close(ESHUTDOWN); - - EXPECT_CALL(*client_, OnConnect()).WillOnce(Invoke([this] { - client_->Close(EIO); - })); - auto status = client_->SendImpulse(17); - ASSERT_FALSE(status); - EXPECT_EQ(EIO, status.error()); - EXPECT_FALSE(client_->IsConnected()); - EXPECT_EQ(-EIO, client_->error()); -} - -TEST_F(ClientChannelFactoryTest, DisableAutoReconnect) { - client_->Close(EIO); - ASSERT_FALSE(client_->IsConnected()); - client_->DisableAutoReconnect(); - auto status = client_->SendImpulse(17); - ASSERT_FALSE(status); - EXPECT_EQ(ESHUTDOWN, status.error()); - EXPECT_FALSE(client_->IsConnected()); - client_->EnableAutoReconnect(kTimeout); - EXPECT_CALL(*client_, OnConnect()); - OnConnectCallback([](auto* mock) { - EXPECT_CALL(*mock, SendImpulse(17, nullptr, 0)) - .WillOnce(Return(Status{})); - }); - ASSERT_TRUE(client_->SendImpulse(17)); - EXPECT_TRUE(client_->IsConnected()); -} - -TEST_F(ClientTransactionTest, SendNoData) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - EXPECT_CALL(*mock_channel(), - SendWithInt(kTransactionState, 1, nullptr, 0, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.Send(1)); - EXPECT_CALL(*mock_channel(), - SendWithFileHandle(kTransactionState, 2, nullptr, 0, nullptr, 0)) - .WillOnce(Return(ByMove(LocalHandle{-1}))); - EXPECT_TRUE(transaction_.Send(2)); - EXPECT_CALL(*mock_channel(), SendWithChannelHandle(kTransactionState, 3, - nullptr, 0, nullptr, 0)) - .WillOnce(Return(ByMove(LocalChannelHandle{nullptr, 1}))); - EXPECT_TRUE(transaction_.Send(3)); -} - -TEST_F(ClientTransactionTest, SendNoState) { - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(nullptr)); - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 1, nullptr, 0, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(nullptr)); - EXPECT_TRUE(transaction_.Send(1)); -} - -TEST_F(ClientTransactionTest, SendBuffers) { - const void* const kSendBuffer = IntToConstPtr(123); - const size_t kSendSize = 12; - void* const kReceiveBuffer = IntToPtr(456); - const size_t kReceiveSize = 34; - - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(nullptr)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(nullptr)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 1, nullptr, 0, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.Send(1, nullptr, 0, nullptr, 0)); - - EXPECT_CALL(*mock_channel(), - SendWithInt(nullptr, 2, Ne(nullptr), 1, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.Send(2, kSendBuffer, kSendSize, nullptr, 0)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 3, nullptr, 0, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.Send(3, kSendBuffer, 0, nullptr, 0)); - - EXPECT_CALL(*mock_channel(), - SendWithInt(nullptr, 4, nullptr, 0, Ne(nullptr), 1)) - .WillOnce(Return(0)); - EXPECT_TRUE( - transaction_.Send(4, nullptr, 0, kReceiveBuffer, kReceiveSize)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 5, nullptr, 0, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.Send(5, nullptr, 0, kReceiveBuffer, 0)); - - EXPECT_CALL(*mock_channel(), - SendWithInt(nullptr, 5, Ne(nullptr), 1, Ne(nullptr), 1)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.Send(5, kSendBuffer, kSendSize, kReceiveBuffer, - kReceiveSize)); -} - -TEST_F(ClientTransactionTest, SendVector) { - iovec send[3] = {}; - iovec recv[4] = {}; - - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(nullptr)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(nullptr)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 1, nullptr, 0, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.SendVector(1, nullptr, 0, nullptr, 0)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 2, send, 3, recv, 4)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.SendVector(2, send, 3, recv, 4)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 3, send, 3, nullptr, 0)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.SendVector(3, send, nullptr)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 4, nullptr, 0, recv, 4)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.SendVector(4, nullptr, recv)); - - EXPECT_CALL(*mock_channel(), SendWithInt(nullptr, 5, send, 3, recv, 4)) - .WillOnce(Return(0)); - EXPECT_TRUE(transaction_.SendVector(5, send, recv)); -} - -TEST_F(ClientTransactionTest, PushHandle) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - - EXPECT_CALL(*mock_channel(), - PushFileHandle(kTransactionState, A())) - .WillOnce(Return(1)); - EXPECT_EQ(1, transaction_.PushFileHandle(LocalHandle{-1}).get()); - - EXPECT_CALL(*mock_channel(), - PushFileHandle(kTransactionState, A())) - .WillOnce(Return(2)); - EXPECT_EQ(2, transaction_.PushFileHandle(BorrowedHandle{-1}).get()); - - EXPECT_EQ(3, transaction_.PushFileHandle(RemoteHandle{3}).get()); - - EXPECT_CALL( - *mock_channel(), - PushChannelHandle(kTransactionState, A())) - .WillOnce(Return(11)); - EXPECT_EQ( - 11, transaction_.PushChannelHandle(LocalChannelHandle{nullptr, 1}).get()); - - EXPECT_CALL( - *mock_channel(), - PushChannelHandle(kTransactionState, A())) - .WillOnce(Return(12)); - EXPECT_EQ(12, transaction_.PushChannelHandle(BorrowedChannelHandle{2}).get()); - - EXPECT_EQ(13, transaction_.PushChannelHandle(RemoteChannelHandle{13}).get()); -} - -TEST_F(ClientTransactionTest, GetHandle) { - void* const kTransactionState = IntToPtr(123); - EXPECT_CALL(*mock_channel(), AllocateTransactionState()) - .WillOnce(Return(kTransactionState)); - EXPECT_CALL(*mock_channel(), FreeTransactionState(kTransactionState)); - - EXPECT_CALL(*mock_channel(), GetFileHandle(kTransactionState, 1, _)) - .WillOnce(Return(false)) - .WillOnce(Return(true)); - - LocalHandle file_handle; - EXPECT_FALSE(transaction_.GetFileHandle(1, &file_handle)); - EXPECT_TRUE(transaction_.GetFileHandle(1, &file_handle)); - - EXPECT_CALL(*mock_channel(), GetChannelHandle(kTransactionState, 2, _)) - .WillOnce(Return(false)) - .WillOnce(Return(true)); - - LocalChannelHandle channel_handle; - EXPECT_FALSE(transaction_.GetChannelHandle(2, &channel_handle)); - EXPECT_TRUE(transaction_.GetChannelHandle(2, &channel_handle)); -} diff --git a/libs/vr/libpdx/encoder_performance_test.cpp b/libs/vr/libpdx/encoder_performance_test.cpp deleted file mode 100644 index 7b477c4ce2..0000000000 --- a/libs/vr/libpdx/encoder_performance_test.cpp +++ /dev/null @@ -1,515 +0,0 @@ -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -using namespace android::pdx::rpc; -using namespace android::pdx; -using std::placeholders::_1; -using std::placeholders::_2; -using std::placeholders::_3; -using std::placeholders::_4; -using std::placeholders::_5; -using std::placeholders::_6; - -namespace { - -constexpr size_t kMaxStaticBufferSize = 20480; - -// Provide numpunct facet that formats numbers with ',' as thousands separators. -class CommaNumPunct : public std::numpunct { - protected: - char do_thousands_sep() const override { return ','; } - std::string do_grouping() const override { return "\03"; } -}; - -class TestPayload : public MessagePayload, - public MessageWriter, - public MessageReader, - public NoOpResourceMapper { - public: - // MessageWriter - void* GetNextWriteBufferSection(size_t size) override { - const size_t section_offset = Size(); - Extend(size); - return Data() + section_offset; - } - - OutputResourceMapper* GetOutputResourceMapper() override { return this; } - - // MessageReader - BufferSection GetNextReadBufferSection() override { - return {&*ConstCursor(), &*ConstEnd()}; - } - - void ConsumeReadBufferSectionData(const void* new_start) override { - std::advance(ConstCursor(), PointerDistance(new_start, &*ConstCursor())); - } - - InputResourceMapper* GetInputResourceMapper() override { return this; } -}; - -class StaticBuffer : public MessageWriter, - public MessageReader, - public NoOpResourceMapper { - public: - void Clear() { - read_ptr_ = buffer_; - write_ptr_ = 0; - } - void Rewind() { read_ptr_ = buffer_; } - - // MessageWriter - void* GetNextWriteBufferSection(size_t size) override { - void* ptr = buffer_ + write_ptr_; - write_ptr_ += size; - return ptr; - } - - OutputResourceMapper* GetOutputResourceMapper() override { return this; } - - // MessageReader - BufferSection GetNextReadBufferSection() override { - return {read_ptr_, std::end(buffer_)}; - } - - void ConsumeReadBufferSectionData(const void* new_start) override { - read_ptr_ = static_cast(new_start); - } - - InputResourceMapper* GetInputResourceMapper() override { return this; } - - private: - uint8_t buffer_[kMaxStaticBufferSize]; - const uint8_t* read_ptr_{buffer_}; - size_t write_ptr_{0}; -}; - -// Simple callback function to clear/reset the input/output buffers for -// serialization. Using raw function pointer here instead of std::function to -// minimize the overhead of invocation in the tight test loop over millions of -// iterations. -using ResetFunc = void(void*); - -// Serialization test function signature, used by the TestRunner. -using SerializeTestSignature = std::chrono::nanoseconds(MessageWriter* writer, - size_t iterations, - ResetFunc* write_reset, - void* reset_data); - -// Deserialization test function signature, used by the TestRunner. -using DeserializeTestSignature = std::chrono::nanoseconds( - MessageReader* reader, MessageWriter* writer, size_t iterations, - ResetFunc* read_reset, ResetFunc* write_reset, void* reset_data); - -// Generic serialization test runner method. Takes the |value| of type T and -// serializes it into the output buffer represented by |writer|. -template -std::chrono::nanoseconds SerializeTestRunner(MessageWriter* writer, - size_t iterations, - ResetFunc* write_reset, - void* reset_data, const T& value) { - auto start = std::chrono::high_resolution_clock::now(); - for (size_t i = 0; i < iterations; i++) { - write_reset(reset_data); - Serialize(value, writer); - } - auto stop = std::chrono::high_resolution_clock::now(); - return stop - start; -} - -// Generic deserialization test runner method. Takes the |value| of type T and -// temporarily serializes it into the output buffer, then repeatedly -// deserializes the data back from that buffer. -template -std::chrono::nanoseconds DeserializeTestRunner( - MessageReader* reader, MessageWriter* writer, size_t iterations, - ResetFunc* read_reset, ResetFunc* write_reset, void* reset_data, - const T& value) { - write_reset(reset_data); - Serialize(value, writer); - T output_data; - auto start = std::chrono::high_resolution_clock::now(); - for (size_t i = 0; i < iterations; i++) { - read_reset(reset_data); - Deserialize(&output_data, reader); - } - auto stop = std::chrono::high_resolution_clock::now(); - if (output_data != value) - return start - stop; // Return negative value to indicate error. - return stop - start; -} - -// Special version of SerializeTestRunner that doesn't perform any serialization -// but does all the same setup steps and moves data of size |data_size| into -// the output buffer. Useful to determine the baseline to calculate time used -// just for serialization layer. -std::chrono::nanoseconds SerializeBaseTest(MessageWriter* writer, - size_t iterations, - ResetFunc* write_reset, - void* reset_data, size_t data_size) { - std::vector fake_data(data_size); - auto start = std::chrono::high_resolution_clock::now(); - for (size_t i = 0; i < iterations; i++) { - write_reset(reset_data); - memcpy(writer->GetNextWriteBufferSection(fake_data.size()), - fake_data.data(), fake_data.size()); - } - auto stop = std::chrono::high_resolution_clock::now(); - return stop - start; -} - -// Special version of DeserializeTestRunner that doesn't perform any -// deserialization but invokes Rewind on the input buffer repeatedly. -// Useful to determine the baseline to calculate time used just for -// deserialization layer. -std::chrono::nanoseconds DeserializeBaseTest( - MessageReader* reader, MessageWriter* writer, size_t iterations, - ResetFunc* read_reset, ResetFunc* write_reset, void* reset_data, - size_t data_size) { - std::vector fake_data(data_size); - write_reset(reset_data); - memcpy(writer->GetNextWriteBufferSection(fake_data.size()), fake_data.data(), - fake_data.size()); - auto start = std::chrono::high_resolution_clock::now(); - for (size_t i = 0; i < iterations; i++) { - read_reset(reset_data); - auto section = reader->GetNextReadBufferSection(); - memcpy(fake_data.data(), section.first, fake_data.size()); - reader->ConsumeReadBufferSectionData( - AdvancePointer(section.first, fake_data.size())); - } - auto stop = std::chrono::high_resolution_clock::now(); - return stop - start; -} - -// The main class that accumulates individual tests to be executed. -class TestRunner { - public: - struct BufferInfo { - BufferInfo(const std::string& buffer_name, MessageReader* reader, - MessageWriter* writer, ResetFunc* read_reset_func, - ResetFunc* write_reset_func, void* reset_data) - : name{buffer_name}, - reader{reader}, - writer{writer}, - read_reset_func{read_reset_func}, - write_reset_func{write_reset_func}, - reset_data{reset_data} {} - std::string name; - MessageReader* reader; - MessageWriter* writer; - ResetFunc* read_reset_func; - ResetFunc* write_reset_func; - void* reset_data; - }; - - void AddTestFunc(const std::string& name, - std::function serialize_test, - std::function deserialize_test, - size_t data_size) { - tests_.emplace_back(name, std::move(serialize_test), - std::move(deserialize_test), data_size); - } - - template - void AddSerializationTest(const std::string& name, T&& value) { - const size_t data_size = GetSerializedSize(value); - auto serialize_test = - std::bind(static_cast( - &SerializeTestRunner), - _1, _2, _3, _4, std::forward(value)); - tests_.emplace_back(name, std::move(serialize_test), - std::function{}, data_size); - } - - template - void AddDeserializationTest(const std::string& name, T&& value) { - const size_t data_size = GetSerializedSize(value); - auto deserialize_test = - std::bind(static_cast(&DeserializeTestRunner), - _1, _2, _3, _4, _5, _6, std::forward(value)); - tests_.emplace_back(name, std::function{}, - std::move(deserialize_test), data_size); - } - - template - void AddTest(const std::string& name, T&& value) { - const size_t data_size = GetSerializedSize(value); - if (data_size > kMaxStaticBufferSize) { - std::cerr << "Test '" << name << "' requires " << data_size - << " bytes in the serialization buffer but only " - << kMaxStaticBufferSize << " are available." << std::endl; - exit(1); - } - auto serialize_test = - std::bind(static_cast( - &SerializeTestRunner), - _1, _2, _3, _4, value); - auto deserialize_test = - std::bind(static_cast(&DeserializeTestRunner), - _1, _2, _3, _4, _5, _6, std::forward(value)); - tests_.emplace_back(name, std::move(serialize_test), - std::move(deserialize_test), data_size); - } - - std::string CenterString(std::string text, size_t column_width) { - if (text.size() < column_width) { - text = std::string((column_width - text.size()) / 2, ' ') + text; - } - return text; - } - - void RunTests(size_t iteration_count, - const std::vector& buffers) { - using float_seconds = std::chrono::duration; - const std::string name_column_separator = " : "; - const std::string buffer_column_separator = " || "; - const std::string buffer_timing_column_separator = " | "; - const size_t data_size_column_width = 6; - const size_t time_column_width = 9; - const size_t qps_column_width = 18; - const size_t buffer_column_width = time_column_width + - buffer_timing_column_separator.size() + - qps_column_width; - - auto compare_name_length = [](const TestEntry& t1, const TestEntry& t2) { - return t1.name.size() < t2.name.size(); - }; - auto test_with_longest_name = - std::max_element(tests_.begin(), tests_.end(), compare_name_length); - size_t name_column_width = test_with_longest_name->name.size(); - - size_t total_width = - name_column_width + name_column_separator.size() + - data_size_column_width + buffer_column_separator.size() + - buffers.size() * (buffer_column_width + buffer_column_separator.size()); - - const std::string dbl_separator(total_width, '='); - const std::string separator(total_width, '-'); - - auto print_header = [&](const std::string& header) { - std::cout << dbl_separator << std::endl; - std::stringstream ss; - ss.imbue(std::locale(ss.getloc(), new CommaNumPunct)); - ss << header << " (" << iteration_count << " iterations)"; - std::cout << CenterString(ss.str(), total_width) << std::endl; - std::cout << dbl_separator << std::endl; - std::cout << std::setw(name_column_width) << "Test Name" << std::left - << name_column_separator << std::setw(data_size_column_width) - << CenterString("Size", data_size_column_width) - << buffer_column_separator; - for (const auto& buffer_info : buffers) { - std::cout << std::setw(buffer_column_width) - << CenterString(buffer_info.name, buffer_column_width) - << buffer_column_separator; - } - std::cout << std::endl; - std::cout << std::setw(name_column_width) << "" << name_column_separator - << std::setw(data_size_column_width) - << CenterString("bytes", data_size_column_width) - << buffer_column_separator << std::left; - for (size_t i = 0; i < buffers.size(); i++) { - std::cout << std::setw(time_column_width) - << CenterString("Time, s", time_column_width) - << buffer_timing_column_separator - << std::setw(qps_column_width) - << CenterString("QPS", qps_column_width) - << buffer_column_separator; - } - std::cout << std::right << std::endl; - std::cout << separator << std::endl; - }; - - print_header("Serialization benchmarks"); - for (const auto& test : tests_) { - if (test.serialize_test) { - std::cout << std::setw(name_column_width) << test.name << " : " - << std::setw(data_size_column_width) << test.data_size - << buffer_column_separator; - for (const auto& buffer_info : buffers) { - auto seconds = - std::chrono::duration_cast(test.serialize_test( - buffer_info.writer, iteration_count, - buffer_info.write_reset_func, buffer_info.reset_data)); - double qps = iteration_count / seconds.count(); - std::cout << std::fixed << std::setprecision(3) - << std::setw(time_column_width) << seconds.count() - << buffer_timing_column_separator - << std::setw(qps_column_width) << qps - << buffer_column_separator; - } - std::cout << std::endl; - } - } - - print_header("Deserialization benchmarks"); - for (const auto& test : tests_) { - if (test.deserialize_test) { - std::cout << std::setw(name_column_width) << test.name << " : " - << std::setw(data_size_column_width) << test.data_size - << buffer_column_separator; - for (const auto& buffer_info : buffers) { - auto seconds = - std::chrono::duration_cast(test.deserialize_test( - buffer_info.reader, buffer_info.writer, iteration_count, - buffer_info.read_reset_func, buffer_info.write_reset_func, - buffer_info.reset_data)); - double qps = iteration_count / seconds.count(); - std::cout << std::fixed << std::setprecision(3) - << std::setw(time_column_width) << seconds.count() - << buffer_timing_column_separator - << std::setw(qps_column_width) << qps - << buffer_column_separator; - } - std::cout << std::endl; - } - } - std::cout << dbl_separator << std::endl; - } - - private: - struct TestEntry { - TestEntry(const std::string& test_name, - std::function serialize_test, - std::function deserialize_test, - size_t data_size) - : name{test_name}, - serialize_test{std::move(serialize_test)}, - deserialize_test{std::move(deserialize_test)}, - data_size{data_size} {} - std::string name; - std::function serialize_test; - std::function deserialize_test; - size_t data_size; - }; - - std::vector tests_; -}; - -std::string GenerateContainerName(const std::string& type, size_t count) { - std::stringstream ss; - ss << type << "(" << count << ")"; - return ss.str(); -} - -} // anonymous namespace - -int main(int /*argc*/, char** /*argv*/) { - const size_t iteration_count = 10000000; // 10M iterations. - TestRunner test_runner; - std::cout.imbue(std::locale(std::cout.getloc(), new CommaNumPunct)); - - // Baseline tests to figure out the overhead of buffer resizing and data - // transfers. - for (size_t len : {0, 1, 9, 66, 259}) { - auto serialize_base_test = - std::bind(&SerializeBaseTest, _1, _2, _3, _4, len); - auto deserialize_base_test = - std::bind(&DeserializeBaseTest, _1, _2, _3, _4, _5, _6, len); - test_runner.AddTestFunc("--Baseline--", std::move(serialize_base_test), - std::move(deserialize_base_test), len); - } - - // Individual serialization/deserialization tests. - test_runner.AddTest("bool", true); - test_runner.AddTest("int32_t", 12); - - for (size_t len : {0, 1, 8, 64, 256}) { - test_runner.AddTest(GenerateContainerName("string", len), - std::string(len, '*')); - } - // Serialization is too slow to handle such large strings, add this test for - // deserialization only. - test_runner.AddDeserializationTest(GenerateContainerName("string", 10240), - std::string(10240, '*')); - - for (size_t len : {0, 1, 8, 64, 256}) { - std::vector int_vector(len); - std::iota(int_vector.begin(), int_vector.end(), 0); - test_runner.AddTest(GenerateContainerName("vector", len), - std::move(int_vector)); - } - - std::vector vector_of_strings = { - "012345678901234567890123456789", "012345678901234567890123456789", - "012345678901234567890123456789", "012345678901234567890123456789", - "012345678901234567890123456789", - }; - test_runner.AddTest( - GenerateContainerName("vector", vector_of_strings.size()), - std::move(vector_of_strings)); - - test_runner.AddTest("tuple", - std::make_tuple(123, true, std::string{"foobar"}, 1.1)); - - for (size_t len : {0, 1, 8, 64}) { - std::map test_map; - for (size_t i = 0; i < len; i++) - test_map.emplace(i, std::to_string(i)); - test_runner.AddTest(GenerateContainerName("map", len), - std::move(test_map)); - } - - for (size_t len : {0, 1, 8, 64}) { - std::unordered_map test_map; - for (size_t i = 0; i < len; i++) - test_map.emplace(i, std::to_string(i)); - test_runner.AddTest( - GenerateContainerName("unordered_map", len), - std::move(test_map)); - } - - // BufferWrapper can't be used with deserialization tests right now because - // it requires external buffer to be filled in, which is not available. - std::vector> data_buffers; - for (size_t len : {0, 1, 8, 64, 256}) { - data_buffers.emplace_back(len); - test_runner.AddSerializationTest( - GenerateContainerName("BufferWrapper", len), - BufferWrapper(data_buffers.back().data(), - data_buffers.back().size())); - } - - // Various backing buffers to run the tests on. - std::vector buffers; - - Payload buffer; - buffers.emplace_back("Non-TLS Buffer", &buffer, &buffer, - [](void* ptr) { static_cast(ptr)->Rewind(); }, - [](void* ptr) { static_cast(ptr)->Clear(); }, - &buffer); - - TestPayload tls_buffer; - buffers.emplace_back( - "TLS Buffer", &tls_buffer, &tls_buffer, - [](void* ptr) { static_cast(ptr)->Rewind(); }, - [](void* ptr) { static_cast(ptr)->Clear(); }, &tls_buffer); - - StaticBuffer static_buffer; - buffers.emplace_back( - "Static Buffer", &static_buffer, &static_buffer, - [](void* ptr) { static_cast(ptr)->Rewind(); }, - [](void* ptr) { static_cast(ptr)->Clear(); }, - &static_buffer); - - // Finally, run all the tests. - test_runner.RunTests(iteration_count, buffers); - return 0; -} diff --git a/libs/vr/libpdx/fuzz/Android.bp b/libs/vr/libpdx/fuzz/Android.bp deleted file mode 100644 index ac831ceda0..0000000000 --- a/libs/vr/libpdx/fuzz/Android.bp +++ /dev/null @@ -1,68 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_fuzz { - name: "libpdx_service_dispatcher_fuzzer", - srcs: [ - "service_dispatcher_fuzzer.cpp", - ], - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - ], - static_libs: [ - "libpdx", - ], - shared_libs: [ - "libutils", - "liblog", - "libcutils", - ], -} - -cc_fuzz { - name: "libpdx_message_fuzzer", - srcs: [ - "message_fuzzer.cpp", - ], - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - ], - static_libs: [ - "libpdx", - ], - shared_libs: [ - "libutils", - "liblog", - "libcutils", - ], -} - -cc_fuzz { - name: "libpdx_serialization_fuzzer", - srcs: [ - "serialization_fuzzer.cpp", - ], - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - ], - static_libs: [ - "libpdx", - ], - shared_libs: [ - "libutils", - "liblog", - "libcutils", - ], -} diff --git a/libs/vr/libpdx/fuzz/helpers.h b/libs/vr/libpdx/fuzz/helpers.h deleted file mode 100644 index 83ec4096f6..0000000000 --- a/libs/vr/libpdx/fuzz/helpers.h +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright 2020 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. - */ -// Authors: corbin.souffrant@leviathansecurity.com -// brian.balling@leviathansecurity.com - -#ifndef LEV_FUZZERS_LIBPDX_HELPERS_H_ -#define LEV_FUZZERS_LIBPDX_HELPERS_H_ - -#define UNUSED(expr) \ - do { \ - (void)(expr); \ - } while (0) - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace android::pdx; - -// Vector of operations we can call in the dispatcher. -static const std::vector&, FuzzedDataProvider*)>> - dispatcher_operations = { - [](const std::unique_ptr& dispatcher, - FuzzedDataProvider*) -> void { dispatcher->EnterDispatchLoop(); }, - [](const std::unique_ptr& dispatcher, - FuzzedDataProvider*) -> void { dispatcher->ReceiveAndDispatch(); }, - [](const std::unique_ptr& dispatcher, - FuzzedDataProvider* fdp) -> void { - dispatcher->ReceiveAndDispatch(fdp->ConsumeIntegral()); - }}; - -// Most of the fuzzing occurs within the endpoint, which is derived from an -// abstract class. So we are returning garbage data for most functions besides -// the ones we added or need to actually use. -class FuzzEndpoint : public Endpoint { - public: - explicit FuzzEndpoint(FuzzedDataProvider* fdp) { - _fdp = fdp; - _epoll_fd = eventfd(0, 0); - } - - ~FuzzEndpoint() { close(_epoll_fd); } - - // Returns an fd that can be used with epoll() to wait for incoming messages - // from this endpoint. - int epoll_fd() const { return _epoll_fd; } - - // Associates a Service instance with an endpoint by setting the service - // context pointer to the address of the Service. Only one Service may be - // associated with a given endpoint. - Status SetService(Service* service) { - _service = service; - return Status(0); - } - - // Set the channel context for the given channel. - Status SetChannel(int channel_id, Channel* channel) { - UNUSED(channel_id); - _channel = std::shared_ptr(channel); - return Status(0); - } - - // Receives a message on the given endpoint file descriptor. - // This is called by the dispatcher to determine what operations - // to make, so we are fuzzing the response. - Status MessageReceive(Message* message) { - // Create a randomized MessageInfo struct. - MessageInfo info; - eventfd_t wakeup_val = 0; - info.pid = _fdp->ConsumeIntegral(); - info.tid = _fdp->ConsumeIntegral(); - info.cid = _fdp->ConsumeIntegral(); - info.mid = _fdp->ConsumeIntegral(); - info.euid = _fdp->ConsumeIntegral(); - info.egid = _fdp->ConsumeIntegral(); - info.op = _fdp->ConsumeIntegral(); - info.flags = _fdp->ConsumeIntegral(); - info.service = _service; - info.channel = _channel.get(); - info.send_len = _fdp->ConsumeIntegral(); - info.recv_len = _fdp->ConsumeIntegral(); - info.fd_count = _fdp->ConsumeIntegral(); - if (_fdp->remaining_bytes() >= 32) { - std::vector impulse_vec = _fdp->ConsumeBytes(32); - memcpy(info.impulse, impulse_vec.data(), 32); - } - - *message = Message(info); - eventfd_read(_epoll_fd, &wakeup_val); - - return Status(); - } - - // Returns a tag that uniquely identifies a specific underlying IPC - // transport. - uint32_t GetIpcTag() const { return 0; } - - // Close a channel, signaling the client file object and freeing the channel - // id. Once closed, the client side of the channel always returns the error - // ESHUTDOWN and signals the poll/epoll events POLLHUP and POLLFREE. - Status CloseChannel(int channel_id) { - UNUSED(channel_id); - return Status(); - } - - // Update the event bits for the given channel (given by id), using the - // given clear and set masks. - Status ModifyChannelEvents(int channel_id, int clear_mask, - int set_mask) { - UNUSED(channel_id); - UNUSED(clear_mask); - UNUSED(set_mask); - return Status(); - } - - // Create a new channel and push it as a file descriptor to the process - // sending the |message|. |flags| may be set to O_NONBLOCK and/or - // O_CLOEXEC to control the initial behavior of the new file descriptor (the - // sending process may change these later using fcntl()). The internal - // Channel instance associated with this channel is set to |channel|, - // which may be nullptr. The new channel id allocated for this channel is - // returned in |channel_id|, which may also be nullptr if not needed. - Status PushChannel(Message* message, int flags, - Channel* channel, int* channel_id) { - UNUSED(message); - UNUSED(flags); - UNUSED(channel); - UNUSED(channel_id); - return Status(); - } - - // Check whether the |ref| is a reference to a channel to the service - // represented by the |endpoint|. If the channel reference in question is - // valid, the Channel object is returned in |channel| when non-nullptr and - // the channel ID is returned through the Status object. - Status CheckChannel(const Message* message, ChannelReference ref, - Channel** channel) { - UNUSED(message); - UNUSED(ref); - UNUSED(channel); - return Status(); - } - - // Replies to the message with a return code. - Status MessageReply(Message* message, int return_code) { - UNUSED(message); - UNUSED(return_code); - return Status(); - } - - // Replies to the message with a file descriptor. - Status MessageReplyFd(Message* message, unsigned int push_fd) { - UNUSED(message); - UNUSED(push_fd); - return Status(); - } - - // Replies to the message with a local channel handle. - Status MessageReplyChannelHandle(Message* message, - const LocalChannelHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - // Replies to the message with a borrowed local channel handle. - Status MessageReplyChannelHandle(Message* message, - const BorrowedChannelHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - // Replies to the message with a remote channel handle. - Status MessageReplyChannelHandle(Message* message, - const RemoteChannelHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - // Reads message data into an array of memory buffers. - Status ReadMessageData(Message* message, const iovec* vector, - size_t vector_length) { - UNUSED(message); - UNUSED(vector); - UNUSED(vector_length); - return Status(); - } - - // Sends reply data for message. - Status WriteMessageData(Message* message, const iovec* vector, - size_t vector_length) { - UNUSED(message); - UNUSED(vector); - UNUSED(vector_length); - return Status(); - } - - // Records a file descriptor into the message buffer and returns the - // remapped reference to be sent to the remote process. - Status PushFileHandle(Message* message, - const LocalHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - Status PushFileHandle(Message* message, - const BorrowedHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - Status PushFileHandle(Message* message, - const RemoteHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - Status PushChannelHandle(Message* message, - const LocalChannelHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - Status PushChannelHandle( - Message* message, const BorrowedChannelHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - Status PushChannelHandle( - Message* message, const RemoteChannelHandle& handle) { - UNUSED(message); - UNUSED(handle); - return Status(); - } - - // Obtains a file descriptor/channel handle from a message for the given - // reference. - LocalHandle GetFileHandle(Message* message, FileReference ref) const { - UNUSED(message); - UNUSED(ref); - return LocalHandle(); - } - - LocalChannelHandle GetChannelHandle(Message* message, - ChannelReference ref) const { - UNUSED(message); - UNUSED(ref); - return LocalChannelHandle(); - } - - // Transport-specific message state management. - void* AllocateMessageState() { return nullptr; } - - void FreeMessageState(void* state) { UNUSED(state); } - - // Cancels the endpoint, unblocking any receiver threads waiting for a - // message. - Status Cancel() { return Status(); } - - private: - FuzzedDataProvider* _fdp; - std::shared_ptr _channel; - Service* _service; - int _epoll_fd; -}; - -#endif // LEV_FUZZERS_LIBPDX_HELPERS_H_ diff --git a/libs/vr/libpdx/fuzz/message_fuzzer.cpp b/libs/vr/libpdx/fuzz/message_fuzzer.cpp deleted file mode 100644 index b627045ab6..0000000000 --- a/libs/vr/libpdx/fuzz/message_fuzzer.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2020 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. - */ -// Authors: corbin.souffrant@leviathansecurity.com -// brian.balling@leviathansecurity.com - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace android::pdx; - -// Fuzzer for Message object functions. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - - FuzzEndpoint* endpoint = new FuzzEndpoint(&fdp); - std::shared_ptr service( - new Service("FuzzService", std::unique_ptr(endpoint))); - std::shared_ptr channel(nullptr); - - // Generate a random Message object to call functions in. - MessageInfo info; - info.pid = fdp.ConsumeIntegral(); - info.tid = fdp.ConsumeIntegral(); - info.cid = fdp.ConsumeIntegral(); - info.mid = fdp.ConsumeIntegral(); - info.euid = fdp.ConsumeIntegral(); - info.egid = fdp.ConsumeIntegral(); - info.op = fdp.ConsumeIntegral(); - info.flags = fdp.ConsumeIntegral(); - info.service = service.get(); - info.channel = channel.get(); - info.send_len = fdp.ConsumeIntegral(); - info.recv_len = fdp.ConsumeIntegral(); - info.fd_count = fdp.ConsumeIntegral(); - if (fdp.remaining_bytes() >= 32) { - std::vector impulse_vec = fdp.ConsumeBytes(32); - memcpy(info.impulse, impulse_vec.data(), 32); - } - - Message message = Message(info); - - // A bunch of getters that probably won't do much, but might as well - // get coverage, while we are here. - message.GetProcessId(); - message.GetThreadId(); - message.GetEffectiveUserId(); - message.GetEffectiveGroupId(); - message.GetChannelId(); - message.GetMessageId(); - message.GetOp(); - message.GetFlags(); - message.GetSendLength(); - message.GetReceiveLength(); - message.GetFileDescriptorCount(); - message.ImpulseEnd(); - message.replied(); - message.IsChannelExpired(); - message.IsServiceExpired(); - message.GetState(); - message.GetState(); - - // Some misc. functions. - unsigned int fd = fdp.ConsumeIntegral(); - int clear_mask = fdp.ConsumeIntegral(); - int set_mask = fdp.ConsumeIntegral(); - Status status = {}; - message.ModifyChannelEvents(clear_mask, set_mask); - - // Fuzz the handle functions. - LocalHandle l_handle = {}; - BorrowedHandle b_handle = {}; - RemoteHandle r_handle = {}; - LocalChannelHandle lc_handle = {}; - BorrowedChannelHandle bc_handle = {}; - RemoteChannelHandle rc_handle = {}; - FileReference f_ref = fdp.ConsumeIntegral(); - ChannelReference c_ref = fdp.ConsumeIntegral(); - - // These don't actually modify any state in the Message or params. - // They can be called in any order. - message.PushFileHandle(b_handle); - message.PushFileHandle(r_handle); - message.PushChannelHandle(lc_handle); - message.PushChannelHandle(bc_handle); - message.PushChannelHandle(rc_handle); - message.GetFileHandle(f_ref, &l_handle); - message.GetChannelHandle(c_ref, &lc_handle); - - // Can only reply once, pick at random. - switch (fdp.ConsumeIntegral()) { - case 0: - message.ReplyFileDescriptor(fd); - break; - case 1: - message.Reply(status); - break; - case 2: - message.Reply(l_handle); - break; - case 3: - message.Reply(b_handle); - break; - case 4: - message.Reply(r_handle); - break; - case 5: - message.Reply(lc_handle); - break; - case 6: - message.Reply(bc_handle); - break; - case 7: - message.Reply(rc_handle); - } - - // Fuzz the channel functions. - int flags = fdp.ConsumeIntegral(); - int channel_id = 0; - message.PushChannel(flags, channel, &channel_id); - message.CheckChannel(service.get(), c_ref, &channel); - message.CheckChannel(c_ref, &channel); - message.PushChannel(service.get(), flags, channel, &channel_id); - size_t iovec_size = sizeof(iovec); - struct iovec* iovecs = nullptr; - - // Fuzz the read/write functions. Needs at least one iovec, plus one byte. - if (fdp.remaining_bytes() >= iovec_size + 1) { - std::vector tmp_vec = fdp.ConsumeBytes(iovec_size); - struct iovec* vector = reinterpret_cast(tmp_vec.data()); - std::vector tmp_buf = - fdp.ConsumeBytes(fdp.remaining_bytes()); - void* buf = reinterpret_cast(tmp_buf.data()); - size_t buf_size = fdp.ConsumeIntegral(); - - // Capping num_vecs to 1024 so it doesn't allocate too much memory. - size_t num_vecs = fdp.ConsumeIntegralInRange(0, 1024); - - if (num_vecs > 0) - iovecs = new struct iovec[num_vecs]; - for (size_t i = 0; i < num_vecs; i++) { - iovecs[i] = *vector; - } - - message.ReadAll(vector, buf_size); - message.WriteAll(buf, buf_size); - message.ReadVectorAll(vector, num_vecs); - message.WriteVectorAll(vector, num_vecs); - message.ReadVector(vector, buf_size); - message.WriteVector(vector, buf_size); - } - - if (iovecs != nullptr) - delete[] iovecs; - return 0; -} diff --git a/libs/vr/libpdx/fuzz/serialization_fuzzer.cpp b/libs/vr/libpdx/fuzz/serialization_fuzzer.cpp deleted file mode 100644 index f5c5a5a4c4..0000000000 --- a/libs/vr/libpdx/fuzz/serialization_fuzzer.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright 2020 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. - */ -// Authors: corbin.souffrant@leviathansecurity.com -// brian.balling@leviathansecurity.com - -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace android::pdx; -using namespace android::pdx::rpc; - -struct FuzzType { - int a; - float b; - std::string c; - - FuzzType() {} - FuzzType(int a, float b, const std::string& c) : a(a), b(b), c(c) {} - - private: - PDX_SERIALIZABLE_MEMBERS(FuzzType, a, b, c); -}; - -// Fuzzer for Serialization operations, this is mostly just lifted from the -// existing test cases to use fuzzed values as inputs. -void FuzzSerializeDeserialize(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload result; - - // Currently, only fuzzing subset of types. In the future, may want - // to add more difficult to generate types like array, map, enum, etc... - bool b_val = fdp.ConsumeBool(); - uint8_t u8_val = fdp.ConsumeIntegral(); - uint16_t u16_val = fdp.ConsumeIntegral(); - uint32_t u32_val = fdp.ConsumeIntegral(); - uint64_t u64_val = fdp.ConsumeIntegral(); - int8_t i8_val = fdp.ConsumeIntegral(); - int16_t i16_val = fdp.ConsumeIntegral(); - int32_t i32_val = fdp.ConsumeIntegral(); - int64_t i64_val = fdp.ConsumeIntegral(); - float f_val = fdp.ConsumeFloatingPoint(); - double d_val = fdp.ConsumeFloatingPoint(); - std::string s_val = fdp.ConsumeRandomLengthString(fdp.remaining_bytes()); - std::vector vec_val = - fdp.ConsumeBytes(fdp.remaining_bytes()); - FuzzType t1_val{reinterpret_cast(i32_val), f_val, s_val}; - - // Types need to be individually fuzzed because code path changes depending - // on which type is being serialized/deserialized. - Serialize(b_val, &result); - Deserialize(&b_val, &result); - Serialize(u8_val, &result); - Deserialize(&u8_val, &result); - Serialize(u16_val, &result); - Deserialize(&u16_val, &result); - Serialize(u32_val, &result); - Deserialize(&u32_val, &result); - Serialize(u64_val, &result); - Deserialize(&u64_val, &result); - Serialize(i8_val, &result); - Deserialize(&i8_val, &result); - Serialize(i16_val, &result); - Deserialize(&i16_val, &result); - Serialize(i32_val, &result); - Deserialize(&i32_val, &result); - Serialize(i64_val, &result); - Deserialize(&i64_val, &result); - Serialize(f_val, &result); - Deserialize(&f_val, &result); - Serialize(d_val, &result); - Deserialize(&d_val, &result); - Serialize(s_val, &result); - Deserialize(&s_val, &result); - Serialize(WrapString(s_val), &result); - Deserialize(&s_val, &result); - Serialize(vec_val, &result); - Deserialize(&vec_val, &result); - Serialize(t1_val, &result); - Deserialize(&t1_val, &result); -} - -void FuzzDeserializeUint8(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_UINT8, fdp.ConsumeIntegral()}; - std::uint8_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeUint16(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_UINT16, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - std::uint16_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeUint32(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_UINT32, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - std::uint32_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeUint64(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = { - ENCODING_TYPE_UINT64, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - std::uint64_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeInt8(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_INT8, fdp.ConsumeIntegral()}; - std::int8_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeInt16(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_INT16, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - std::int16_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeInt32(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_INT32, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - std::int32_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeInt64(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_INT64, - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - std::int64_t result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeFloat32(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_FLOAT32, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - float floatResult; - Deserialize(&floatResult, &buffer); - - buffer.Rewind(); - double doubleResult; - Deserialize(&doubleResult, &buffer); -} - -void FuzzDeserializeFloat64(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = { - ENCODING_TYPE_FLOAT64, fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - double result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeFixstr(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - std::string s_val = fdp.ConsumeRemainingBytesAsString(); - Payload buffer = {ENCODING_TYPE_FIXSTR_MAX}; - for (std::string::iterator iter = s_val.begin(); iter != s_val.end(); - iter++) { - buffer.Append(1, *iter); - } - std::string result; - Deserialize(&result, &buffer); -} - -void FuzzDeserializeFixmap(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_FIXMAP_MAX}; - // Fill the map with the fuzzed data, not attempting to - // make a valid map - while (fdp.remaining_bytes() > 0) { - buffer.Append(1, fdp.ConsumeIntegral()); - } - - std::map result; - Deserialize(&result, &buffer); - - buffer.Rewind(); - std::unordered_map unorderedResult; - Deserialize(&unorderedResult, &buffer); -} - -void FuzzDeserializeVariant(const uint8_t* data, size_t size) { - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - Payload buffer = {ENCODING_TYPE_INT16, - ENCODING_TYPE_FLOAT32, - ENCODING_TYPE_FIXSTR_MAX, - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral(), - fdp.ConsumeIntegral()}; - // Add the rest of the data as a string - std::string s_val = fdp.ConsumeRemainingBytesAsString(); - for (std::string::iterator iter = s_val.begin(); iter != s_val.end(); - iter++) { - buffer.Append(1, *iter); - } - Variant result; - Deserialize(&result, &buffer); -} - -// Attempts to deserialize fuzzed data as various types -void FuzzDeserialize(const uint8_t* data, size_t size) { - FuzzDeserializeUint8(data, size); - FuzzDeserializeUint16(data, size); - FuzzDeserializeUint32(data, size); - FuzzDeserializeUint64(data, size); - FuzzDeserializeInt8(data, size); - FuzzDeserializeInt16(data, size); - FuzzDeserializeInt32(data, size); - FuzzDeserializeInt64(data, size); - FuzzDeserializeFloat32(data, size); - FuzzDeserializeFloat64(data, size); - FuzzDeserializeFixstr(data, size); - FuzzDeserializeFixmap(data, size); - FuzzDeserializeVariant(data, size); -} - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - FuzzSerializeDeserialize(data, size); - FuzzDeserialize(data, size); - - return 0; -} diff --git a/libs/vr/libpdx/fuzz/service_dispatcher_fuzzer.cpp b/libs/vr/libpdx/fuzz/service_dispatcher_fuzzer.cpp deleted file mode 100644 index 3a3bfd9bcf..0000000000 --- a/libs/vr/libpdx/fuzz/service_dispatcher_fuzzer.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2020 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. - */ -// Authors: corbin.souffrant@leviathansecurity.com -// brian.balling@leviathansecurity.com - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace android::pdx; - -// Dispatch fuzzer entry point. This fuzzer creates a ServiceDispatcher -// and creates an endpoint that returns fuzzed messages that are passed -// to the ReceiveAndDispatch and DispatchLoop functions. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - eventfd_t wakeup_val = 1; - FuzzedDataProvider fdp = FuzzedDataProvider(data, size); - - // Endpoint is only used to be immediately wrapped as a unique_ptr, - // so it is ok to be using a raw ptr and new here without freeing. - FuzzEndpoint* endpoint = new FuzzEndpoint(&fdp); - std::unique_ptr dispatcher = ServiceDispatcher::Create(); - std::shared_ptr channel(nullptr); - std::shared_ptr client(nullptr); - std::shared_ptr service( - new Service("FuzzService", std::unique_ptr(endpoint))); - - service->SetChannel(0, std::shared_ptr(channel)); - dispatcher->AddService(service); - - // Dispatcher blocks, so needs to run in its own thread. - std::thread run_dispatcher([&]() { - uint8_t opt = 0; - - // Right now the only operations block, so the while loop is pointless - // but leaving it in, just in case that ever changes. - while (fdp.remaining_bytes() > sizeof(MessageInfo)) { - opt = fdp.ConsumeIntegral() % dispatcher_operations.size(); - dispatcher_operations[opt](dispatcher, &fdp); - } - }); - - // Continuously wake up the epoll so the dispatcher can run. - while (fdp.remaining_bytes() > sizeof(MessageInfo)) { - eventfd_write(endpoint->epoll_fd(), wakeup_val); - } - - // Cleanup the dispatcher and thread. - dispatcher->SetCanceled(true); - if (run_dispatcher.joinable()) - run_dispatcher.join(); - dispatcher->RemoveService(service); - - return 0; -} diff --git a/libs/vr/libpdx/mock_tests.cpp b/libs/vr/libpdx/mock_tests.cpp deleted file mode 100644 index 4143837cb4..0000000000 --- a/libs/vr/libpdx/mock_tests.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include -#include -#include -#include -#include -#include - -TEST(MockTypes, Instantiation) { - // Make sure all our interfaces are mocked out properly and mock instances - // can be created. - android::pdx::MockClientChannel client_channel; - android::pdx::MockClientChannelFactory client_channel_factory; - android::pdx::MockInputResourceMapper input_resource_mapper; - android::pdx::MockMessageReader message_reader; - android::pdx::MockOutputResourceMapper output_resource_mapper; - android::pdx::MockMessageWriter message_writer; - android::pdx::MockEndpoint endpoint; -} diff --git a/libs/vr/libpdx/private/pdx/channel_handle.h b/libs/vr/libpdx/private/pdx/channel_handle.h deleted file mode 100644 index bd04305184..0000000000 --- a/libs/vr/libpdx/private/pdx/channel_handle.h +++ /dev/null @@ -1,123 +0,0 @@ -#ifndef ANDROID_PDX_CHANNEL_HANDLE_H_ -#define ANDROID_PDX_CHANNEL_HANDLE_H_ - -#include -#include - -namespace android { -namespace pdx { - -enum class ChannelHandleMode { - Local, - Borrowed, - Remote, -}; - -class ChannelManagerInterface { - public: - virtual void CloseHandle(std::int32_t handle) = 0; - - protected: - // Nobody should be allowed to delete the instance of channel manager - // through this interface. - virtual ~ChannelManagerInterface() = default; -}; - -class ChannelHandleBase { - public: - ChannelHandleBase() = default; - explicit ChannelHandleBase(const int32_t& value) : value_{value} {} - - ChannelHandleBase(const ChannelHandleBase&) = delete; - ChannelHandleBase& operator=(const ChannelHandleBase&) = delete; - - std::int32_t value() const { return value_; } - bool valid() const { return value_ >= 0; } - explicit operator bool() const { return valid(); } - - void Close() { value_ = kEmptyHandle; } - - protected: - // Must not be used by itself. Must be derived from. - ~ChannelHandleBase() = default; - enum : std::int32_t { kEmptyHandle = -1 }; - - std::int32_t value_{kEmptyHandle}; -}; - -template -class ChannelHandle : public ChannelHandleBase { - public: - ChannelHandle() = default; - using ChannelHandleBase::ChannelHandleBase; - ChannelHandle(ChannelHandle&& other) noexcept : ChannelHandleBase{other.value_} { - other.value_ = kEmptyHandle; - } - ~ChannelHandle() = default; - - ChannelHandle Duplicate() const { return ChannelHandle{value_}; } - - ChannelHandle& operator=(ChannelHandle&& other) noexcept { - value_ = other.value_; - other.value_ = kEmptyHandle; - return *this; - } -}; - -template <> -class ChannelHandle : public ChannelHandleBase { - public: - ChannelHandle() = default; - ChannelHandle(ChannelManagerInterface* manager, int32_t value) - : ChannelHandleBase{value}, manager_{manager} {} - - ChannelHandle(const ChannelHandle&) = delete; - ChannelHandle& operator=(const ChannelHandle&) = delete; - - ChannelHandle(ChannelHandle&& other) noexcept - : ChannelHandleBase{other.value_}, manager_{other.manager_} { - other.manager_ = nullptr; - other.value_ = kEmptyHandle; - } - - ChannelHandle& operator=(ChannelHandle&& other) noexcept { - value_ = other.value_; - manager_ = other.manager_; - other.value_ = kEmptyHandle; - other.manager_ = nullptr; - return *this; - } - - ~ChannelHandle() { - if (manager_) - manager_->CloseHandle(value_); - } - - ChannelHandle Borrow() const { - return ChannelHandle{value_}; - } - - void Close() { - if (manager_) - manager_->CloseHandle(value_); - manager_ = nullptr; - value_ = kEmptyHandle; - } - - private: - ChannelManagerInterface* manager_{nullptr}; -}; - -using LocalChannelHandle = ChannelHandle; -using BorrowedChannelHandle = ChannelHandle; -using RemoteChannelHandle = ChannelHandle; - -// ChannelReference is a 32 bit integer used in IPC serialization to be -// transferred across processes. You can convert this value to a local channel -// handle by calling Transaction.GetChannelHandle(). -using ChannelReference = int32_t; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_CHANNEL_HANDLE_H_ diff --git a/libs/vr/libpdx/private/pdx/channel_parcelable.h b/libs/vr/libpdx/private/pdx/channel_parcelable.h deleted file mode 100644 index 59ef9d3119..0000000000 --- a/libs/vr/libpdx/private/pdx/channel_parcelable.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef ANDROID_PDX_CHANNEL_PARCELABLE_H_ -#define ANDROID_PDX_CHANNEL_PARCELABLE_H_ - -#include -#include - -namespace android { -namespace pdx { - -/** - * A parcelable object holds all necessary objects to recreate a ClientChannel. - * In addition to the android::Parcelable interface, this interface exposees - * more PDX-related interface. - */ -class ChannelParcelable : public Parcelable { - public: - virtual ~ChannelParcelable() = default; - - // Returns whether the parcelable object holds a valid client channel. - virtual bool IsValid() const = 0; - - // Returns a channel handle constructed from this parcelable object and takes - // the ownership of all resources from the parcelable object. In another word, - // the parcelable object will become invalid after TakeChannelHandle returns. - virtual LocalChannelHandle TakeChannelHandle() = 0; -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_CHANNEL_PARCELABLE_H_ diff --git a/libs/vr/libpdx/private/pdx/client.h b/libs/vr/libpdx/private/pdx/client.h deleted file mode 100644 index 7e2d55c8fe..0000000000 --- a/libs/vr/libpdx/private/pdx/client.h +++ /dev/null @@ -1,302 +0,0 @@ -#ifndef ANDROID_PDX_CLIENT_H_ -#define ANDROID_PDX_CLIENT_H_ - -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace android { -namespace pdx { - -class Transaction; - -/* - * Base class of client-side service API classes. - */ -class Client { - public: - static const int64_t kInfiniteTimeout = -1; - - virtual ~Client() = default; - - /* - * Returns true if the Client instance successfully initialized, false - * otherwise. Subclasses that can fail to initialize must override this and - * AND their initialization result with this base class method's result. - * - * This method is not intended to perform initialization, only to report - * the status of the initialization. - */ - virtual bool IsInitialized() const; - - /* - * Returns the error code describing the Client initialization failure, or 0 - * if there was no failure. - */ - int error() const; - - // Returns a reference to IPC channel handle. - LocalChannelHandle& GetChannelHandle(); - const LocalChannelHandle& GetChannelHandle() const; - - protected: - friend Transaction; - explicit Client(std::unique_ptr channel); - explicit Client(std::unique_ptr channel_factory, - int64_t timeout_ms = kInfiniteTimeout); - - /* - * Called by Client::Connect() after successfully connecting to the service - * endpoint. Subclasses may override this method to perform additional setup, - * including sending messages to complete the connection process. - * - * Subclasses may call Client::Close() within this method to terminate the - * connection; Client::Connect() returns the negated error passed to - * Client::Close() when this happens. - */ - virtual void OnConnect(); - - enum : size_t { MAX_IMPULSE_LENGTH = sizeof(uint64_t) * 4 }; - - Status SendImpulse(int opcode); - Status SendImpulse(int opcode, const void* buffer, size_t length); - - /* - * Remote method call API using pdx::rpc serialization. - * Include pdx/rpc/remote_method.h to use these methods. - */ - template - Status InvokeRemoteMethod(Args&&... args); - - template - Status InvokeRemoteMethodInPlace(ReturnType* return_value, - Args&&... args); - - /* - * Close the endpoint file descriptor and optionally indicate an error, which - * may be retrieved through error(). Subclasses may use this in their - * constructor to signal failure during initialization or at other times - * during operation. - */ - void Close(int error); - - /* - * Returns true if the client is connected to the service, false otherwise. - */ - bool IsConnected() const; - - /* - * Enables auto-reconnect with the given timeout. Use kInfiniteTimeout (-1) - * for no timeout. Auto-reconnect can only be enabled if the Client class - * was constructed with a ClientChannelFactory. - */ - void EnableAutoReconnect(int64_t reconnect_timeout_ms); - - /* - * Disables auto-reconnect. - */ - void DisableAutoReconnect(); - - /* - * Returns an fd that the client may use to check/wait for asynchronous - * notifications to the channel. It is implementation dependent how the - * transport backend handles this feature, however all implementations must - * support at least POLLIN/EPOLLIN/readable. - * - * For uses that require more than one type of event, use - * ClientChannel::GetEventMask() to distinguish between events. - */ - int event_fd() const; - - /* - * Returns the underlying ClientChannel object. - */ - ClientChannel* GetChannel() const { return channel_.get(); } - std::unique_ptr&& TakeChannel() { return std::move(channel_); } - - private: - Client(const Client&) = delete; - void operator=(const Client&) = delete; - - Status CheckReconnect(); - bool NeedToDisconnectChannel(int error) const; - void CheckDisconnect(int error); - - template - inline void CheckDisconnect(const Status& status) { - if (!status) - CheckDisconnect(status.error()); - } - - std::unique_ptr channel_; - int error_{0}; - - // Reconnection state. - std::unique_ptr channel_factory_; - int64_t reconnect_timeout_ms_{0}; - bool auto_reconnect_enabled_{false}; -}; - -/* - * Utility template base class for client-side service API classes. Handles - * initialization checks during allocation and automatically cleans up on - * failure. - * - * @tparam T Type of the class extending this one. - * @tparam C Client class to wrap. Defaults to the Client class. - */ -template -class ClientBase : public ParentClient { - public: - // Type of the client this class wraps. - using ClientType = ParentClient; - - static_assert(std::is_base_of::value, - "The provided parent client is not a Client subclass."); - - /* - * Allocates a new instance of the superclass and checks for successful - * initialization. - * - * The variadic arguments must expand to match one of type T's constructors - * and are passed through unchanged. If a timeout is desired, subclasses are - * responsible for passing this through to the appropriate ClientBase - * constructor. - * - * Returns a unique_ptr to the new instance on success, or an empty unique_ptr - * otherwise. - */ - template - static inline std::unique_ptr Create(Args&&... args) { - std::unique_ptr client(new T(std::forward(args)...)); - if (client->IsInitialized()) - return client; - else - return nullptr; - } - - protected: - /* - * Type of the base class. Useful for referencing the base class type and - * constructor in subclasses. Subclasses with non-public constructors - * must declare BASE a friend. - */ - using BASE = ClientBase; - - /* - * Type of the unique_ptr deleter. Useful for friend declarations. - */ - using deleter_type = typename std::unique_ptr::deleter_type; - - using ParentClient::ParentClient; -}; - -class Transaction final : public OutputResourceMapper, - public InputResourceMapper { - public: - explicit Transaction(Client& client); - ~Transaction(); - - template - Status Send(int opcode) { - return SendVector(opcode, nullptr, 0, nullptr, 0); - } - - template - Status Send(int opcode, const void* send_buffer, size_t send_length, - void* receive_buffer, size_t receive_length) { - const bool send = (send_buffer && send_length); - const bool receive = (receive_buffer && receive_length); - const iovec send_vector = {const_cast(send_buffer), send_length}; - const iovec receive_vector = {receive_buffer, receive_length}; - return SendVector(opcode, send ? &send_vector : nullptr, send ? 1 : 0, - receive ? &receive_vector : nullptr, receive ? 1 : 0); - } - - template - Status SendVector(int opcode, const iovec* send_vector, size_t send_count, - const iovec* receive_vector, size_t receive_count) { - Status ret; - SendTransaction(opcode, &ret, send_vector, send_count, receive_vector, - receive_count); - return ret; - } - - template - Status SendVector(int opcode, const iovec (&send_vector)[send_count], - const iovec (&receive_vector)[receive_count]) { - return SendVector(opcode, send_vector, send_count, receive_vector, - receive_count); - } - - template - Status SendVector(int opcode, const iovec (&send_vector)[send_count], - std::nullptr_t) { - return SendVector(opcode, send_vector, send_count, nullptr, 0); - } - - template - Status SendVector(int opcode, std::nullptr_t, - const iovec (&receive_vector)[receive_count]) { - return SendVector(opcode, nullptr, 0, receive_vector, receive_count); - } - - // OutputResourceMapper - Status PushFileHandle(const LocalHandle& handle) override; - Status PushFileHandle(const BorrowedHandle& handle) override; - Status PushFileHandle(const RemoteHandle& handle) override; - Status PushChannelHandle( - const LocalChannelHandle& handle) override; - Status PushChannelHandle( - const BorrowedChannelHandle& handle) override; - Status PushChannelHandle( - const RemoteChannelHandle& handle) override; - - // InputResourceMapper - bool GetFileHandle(FileReference ref, LocalHandle* handle) override; - bool GetChannelHandle(ChannelReference ref, - LocalChannelHandle* handle) override; - - private: - bool EnsureStateAllocated(); - void SendTransaction(int opcode, Status* ret, const iovec* send_vector, - size_t send_count, const iovec* receive_vector, - size_t receive_count); - void SendTransaction(int opcode, Status* ret, const iovec* send_vector, - size_t send_count, const iovec* receive_vector, - size_t receive_count); - void SendTransaction(int opcode, Status* ret, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, size_t receive_count); - void SendTransaction(int opcode, Status* ret, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, size_t receive_count); - void CheckDisconnect(int error); - - template - inline void CheckDisconnect(const Status& status) { - if (!status) - CheckDisconnect(status.error()); - } - - Client& client_; - void* state_{nullptr}; - bool state_allocated_{false}; -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_CLIENT_H_ diff --git a/libs/vr/libpdx/private/pdx/client_channel.h b/libs/vr/libpdx/private/pdx/client_channel.h deleted file mode 100644 index f33a60e881..0000000000 --- a/libs/vr/libpdx/private/pdx/client_channel.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef ANDROID_PDX_CLIENT_CHANNEL_H_ -#define ANDROID_PDX_CLIENT_CHANNEL_H_ - -#include - -#include -#include -#include -#include - -struct iovec; - -namespace android { -namespace pdx { - -class ClientChannel { - public: - virtual ~ClientChannel() = default; - - // Returns a tag that uniquely identifies a specific underlying IPC transport. - virtual uint32_t GetIpcTag() const = 0; - - virtual int event_fd() const = 0; - virtual Status GetEventMask(int events) = 0; - - struct EventSource { - int event_fd; - int event_mask; - }; - - // Returns a set of event-generating fds with and event mask for each. These - // fds are owned by the ClientChannel and must never be closed by the caller. - virtual std::vector GetEventSources() const = 0; - - virtual LocalChannelHandle& GetChannelHandle() = 0; - virtual const LocalChannelHandle& GetChannelHandle() const = 0; - virtual void* AllocateTransactionState() = 0; - virtual void FreeTransactionState(void* state) = 0; - - virtual Status SendImpulse(int opcode, const void* buffer, - size_t length) = 0; - - virtual Status SendWithInt(void* transaction_state, int opcode, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, - size_t receive_count) = 0; - virtual Status SendWithFileHandle( - void* transaction_state, int opcode, const iovec* send_vector, - size_t send_count, const iovec* receive_vector, size_t receive_count) = 0; - virtual Status SendWithChannelHandle( - void* transaction_state, int opcode, const iovec* send_vector, - size_t send_count, const iovec* receive_vector, size_t receive_count) = 0; - - virtual FileReference PushFileHandle(void* transaction_state, - const LocalHandle& handle) = 0; - virtual FileReference PushFileHandle(void* transaction_state, - const BorrowedHandle& handle) = 0; - virtual ChannelReference PushChannelHandle( - void* transaction_state, const LocalChannelHandle& handle) = 0; - virtual ChannelReference PushChannelHandle( - void* transaction_state, const BorrowedChannelHandle& handle) = 0; - virtual bool GetFileHandle(void* transaction_state, FileReference ref, - LocalHandle* handle) const = 0; - virtual bool GetChannelHandle(void* transaction_state, ChannelReference ref, - LocalChannelHandle* handle) const = 0; - - // Returns the internal state of the channel as a parcelable object. The - // ClientChannel is invalidated however, the channel is kept alive by the - // parcelable object and may be transferred to another process. - virtual std::unique_ptr TakeChannelParcelable() = 0; -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_CLIENT_CHANNEL_H_ diff --git a/libs/vr/libpdx/private/pdx/client_channel_factory.h b/libs/vr/libpdx/private/pdx/client_channel_factory.h deleted file mode 100644 index a82ab70be3..0000000000 --- a/libs/vr/libpdx/private/pdx/client_channel_factory.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef ANDROID_PDX_CLIENT_CHANNEL_FACTORY_H_ -#define ANDROID_PDX_CLIENT_CHANNEL_FACTORY_H_ - -#include -#include - -namespace android { -namespace pdx { - -class ClientChannelFactory { - public: - virtual ~ClientChannelFactory() = default; - - virtual Status> Connect( - int64_t timeout_ms) const = 0; -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_CLIENT_CHANNEL_FACTORY_H_ diff --git a/libs/vr/libpdx/private/pdx/file_handle.h b/libs/vr/libpdx/private/pdx/file_handle.h deleted file mode 100644 index fed1529c78..0000000000 --- a/libs/vr/libpdx/private/pdx/file_handle.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef ANDROID_PDX_FILE_HANDLE_H_ -#define ANDROID_PDX_FILE_HANDLE_H_ - -#include -#include - -#include - -namespace android { -namespace pdx { - -enum class FileHandleMode { - Local, - Remote, - Borrowed, -}; - -// Manages ownership, sharing, and lifetime of file descriptors. -template -class FileHandle { - public: - static constexpr int kEmptyFileHandle = -1; - - // Constructs an empty FileHandle object. - FileHandle() : fd_(kEmptyFileHandle) {} - - // Constructs a FileHandle from an integer file descriptor and takes - // ownership. - explicit FileHandle(int fd) : fd_(fd) {} - - // Constructs a FileHandle by opening |path|. The arguments follow the - // semantics of open(). - FileHandle(const std::string& path, int flags, mode_t mode = 0) { - fd_ = open(path.c_str(), flags, mode); - } - - // Constructs a FileHandle by opening |path| relative to |dir_fd|, following - // the semantics of openat(). - FileHandle(const int directory_fd, const std::string& path, int flags, - mode_t mode = 0) { - fd_ = openat(directory_fd, path.c_str(), flags, mode); - } - - // Move constructor that assumes ownership of the file descriptor, leaving the - // other FileHandle object empty. - FileHandle(FileHandle&& other) noexcept { - fd_ = other.fd_; - other.fd_ = kEmptyFileHandle; - } - - // Returns a FileHandle as a duplicate handle of |fd|. Borrowed handles and - // handles in remote handle space are not duplicated. - static FileHandle AsDuplicate(const int fd) { - if (Mode == FileHandleMode::Local) - return FileHandle(dup(fd)); - else - return FileHandle(fd); - } - - // Destructor closes the file descriptor when non-empty. - ~FileHandle() { Close(); } - - // Move assignment operator that assumes ownership of the underlying file - // descriptor, leaving the other FileHandle object empty. - FileHandle& operator=(FileHandle&& other) noexcept { - if (this != &other) { - Reset(other.fd_); - other.fd_ = kEmptyFileHandle; - } - return *this; - } - - // Resets the underlying file handle to |fd|. - void Reset(int fd) { - Close(); - fd_ = fd; - } - - // Closes the underlying file descriptor when non-empty. - void Close() { - if (IsValid() && Mode == FileHandleMode::Local) - close(fd_); - fd_ = kEmptyFileHandle; - } - - // Return the internal fd, passing ownership to the caller. - int Release() { - int release_fd = fd_; - fd_ = kEmptyFileHandle; - return release_fd; - } - - // Duplicates the underlying file descriptor and returns a FileHandle that - // owns the new file descriptor. File descriptors are not duplicated when Mode - // is Remote or Borrowed. - FileHandle Duplicate() const { - return FileHandle(Mode == FileHandleMode::Local ? dup(fd_) : fd_); - } - - FileHandle Borrow() const { - return FileHandle(Get()); - } - - // Gets the underlying file descriptor value. - int Get() const { return fd_; } - bool IsValid() const { return fd_ >= 0; } - explicit operator bool() const { return IsValid(); } - - private: - int fd_; - - FileHandle(const FileHandle&) = delete; - void operator=(const FileHandle&) = delete; -}; - -// Alias for a file handle in the local process' handle space. -using LocalHandle = FileHandle; - -// Alias for a file handle in another process' handle space. Handles returned -// from pushing a file object or channel must be stored in this type of handle -// class, which doesn't close the underlying file descriptor. The underlying -// file descriptor in this wrapper should not be passed to close() because doing -// so would close an unrelated file descriptor in the local handle space. -using RemoteHandle = FileHandle; - -// Alias for borrowed handles in the local process' handle space. A borrowed -// file handle is not close() because this wrapper does not own the underlying -// file descriptor. Care must be take to ensure that a borrowed file handle -// remains valid during use. -using BorrowedHandle = FileHandle; - -// FileReference is a 16 bit integer used in IPC serialization to be -// transferred across processes. You can convert this value to a local file -// handle by calling Transaction.GetFileHandle() on client side and -// Message.GetFileHandle() on service side. -using FileReference = int16_t; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_FILE_HANDLE_H_ diff --git a/libs/vr/libpdx/private/pdx/message_reader.h b/libs/vr/libpdx/private/pdx/message_reader.h deleted file mode 100644 index bc280cffd7..0000000000 --- a/libs/vr/libpdx/private/pdx/message_reader.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef ANDROID_PDX_MESSAGE_READER_H_ -#define ANDROID_PDX_MESSAGE_READER_H_ - -#include - -#include -#include - -namespace android { -namespace pdx { - -class InputResourceMapper { - public: - virtual bool GetFileHandle(FileReference ref, LocalHandle* handle) = 0; - virtual bool GetChannelHandle(ChannelReference ref, - LocalChannelHandle* handle) = 0; - - protected: - virtual ~InputResourceMapper() = default; -}; - -class MessageReader { - public: - // Pointers to start/end of the region in the read buffer. - using BufferSection = std::pair; - - virtual BufferSection GetNextReadBufferSection() = 0; - virtual void ConsumeReadBufferSectionData(const void* new_start) = 0; - virtual InputResourceMapper* GetInputResourceMapper() = 0; - - protected: - virtual ~MessageReader() = default; -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MESSAGE_READER_H_ diff --git a/libs/vr/libpdx/private/pdx/message_writer.h b/libs/vr/libpdx/private/pdx/message_writer.h deleted file mode 100644 index 4a101d6806..0000000000 --- a/libs/vr/libpdx/private/pdx/message_writer.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef ANDROID_PDX_MESSAGE_WRITER_H_ -#define ANDROID_PDX_MESSAGE_WRITER_H_ - -#include -#include -#include - -namespace android { -namespace pdx { - -class OutputResourceMapper { - public: - virtual Status PushFileHandle(const LocalHandle& handle) = 0; - virtual Status PushFileHandle( - const BorrowedHandle& handle) = 0; - virtual Status PushFileHandle(const RemoteHandle& handle) = 0; - virtual Status PushChannelHandle( - const LocalChannelHandle& handle) = 0; - virtual Status PushChannelHandle( - const BorrowedChannelHandle& handle) = 0; - virtual Status PushChannelHandle( - const RemoteChannelHandle& handle) = 0; - - protected: - virtual ~OutputResourceMapper() = default; -}; - -class MessageWriter { - public: - virtual void* GetNextWriteBufferSection(size_t size) = 0; - virtual OutputResourceMapper* GetOutputResourceMapper() = 0; - - protected: - virtual ~MessageWriter() = default; -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MESSAGE_WRITER_H_ diff --git a/libs/vr/libpdx/private/pdx/mock_client_channel.h b/libs/vr/libpdx/private/pdx/mock_client_channel.h deleted file mode 100644 index b1a12996c5..0000000000 --- a/libs/vr/libpdx/private/pdx/mock_client_channel.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef ANDROID_PDX_MOCK_CLIENT_CHANNEL_H_ -#define ANDROID_PDX_MOCK_CLIENT_CHANNEL_H_ - -#include -#include - -namespace android { -namespace pdx { - -class MockClientChannel : public ClientChannel { - public: - MOCK_CONST_METHOD0(GetIpcTag, uint32_t()); - MOCK_CONST_METHOD0(event_fd, int()); - MOCK_CONST_METHOD0(GetEventSources, std::vector()); - MOCK_METHOD1(GetEventMask, Status(int)); - MOCK_METHOD0(GetChannelHandle, LocalChannelHandle&()); - MOCK_CONST_METHOD0(GetChannelHandle, const LocalChannelHandle&()); - MOCK_METHOD0(AllocateTransactionState, void*()); - MOCK_METHOD1(FreeTransactionState, void(void* state)); - MOCK_METHOD3(SendImpulse, - Status(int opcode, const void* buffer, size_t length)); - MOCK_METHOD6(SendWithInt, - Status(void* transaction_state, int opcode, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, size_t receive_count)); - MOCK_METHOD6(SendWithFileHandle, - Status(void* transaction_state, int opcode, - const iovec* send_vector, size_t send_count, - const iovec* receive_vector, - size_t receive_count)); - MOCK_METHOD6(SendWithChannelHandle, - Status(void* transaction_state, int opcode, - const iovec* send_vector, - size_t send_count, - const iovec* receive_vector, - size_t receive_count)); - MOCK_METHOD2(PushFileHandle, FileReference(void* transaction_state, - const LocalHandle& handle)); - MOCK_METHOD2(PushFileHandle, FileReference(void* transaction_state, - const BorrowedHandle& handle)); - MOCK_METHOD2(PushChannelHandle, - ChannelReference(void* transaction_state, - const LocalChannelHandle& handle)); - MOCK_METHOD2(PushChannelHandle, - ChannelReference(void* transaction_state, - const BorrowedChannelHandle& handle)); - MOCK_CONST_METHOD3(GetFileHandle, - bool(void* transaction_state, FileReference ref, - LocalHandle* handle)); - MOCK_CONST_METHOD3(GetChannelHandle, - bool(void* transaction_state, ChannelReference ref, - LocalChannelHandle* handle)); - MOCK_METHOD0(TakeChannelParcelable, std::unique_ptr()); -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MOCK_CLIENT_CHANNEL_H_ diff --git a/libs/vr/libpdx/private/pdx/mock_client_channel_factory.h b/libs/vr/libpdx/private/pdx/mock_client_channel_factory.h deleted file mode 100644 index 0190f5e458..0000000000 --- a/libs/vr/libpdx/private/pdx/mock_client_channel_factory.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef ANDROID_PDX_MOCK_CLIENT_CHANNEL_FACTORY_H_ -#define ANDROID_PDX_MOCK_CLIENT_CHANNEL_FACTORY_H_ - -#include -#include - -namespace android { -namespace pdx { - -class MockClientChannelFactory : public ClientChannelFactory { - public: - MOCK_CONST_METHOD1( - Connect, Status>(int64_t timeout_ms)); -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MOCK_CLIENT_CHANNEL_FACTORY_H_ diff --git a/libs/vr/libpdx/private/pdx/mock_message_reader.h b/libs/vr/libpdx/private/pdx/mock_message_reader.h deleted file mode 100644 index 85e96ef993..0000000000 --- a/libs/vr/libpdx/private/pdx/mock_message_reader.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef ANDROID_PDX_MOCK_MESSAGE_READER_H_ -#define ANDROID_PDX_MOCK_MESSAGE_READER_H_ - -#include -#include - -namespace android { -namespace pdx { - -class MockInputResourceMapper : public InputResourceMapper { - public: - MOCK_METHOD2(GetFileHandle, bool(FileReference ref, LocalHandle* handle)); - MOCK_METHOD2(GetChannelHandle, - bool(ChannelReference ref, LocalChannelHandle* handle)); -}; - -class MockMessageReader : public MessageReader { - public: - MOCK_METHOD0(GetNextReadBufferSection, BufferSection()); - MOCK_METHOD1(ConsumeReadBufferSectionData, void(const void* new_start)); - MOCK_METHOD0(GetInputResourceMapper, InputResourceMapper*()); -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MOCK_MESSAGE_READER_H_ diff --git a/libs/vr/libpdx/private/pdx/mock_message_writer.h b/libs/vr/libpdx/private/pdx/mock_message_writer.h deleted file mode 100644 index e06e5bbc2b..0000000000 --- a/libs/vr/libpdx/private/pdx/mock_message_writer.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef ANDROID_PDX_MOCK_MESSAGE_WRITER_H_ -#define ANDROID_PDX_MOCK_MESSAGE_WRITER_H_ - -#include -#include - -namespace android { -namespace pdx { - -class MockOutputResourceMapper : public OutputResourceMapper { - public: - MOCK_METHOD1(PushFileHandle, - Status(const LocalHandle& handle)); - MOCK_METHOD1(PushFileHandle, - Status(const BorrowedHandle& handle)); - MOCK_METHOD1(PushFileHandle, - Status(const RemoteHandle& handle)); - MOCK_METHOD1(PushChannelHandle, - Status(const LocalChannelHandle& handle)); - MOCK_METHOD1(PushChannelHandle, - Status(const BorrowedChannelHandle& handle)); - MOCK_METHOD1(PushChannelHandle, - Status(const RemoteChannelHandle& handle)); -}; - -class MockMessageWriter : public MessageWriter { - public: - MOCK_METHOD1(GetNextWriteBufferSection, void*(size_t size)); - MOCK_METHOD0(GetOutputResourceMapper, OutputResourceMapper*()); -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MOCK_MESSAGE_WRITER_H_ diff --git a/libs/vr/libpdx/private/pdx/mock_service_endpoint.h b/libs/vr/libpdx/private/pdx/mock_service_endpoint.h deleted file mode 100644 index 7f829e70d0..0000000000 --- a/libs/vr/libpdx/private/pdx/mock_service_endpoint.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef ANDROID_PDX_MOCK_ENDPOINT_H_ -#define ANDROID_PDX_MOCK_ENDPOINT_H_ - -#include -#include - -namespace android { -namespace pdx { - -class MockEndpoint : public Endpoint { - public: - MOCK_CONST_METHOD0(GetIpcTag, uint32_t()); - MOCK_METHOD1(SetService, Status(Service* service)); - MOCK_METHOD2(SetChannel, Status(int channel_id, Channel* channel)); - MOCK_METHOD1(CloseChannel, Status(int channel_id)); - MOCK_METHOD3(ModifyChannelEvents, - Status(int channel_id, int clear_mask, int set_mask)); - MOCK_METHOD4(PushChannel, - Status(Message* message, int flags, - Channel* channel, int* channel_id)); - MOCK_METHOD3(CheckChannel, - Status(const Message* message, ChannelReference ref, - Channel** channel)); - MOCK_METHOD1(MessageReceive, Status(Message* message)); - MOCK_METHOD2(MessageReply, Status(Message* message, int return_code)); - MOCK_METHOD2(MessageReplyFd, - Status(Message* message, unsigned int push_fd)); - MOCK_METHOD2(MessageReplyChannelHandle, - Status(Message* message, - const LocalChannelHandle& handle)); - MOCK_METHOD2(MessageReplyChannelHandle, - Status(Message* message, - const BorrowedChannelHandle& handle)); - MOCK_METHOD2(MessageReplyChannelHandle, - Status(Message* message, - const RemoteChannelHandle& handle)); - MOCK_METHOD3(ReadMessageData, - Status(Message* message, const iovec* vector, - size_t vector_length)); - MOCK_METHOD3(WriteMessageData, - Status(Message* message, const iovec* vector, - size_t vector_length)); - MOCK_METHOD2(PushFileHandle, - Status(Message* message, - const LocalHandle& handle)); - MOCK_METHOD2(PushFileHandle, - Status(Message* message, - const BorrowedHandle& handle)); - MOCK_METHOD2(PushFileHandle, - Status(Message* message, - const RemoteHandle& handle)); - MOCK_METHOD2(PushChannelHandle, - Status(Message* message, - const LocalChannelHandle& handle)); - MOCK_METHOD2(PushChannelHandle, - Status(Message* message, - const BorrowedChannelHandle& handle)); - MOCK_METHOD2(PushChannelHandle, - Status(Message* message, - const RemoteChannelHandle& handle)); - MOCK_CONST_METHOD2(GetFileHandle, - LocalHandle(Message* message, FileReference ref)); - MOCK_CONST_METHOD2(GetChannelHandle, - LocalChannelHandle(Message* message, - ChannelReference ref)); - MOCK_METHOD0(AllocateMessageState, void*()); - MOCK_METHOD1(FreeMessageState, void(void* state)); - MOCK_METHOD0(Cancel, Status()); - MOCK_CONST_METHOD0(epoll_fd, int()); -}; - -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_MOCK_ENDPOINT_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/argument_encoder.h b/libs/vr/libpdx/private/pdx/rpc/argument_encoder.h deleted file mode 100644 index e0062845a5..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/argument_encoder.h +++ /dev/null @@ -1,184 +0,0 @@ -#ifndef ANDROID_PDX_RPC_ARGUMENT_ENCODER_H_ -#define ANDROID_PDX_RPC_ARGUMENT_ENCODER_H_ - -#include -#include -#include - -#include -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Provides automatic serialization of argument lists and return -// values by analyzing the supplied function signature types. -// Examples: -// ArgumentEncoder encoder(writer); -// encoder.EncodeArguments(1, 1.0); - -template -class ArgumentEncoder; - -// Specialization of ArgumentEncoder for void return types. -template -class ArgumentEncoder { - public: - explicit ArgumentEncoder(MessageWriter* writer) : writer_{writer} {} - - // Serializes the arguments as a tuple. - void EncodeArguments(Args... args) { - Serialize(std::forward_as_tuple(args...), writer_); - } - - private: - MessageWriter* writer_; -}; - -// Specialization of ArgumentEncoder for non-void return types. -template -class ArgumentEncoder { - public: - // Simplified types with reference and cv removed. - using ReturnType = typename std::decay::type; - - explicit ArgumentEncoder(MessageWriter* writer) : writer_{writer} {} - - // Serializes the arguments as a tuple. - void EncodeArguments(Args... args) { - Serialize(std::forward_as_tuple(args...), writer_); - } - - // Serializes the return value for rvalue references. - void EncodeReturn(const ReturnType& return_value) { - Serialize(return_value, writer_); - } - - private: - MessageWriter* writer_; -}; - -// Utility to build an ArgumentEncoder from a function pointer and a message -// writer. -template -inline ArgumentEncoder MakeArgumentEncoder( - Return (*)(Args...), MessageWriter* writer) { - return ArgumentEncoder(writer); -} - -// Utility to build an ArgumentEncoder from a method pointer and a message -// writer. -template -inline ArgumentEncoder MakeArgumentEncoder( - Return (Class::*)(Args...), MessageWriter* writer) { - return ArgumentEncoder(writer); -} - -// Utility to build an ArgumentEncoder from a const method pointer and a -// message writer. -template -inline ArgumentEncoder MakeArgumentEncoder( - Return (Class::*)(Args...) const, MessageWriter* writer) { - return ArgumentEncoder(writer); -} - -// Utility to build an ArgumentEncoder from a function type and a message -// writer. -template -inline ArgumentEncoder MakeArgumentEncoder(MessageWriter* writer) { - return ArgumentEncoder(writer); -} - -////////////////////////////////////////////////////////////////////////////// -// Provides automatic deserialization of argument lists and return -// values by analyzing the supplied function signature types. -// Examples: -// auto decoder = MakeArgumentDecoder(reader); -// ErrorType error = decoder.DecodeReturn(&return_value); - -template -class ArgumentDecoder; - -// Specialization of ArgumentDecoder for void return types. -template -class ArgumentDecoder { - public: - // Simplified types with reference and cv removed. - using ArgsTupleType = std::tuple::type...>; - - explicit ArgumentDecoder(MessageReader* reader) : reader_{reader} {} - - // Deserializes arguments into a tuple. - ArgsTupleType DecodeArguments(ErrorType* error) { - ArgsTupleType value; - *error = Deserialize(&value, reader_); - return value; - } - - private: - MessageReader* reader_; -}; - -// Specialization of ArgumentDecoder for non-void return types. -template -class ArgumentDecoder { - public: - // Simplified types with reference and cv removed. - using ArgsTupleType = std::tuple::type...>; - using ReturnType = typename std::decay::type; - - explicit ArgumentDecoder(MessageReader* reader) : reader_{reader} {} - - // Deserializes arguments into a tuple. - ArgsTupleType DecodeArguments(ErrorType* error) { - ArgsTupleType value; - *error = Deserialize(&value, reader_); - return value; - } - - // Deserializes the return value. - ErrorType DecodeReturn(ReturnType* value) { - return Deserialize(value, reader_); - } - - private: - MessageReader* reader_; -}; - -// Utility to build an ArgumentDecoder from a function pointer and a message -// reader. -template -inline ArgumentDecoder MakeArgumentDecoder( - Return (*)(Args...), MessageReader* reader) { - return ArgumentDecoder(reader); -} - -// Utility to build an ArgumentDecoder from a method pointer and a message -// reader. -template -inline ArgumentDecoder MakeArgumentDecoder( - Return (Class::*)(Args...), MessageReader* reader) { - return ArgumentDecoder(reader); -} - -// Utility to build an ArgumentDecoder from a const method pointer and a -// message reader. -template -inline ArgumentDecoder MakeArgumentDecoder( - Return (Class::*)(Args...) const, MessageReader* reader) { - return ArgumentDecoder(reader); -} - -// Utility to build an ArgumentDecoder from a function type and a message -// reader. -template -inline ArgumentDecoder MakeArgumentDecoder(MessageReader* reader) { - return ArgumentDecoder(reader); -} - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_ARGUMENT_ENCODER_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/array_wrapper.h b/libs/vr/libpdx/private/pdx/rpc/array_wrapper.h deleted file mode 100644 index d835c57a44..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/array_wrapper.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef ANDROID_PDX_RPC_ARRAY_WRAPPER_H_ -#define ANDROID_PDX_RPC_ARRAY_WRAPPER_H_ - -#include -#include -#include -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Wrapper class for C array buffers, providing an interface suitable for -// SerializeObject and DeserializeObject. This class serializes to the same -// format as std::vector, and may be substituted for std::vector during -// serialization and deserialization. This substitution makes handling of C -// arrays more efficient by avoiding unnecessary copies when remote method -// signatures specify std::vector arguments or return values. -template -class ArrayWrapper { - public: - // Define types in the style of STL containers to support STL operators. - typedef T value_type; - typedef std::size_t size_type; - typedef T& reference; - typedef const T& const_reference; - typedef T* pointer; - typedef const T* const_pointer; - - ArrayWrapper() : buffer_(nullptr), capacity_(0), end_(0) {} - - ArrayWrapper(pointer buffer, size_type capacity, size_type size) - : buffer_(&buffer[0]), - capacity_(capacity), - end_(capacity < size ? capacity : size) {} - - ArrayWrapper(pointer buffer, size_type size) - : ArrayWrapper(buffer, size, size) {} - - ArrayWrapper(const ArrayWrapper& other) { *this = other; } - - ArrayWrapper(ArrayWrapper&& other) noexcept { *this = std::move(other); } - - ArrayWrapper& operator=(const ArrayWrapper& other) { - if (&other == this) { - return *this; - } else { - buffer_ = other.buffer_; - capacity_ = other.capacity_; - end_ = other.end_; - } - - return *this; - } - - ArrayWrapper& operator=(ArrayWrapper&& other) noexcept { - if (&other == this) { - return *this; - } else { - buffer_ = other.buffer_; - capacity_ = other.capacity_; - end_ = other.end_; - other.buffer_ = nullptr; - other.capacity_ = 0; - other.end_ = 0; - } - - return *this; - } - - pointer data() { return buffer_; } - const_pointer data() const { return buffer_; } - - pointer begin() { return &buffer_[0]; } - pointer end() { return &buffer_[end_]; } - const_pointer begin() const { return &buffer_[0]; } - const_pointer end() const { return &buffer_[end_]; } - - size_type size() const { return end_; } - size_type max_size() const { return capacity_; } - size_type capacity() const { return capacity_; } - - // Moves the end marker to |size|, clamping the end marker to the max capacity - // of the underlying array. This method does not change the size of the - // underlying array. - void resize(size_type size) { - if (size <= capacity_) - end_ = size; - else - end_ = capacity_; - } - - reference operator[](size_type pos) { return buffer_[pos]; } - const_reference operator[](size_type pos) const { return buffer_[pos]; } - - private: - pointer buffer_; - size_type capacity_; - size_type end_; -}; - -template -ArrayWrapper WrapArray(T* buffer, SizeType size) { - return ArrayWrapper(buffer, size); -} - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_ARRAY_WRAPPER_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/buffer_wrapper.h b/libs/vr/libpdx/private/pdx/rpc/buffer_wrapper.h deleted file mode 100644 index 43184ddd29..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/buffer_wrapper.h +++ /dev/null @@ -1,177 +0,0 @@ -#ifndef ANDROID_PDX_RPC_BUFFER_WRAPPER_H_ -#define ANDROID_PDX_RPC_BUFFER_WRAPPER_H_ - -#include -#include -#include -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Wrapper class for buffers, providing an interface suitable for -// SerializeObject and DeserializeObject. This class supports serialization of -// buffers as raw bytes. -template -class BufferWrapper; - -template -class BufferWrapper { - public: - // Define types in the style of STL containers to support STL operators. - typedef T value_type; - typedef std::size_t size_type; - typedef T& reference; - typedef const T& const_reference; - typedef T* pointer; - typedef const T* const_pointer; - - BufferWrapper() : buffer_(nullptr), capacity_(0), end_(0) {} - - BufferWrapper(pointer buffer, size_type capacity, size_type size) - : buffer_(&buffer[0]), - capacity_(capacity), - end_(capacity < size ? capacity : size) {} - - BufferWrapper(pointer buffer, size_type size) - : BufferWrapper(buffer, size, size) {} - - BufferWrapper(const BufferWrapper& other) { *this = other; } - - BufferWrapper(BufferWrapper&& other) noexcept { *this = std::move(other); } - - BufferWrapper& operator=(const BufferWrapper& other) { - if (&other == this) { - return *this; - } else { - buffer_ = other.buffer_; - capacity_ = other.capacity_; - end_ = other.end_; - } - - return *this; - } - - BufferWrapper& operator=(BufferWrapper&& other) noexcept { - if (&other == this) { - return *this; - } else { - buffer_ = other.buffer_; - capacity_ = other.capacity_; - end_ = other.end_; - other.buffer_ = nullptr; - other.capacity_ = 0; - other.end_ = 0; - } - - return *this; - } - - pointer data() { return buffer_; } - const_pointer data() const { return buffer_; } - - pointer begin() { return &buffer_[0]; } - pointer end() { return &buffer_[end_]; } - const_pointer begin() const { return &buffer_[0]; } - const_pointer end() const { return &buffer_[end_]; } - - size_type size() const { return end_; } - size_type max_size() const { return capacity_; } - size_type capacity() const { return capacity_; } - - void resize(size_type size) { - if (size <= capacity_) - end_ = size; - else - end_ = capacity_; - } - - reference operator[](size_type pos) { return buffer_[pos]; } - const_reference operator[](size_type pos) const { return buffer_[pos]; } - - private: - pointer buffer_; - size_type capacity_; - size_type end_; -}; - -template -class BufferWrapper> { - public: - using BufferType = typename std::vector; - using value_type = typename BufferType::value_type; - using size_type = typename BufferType::size_type; - using reference = typename BufferType::reference; - using const_reference = typename BufferType::const_reference; - using pointer = typename BufferType::pointer; - using const_pointer = typename BufferType::const_pointer; - using iterator = typename BufferType::iterator; - using const_iterator = typename BufferType::const_iterator; - - BufferWrapper() {} - explicit BufferWrapper(const BufferType& buffer) : buffer_(buffer) {} - BufferWrapper(const BufferType& buffer, const Allocator& allocator) - : buffer_(buffer, allocator) {} - explicit BufferWrapper(BufferType&& buffer) : buffer_(std::move(buffer)) {} - BufferWrapper(BufferType&& buffer, const Allocator& allocator) - : buffer_(std::move(buffer), allocator) {} - BufferWrapper(const BufferWrapper&) = default; - BufferWrapper(BufferWrapper&&) noexcept = default; - BufferWrapper& operator=(const BufferWrapper&) = default; - BufferWrapper& operator=(BufferWrapper&&) noexcept = default; - - pointer data() { return buffer_.data(); } - const_pointer data() const { return buffer_.data(); } - - iterator begin() { return buffer_.begin(); } - iterator end() { return buffer_.end(); } - const_iterator begin() const { return buffer_.begin(); } - const_iterator end() const { return buffer_.end(); } - - size_type size() const { return buffer_.size(); } - size_type max_size() const { return buffer_.capacity(); } - size_type capacity() const { return buffer_.capacity(); } - - void resize(size_type size) { buffer_.resize(size); } - void reserve(size_type size) { buffer_.reserve(size); } - - reference operator[](size_type pos) { return buffer_[pos]; } - const_reference operator[](size_type pos) const { return buffer_[pos]; } - - BufferType& buffer() { return buffer_; } - const BufferType& buffer() const { return buffer_; } - - private: - BufferType buffer_; -}; - -template -BufferWrapper WrapBuffer(T* buffer, SizeType size) { - return BufferWrapper(buffer, size); -} - -template -BufferWrapper WrapBuffer(void* buffer, SizeType size) { - return BufferWrapper(static_cast(buffer), size); -} - -template -BufferWrapper WrapBuffer(const void* buffer, - SizeType size) { - return BufferWrapper( - static_cast(buffer), size); -} - -template > -BufferWrapper> WrapBuffer( - std::vector&& buffer) { - return BufferWrapper>( - std::forward>(buffer)); -} - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_BUFFER_WRAPPER_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/copy_cv_reference.h b/libs/vr/libpdx/private/pdx/rpc/copy_cv_reference.h deleted file mode 100644 index 5ce34f8f9c..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/copy_cv_reference.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef ANDROID_PDX_RPC_COPY_CV_REFERENCE_H_ -#define ANDROID_PDX_RPC_COPY_CV_REFERENCE_H_ - -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Copies const, void, and reference qualifiers from type T to type U, such that -// the new type U' carries the same cv-reference qualifiers as T, with the same -// underlying type as U. -template -class CopyCVReference { - private: - using R = typename std::remove_reference::type; - using U1 = - typename std::conditional::value, - typename std::add_const::type, U>::type; - using U2 = - typename std::conditional::value, - typename std::add_volatile::type, U1>::type; - using U3 = - typename std::conditional::value, - typename std::add_lvalue_reference::type, - U2>::type; - using U4 = - typename std::conditional::value, - typename std::add_rvalue_reference::type, - U3>::type; - - public: - using Type = U4; -}; - -template -using CopyCVReferenceType = typename CopyCVReference::Type; - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_COPY_CV_REFERENCE_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/default_initialization_allocator.h b/libs/vr/libpdx/private/pdx/rpc/default_initialization_allocator.h deleted file mode 100644 index b6e298084e..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/default_initialization_allocator.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef ANDROID_PDX_RPC_DEFAULT_INITIALIZATION_ALLOCATOR_H_ -#define ANDROID_PDX_RPC_DEFAULT_INITIALIZATION_ALLOCATOR_H_ - -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Allocator adaptor that interposes construct() calls to convert value -// initialization into default initialization. All standard containers -// value-initialize their elements when constructed with a single size_type -// argument or when grown by a call to resize. This allocator avoids potentially -// costly value-initialization in these situations for value types that are -// default constructible. As a consequence, elements of non-class types are left -// uninitialized; this is desirable when using std::vector as a resizable -// buffer, for example. -template > -class DefaultInitializationAllocator : public Allocator { - typedef std::allocator_traits AllocatorTraits; - - public: - template - struct rebind { - using other = DefaultInitializationAllocator< - U, typename AllocatorTraits::template rebind_alloc>; - }; - - using Allocator::Allocator; - - template - void construct(U* pointer) noexcept( - std::is_nothrow_default_constructible::value) { - ::new (static_cast(pointer)) U; - } - template - void construct(U* pointer, Args&&... args) { - AllocatorTraits::construct(static_cast(*this), pointer, - std::forward(args)...); - } -}; - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_DEFAULT_INITIALIZATION_ALLOCATOR_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/encoding.h b/libs/vr/libpdx/private/pdx/rpc/encoding.h deleted file mode 100644 index f51d807f5b..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/encoding.h +++ /dev/null @@ -1,616 +0,0 @@ -#ifndef ANDROID_PDX_RPC_ENCODING_H_ -#define ANDROID_PDX_RPC_ENCODING_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "array_wrapper.h" -#include "buffer_wrapper.h" -#include "string_wrapper.h" -#include "variant.h" - -namespace android { -namespace pdx { -namespace rpc { - -// This library uses a subset, or profile, of MessagePack (http://msgpack.org) -// to encode supported data types during serialization and to verify the -// expected data types during deserialization. One notable deviation from the -// MessagePack specification is that little-endian byte order is used for -// multi-byte numeric types to avoid unnecessary conversion on nearly all -// relevant architectures. -// -// Some data types, integers for example, support multiple encoding strategies. -// This library attempts to optimize for space based on the value of such types. -// However, during decode all valid encodings for a given type are accepted. - -// Prefix byte for type encodings. This is the complete list of prefix bytes -// from the MessagePack specification, even though not all types are used by -// this library. -enum EncodingPrefix { - ENCODING_TYPE_POSITIVE_FIXINT = 0x00, - ENCODING_TYPE_POSITIVE_FIXINT_MIN = 0x00, - ENCODING_TYPE_POSITIVE_FIXINT_MAX = 0x7f, - ENCODING_TYPE_POSITIVE_FIXINT_MASK = 0x7f, - ENCODING_TYPE_FIXMAP = 0x80, - ENCODING_TYPE_FIXMAP_MIN = 0x80, - ENCODING_TYPE_FIXMAP_MAX = 0x8f, - ENCODING_TYPE_FIXMAP_MASK = 0x0f, - ENCODING_TYPE_FIXARRAY = 0x90, - ENCODING_TYPE_FIXARRAY_MIN = 0x90, - ENCODING_TYPE_FIXARRAY_MAX = 0x9f, - ENCODING_TYPE_FIXARRAY_MASK = 0x0f, - ENCODING_TYPE_FIXSTR = 0xa0, - ENCODING_TYPE_FIXSTR_MIN = 0xa0, - ENCODING_TYPE_FIXSTR_MAX = 0xbf, - ENCODING_TYPE_FIXSTR_MASK = 0x1f, - ENCODING_TYPE_NIL = 0xc0, - ENCODING_TYPE_RESERVED = 0xc1, - ENCODING_TYPE_FALSE = 0xc2, - ENCODING_TYPE_TRUE = 0xc3, - ENCODING_TYPE_BIN8 = 0xc4, - ENCODING_TYPE_BIN16 = 0xc5, - ENCODING_TYPE_BIN32 = 0xc6, - ENCODING_TYPE_EXT8 = 0xc7, - ENCODING_TYPE_EXT16 = 0xc8, - ENCODING_TYPE_EXT32 = 0xc9, - ENCODING_TYPE_FLOAT32 = 0xca, - ENCODING_TYPE_FLOAT64 = 0xcb, - ENCODING_TYPE_UINT8 = 0xcc, - ENCODING_TYPE_UINT16 = 0xcd, - ENCODING_TYPE_UINT32 = 0xce, - ENCODING_TYPE_UINT64 = 0xcf, - ENCODING_TYPE_INT8 = 0xd0, - ENCODING_TYPE_INT16 = 0xd1, - ENCODING_TYPE_INT32 = 0xd2, - ENCODING_TYPE_INT64 = 0xd3, - ENCODING_TYPE_FIXEXT1 = 0xd4, - ENCODING_TYPE_FIXEXT2 = 0xd5, - ENCODING_TYPE_FIXEXT4 = 0xd6, - ENCODING_TYPE_FIXEXT8 = 0xd7, - ENCODING_TYPE_FIXEXT16 = 0xd8, - ENCODING_TYPE_STR8 = 0xd9, - ENCODING_TYPE_STR16 = 0xda, - ENCODING_TYPE_STR32 = 0xdb, - ENCODING_TYPE_ARRAY16 = 0xdc, - ENCODING_TYPE_ARRAY32 = 0xdd, - ENCODING_TYPE_MAP16 = 0xde, - ENCODING_TYPE_MAP32 = 0xdf, - ENCODING_TYPE_NEGATIVE_FIXINT = 0xe0, - ENCODING_TYPE_NEGATIVE_FIXINT_MIN = 0xe0, - ENCODING_TYPE_NEGATIVE_FIXINT_MAX = 0xff, -}; - -// Base encoding classes grouping multi-strategy encodings. -enum EncodingClass { - ENCODING_CLASS_BOOL, - ENCODING_CLASS_NIL, - ENCODING_CLASS_INT, - ENCODING_CLASS_UINT, - ENCODING_CLASS_FLOAT, - ENCODING_CLASS_ARRAY, - ENCODING_CLASS_MAP, - ENCODING_CLASS_STRING, - ENCODING_CLASS_BINARY, - ENCODING_CLASS_EXTENSION, -}; - -// Encoding prefixes are unsigned bytes. -typedef std::uint8_t EncodingType; - -// Extension encoding types defined by this library. -enum EncodingExtType : int8_t { - ENCODING_EXT_TYPE_FILE_DESCRIPTOR, - ENCODING_EXT_TYPE_CHANNEL_HANDLE, -}; - -// Encoding predicates. Determines whether the given encoding is of a specific -// type. -inline constexpr bool IsFixintEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_NEGATIVE_FIXINT_MIN ... ENCODING_TYPE_NEGATIVE_FIXINT_MAX: - return true; - default: - return false; - } -} - -inline constexpr bool IsUnsignedFixintEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - return true; - default: - return false; - } -} - -inline constexpr bool IsInt8Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_NEGATIVE_FIXINT_MIN ... ENCODING_TYPE_NEGATIVE_FIXINT_MAX: - case ENCODING_TYPE_INT8: - return true; - default: - return false; - } -} - -inline constexpr bool IsUInt8Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_UINT8: - return true; - default: - return false; - } -} - -inline constexpr bool IsInt16Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_NEGATIVE_FIXINT_MIN ... ENCODING_TYPE_NEGATIVE_FIXINT_MAX: - case ENCODING_TYPE_INT8: - case ENCODING_TYPE_INT16: - return true; - default: - return false; - } -} - -inline constexpr bool IsUInt16Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_UINT8: - case ENCODING_TYPE_UINT16: - return true; - default: - return false; - } -} - -inline constexpr bool IsInt32Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_NEGATIVE_FIXINT_MIN ... ENCODING_TYPE_NEGATIVE_FIXINT_MAX: - case ENCODING_TYPE_INT8: - case ENCODING_TYPE_INT16: - case ENCODING_TYPE_INT32: - return true; - default: - return false; - } -} - -inline constexpr bool IsUInt32Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_UINT8: - case ENCODING_TYPE_UINT16: - case ENCODING_TYPE_UINT32: - return true; - default: - return false; - } -} - -inline constexpr bool IsInt64Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_NEGATIVE_FIXINT_MIN ... ENCODING_TYPE_NEGATIVE_FIXINT_MAX: - case ENCODING_TYPE_INT8: - case ENCODING_TYPE_INT16: - case ENCODING_TYPE_INT32: - case ENCODING_TYPE_INT64: - return true; - default: - return false; - } -} - -inline constexpr bool IsUInt64Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_UINT8: - case ENCODING_TYPE_UINT16: - case ENCODING_TYPE_UINT32: - case ENCODING_TYPE_UINT64: - return true; - default: - return false; - } -} - -inline constexpr bool IsFixmapEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FIXMAP_MIN ... ENCODING_TYPE_FIXMAP_MAX: - return true; - default: - return false; - } -} - -inline constexpr bool IsFixarrayEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FIXARRAY_MIN ... ENCODING_TYPE_FIXARRAY_MAX: - return true; - default: - return false; - } -} - -inline constexpr bool IsFixstrEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FIXSTR_MIN ... ENCODING_TYPE_FIXSTR_MAX: - return true; - default: - return false; - } -} - -inline constexpr bool IsFixextEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FIXEXT1: - case ENCODING_TYPE_FIXEXT2: - case ENCODING_TYPE_FIXEXT4: - case ENCODING_TYPE_FIXEXT8: - case ENCODING_TYPE_FIXEXT16: - return true; - default: - return false; - } -} - -inline constexpr bool IsFloat32Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FLOAT32: - return true; - default: - return false; - } -} - -inline constexpr bool IsFloat64Encoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FLOAT32: - case ENCODING_TYPE_FLOAT64: - return true; - default: - return false; - } -} - -inline constexpr bool IsBoolEncoding(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FALSE: - case ENCODING_TYPE_TRUE: - return true; - default: - return false; - } -} - -inline constexpr std::size_t GetFixstrSize(EncodingType encoding) { - return encoding & ENCODING_TYPE_FIXSTR_MASK; -} - -inline constexpr std::size_t GetFixarraySize(EncodingType encoding) { - return encoding & ENCODING_TYPE_FIXARRAY_MASK; -} - -inline constexpr std::size_t GetFixmapSize(EncodingType encoding) { - return encoding & ENCODING_TYPE_FIXMAP_MASK; -} - -inline constexpr std::size_t GetFixextSize(EncodingType encoding) { - switch (encoding) { - case ENCODING_TYPE_FIXEXT1: - return 1; - case ENCODING_TYPE_FIXEXT2: - return 2; - case ENCODING_TYPE_FIXEXT4: - return 4; - case ENCODING_TYPE_FIXEXT8: - return 8; - case ENCODING_TYPE_FIXEXT16: - return 16; - default: - return 0; // Invalid fixext size. - } -} - -// Gets the size of the encoding in bytes, not including external payload data. -inline constexpr std::size_t GetEncodingSize(EncodingType encoding) { - switch (encoding) { - // Encoding is fully contained within the type value. - case ENCODING_TYPE_POSITIVE_FIXINT_MIN ... ENCODING_TYPE_POSITIVE_FIXINT_MAX: - case ENCODING_TYPE_NEGATIVE_FIXINT_MIN ... ENCODING_TYPE_NEGATIVE_FIXINT_MAX: - case ENCODING_TYPE_FIXMAP_MIN ... ENCODING_TYPE_FIXMAP_MAX: - case ENCODING_TYPE_FIXARRAY_MIN ... ENCODING_TYPE_FIXARRAY_MAX: - case ENCODING_TYPE_FIXSTR_MIN ... ENCODING_TYPE_FIXSTR_MAX: - case ENCODING_TYPE_NIL: - case ENCODING_TYPE_RESERVED: - case ENCODING_TYPE_FALSE: - case ENCODING_TYPE_TRUE: - return 1; - - // Encoding type followed by one-byte size or immediate value. - case ENCODING_TYPE_BIN8: - case ENCODING_TYPE_EXT8: - case ENCODING_TYPE_UINT8: - case ENCODING_TYPE_INT8: - case ENCODING_TYPE_STR8: - // Encoding type followed by one-byte extension type. - case ENCODING_TYPE_FIXEXT1: - case ENCODING_TYPE_FIXEXT2: - case ENCODING_TYPE_FIXEXT4: - case ENCODING_TYPE_FIXEXT8: - case ENCODING_TYPE_FIXEXT16: - return 2; - - // Encoding type followed by two-byte size or immediate value. - case ENCODING_TYPE_BIN16: - case ENCODING_TYPE_EXT16: - case ENCODING_TYPE_UINT16: - case ENCODING_TYPE_INT16: - case ENCODING_TYPE_STR16: - case ENCODING_TYPE_ARRAY16: - case ENCODING_TYPE_MAP16: - return 3; - - // Encoding type followed by four-byte size or immediate value. - case ENCODING_TYPE_BIN32: - case ENCODING_TYPE_EXT32: - case ENCODING_TYPE_FLOAT32: - case ENCODING_TYPE_UINT32: - case ENCODING_TYPE_INT32: - case ENCODING_TYPE_STR32: - case ENCODING_TYPE_ARRAY32: - case ENCODING_TYPE_MAP32: - return 5; - - // Encoding type followed by eight-byte immediate value. - case ENCODING_TYPE_FLOAT64: - case ENCODING_TYPE_UINT64: - case ENCODING_TYPE_INT64: - return 9; - - default: - return 0; - } -} - -// Encoding for standard types. Each supported data type has an associated -// encoding or set of encodings. These functions determine the MessagePack -// encoding based on the data type, value, and size of their arguments. - -inline constexpr EncodingType EncodeArrayType(std::size_t size) { - if (size < (1U << 4)) - return ENCODING_TYPE_FIXARRAY | (size & ENCODING_TYPE_FIXARRAY_MASK); - else if (size < (1U << 16)) - return ENCODING_TYPE_ARRAY16; - else - return ENCODING_TYPE_ARRAY32; -} - -inline constexpr EncodingType EncodeMapType(std::size_t size) { - if (size < (1U << 4)) - return ENCODING_TYPE_FIXMAP | (size & ENCODING_TYPE_FIXMAP_MASK); - else if (size < (1U << 16)) - return ENCODING_TYPE_MAP16; - else - return ENCODING_TYPE_MAP32; -} - -inline constexpr EncodingType EncodeStringType(std::size_t size) { - if (size < (1U << 5)) - return ENCODING_TYPE_FIXSTR | (size & ENCODING_TYPE_FIXSTR_MASK); - else if (size < (1U << 8)) - return ENCODING_TYPE_STR8; - else if (size < (1U << 16)) - return ENCODING_TYPE_STR16; - else - return ENCODING_TYPE_STR32; -} - -inline constexpr EncodingType EncodeBinType(std::size_t size) { - if (size < (1U << 8)) - return ENCODING_TYPE_BIN8; - else if (size < (1U << 16)) - return ENCODING_TYPE_BIN16; - else - return ENCODING_TYPE_BIN32; -} - -inline EncodingType EncodeType(const EmptyVariant& /*empty*/) { - return ENCODING_TYPE_NIL; -} - -// Variant is encoded as a single-element map, with the type index as the key. -template -inline EncodingType EncodeType(const Variant& /*variant*/) { - return EncodeMapType(1); -} - -template -inline constexpr EncodingType EncodeType(const StringWrapper& value) { - return EncodeStringType(value.length()); -} - -inline constexpr EncodingType EncodeType(const std::string& value) { - return EncodeStringType(value.length()); -} - -template -inline constexpr EncodingType EncodeType(const std::array& /*value*/) { - return EncodeArrayType(Size); -} - -template -inline constexpr EncodingType EncodeType(const ArrayWrapper& value) { - return EncodeArrayType(value.size()); -} - -template -inline constexpr EncodingType EncodeType( - const std::vector& value) { - return EncodeArrayType(value.size()); -} - -template -inline constexpr EncodingType EncodeType( - const std::map& value) { - return EncodeMapType(value.size()); -} - -template -inline constexpr EncodingType EncodeType( - const std::unordered_map& value) { - return EncodeMapType(value.size()); -} - -template -inline constexpr EncodingType EncodeType(const BufferWrapper& value) { - // BIN size is in bytes. - return EncodeBinType(value.size() * - sizeof(typename BufferWrapper::value_type)); -} - -template -inline constexpr EncodingType EncodeType(const std::pair& /*value*/) { - return EncodeArrayType(2); -} - -template -inline constexpr EncodingType EncodeType(const std::tuple& /*value*/) { - return EncodeArrayType(sizeof...(T)); -} - -// FileHandle is encoded as a FIXEXT2 with a type code for "FileDescriptor" -// and a signed 16-bit index into the pushed fd array. Empty file descriptor -// have an array index of -1. -template -inline constexpr EncodingType EncodeType(const FileHandle& /*fd*/) { - return ENCODING_TYPE_FIXEXT2; -} - -// ChannelHandle is encoded as a FIXEXT4 with a type of -// ENCODING_EXT_TYPE_CHANNEL_HANDLE and a signed 32-bit value representing -// a client channel in a remote process. Empty handle has a value of -1. -template -inline constexpr EncodingType EncodeType( - const ChannelHandle& /*handle*/) { - return ENCODING_TYPE_FIXEXT4; -} - -inline constexpr EncodingType EncodeType(const bool& value) { - return value ? ENCODING_TYPE_TRUE : ENCODING_TYPE_FALSE; -} - -// Type 'char' is a little bit special in that it is distinct from 'signed char' -// and 'unsigned char'. Treating it as an unsigned 8-bit value is safe for -// encoding purposes and nicely handles 7-bit ASCII encodings as FIXINT. -inline constexpr EncodingType EncodeType(const char& value) { - if (value < static_cast(1 << 7)) - return value; - else - return ENCODING_TYPE_UINT8; -} - -inline constexpr EncodingType EncodeType(const uint8_t& value) { - if (value < (1U << 7)) - return value; - else - return ENCODING_TYPE_UINT8; -} -inline constexpr EncodingType EncodeType(const int8_t& value) { - if (value >= -32) - return value; - else - return ENCODING_TYPE_INT8; -} -inline constexpr EncodingType EncodeType(const uint16_t& value) { - if (value < (1U << 7)) - return static_cast(value); - else if (value < (1U << 8)) - return ENCODING_TYPE_UINT8; - else - return ENCODING_TYPE_UINT16; -} -inline constexpr EncodingType EncodeType(const int16_t& value) { - if (value >= -32 && value <= 127) - return static_cast(value); - else if (value >= -128 && value <= 127) - return ENCODING_TYPE_INT8; - else - return ENCODING_TYPE_INT16; -} -inline constexpr EncodingType EncodeType(const uint32_t& value) { - if (value < (1U << 7)) - return static_cast(value); - else if (value < (1U << 8)) - return ENCODING_TYPE_UINT8; - else if (value < (1U << 16)) - return ENCODING_TYPE_UINT16; - else - return ENCODING_TYPE_UINT32; -} -inline constexpr EncodingType EncodeType(const int32_t& value) { - if (value >= -32 && value <= 127) - return static_cast(value); - else if (value >= -128 && value <= 127) - return ENCODING_TYPE_INT8; - else if (value >= -32768 && value <= 32767) - return ENCODING_TYPE_INT16; - else - return ENCODING_TYPE_INT32; -} -inline constexpr EncodingType EncodeType(const uint64_t& value) { - if (value < (1ULL << 7)) - return static_cast(value); - else if (value < (1ULL << 8)) - return ENCODING_TYPE_UINT8; - else if (value < (1ULL << 16)) - return ENCODING_TYPE_UINT16; - else if (value < (1ULL << 32)) - return ENCODING_TYPE_UINT32; - else - return ENCODING_TYPE_UINT64; -} -inline constexpr EncodingType EncodeType(const int64_t& value) { - if (value >= -32 && value <= 127) - return static_cast(value); - else if (value >= -128 && value <= 127) // Effectively [-128, -32). - return ENCODING_TYPE_INT8; - else if (value >= -32768 && value <= 32767) - return ENCODING_TYPE_INT16; - else if (value >= -2147483648 && value <= 2147483647) - return ENCODING_TYPE_INT32; - else - return ENCODING_TYPE_INT64; -} - -inline constexpr EncodingType EncodeType(const float& /*value*/) { - return ENCODING_TYPE_FLOAT32; -} - -inline constexpr EncodingType EncodeType(const double& /*value*/) { - return ENCODING_TYPE_FLOAT64; -} - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_ENCODING_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/enumeration.h b/libs/vr/libpdx/private/pdx/rpc/enumeration.h deleted file mode 100644 index 7a35d31b22..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/enumeration.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef ANDROID_PDX_RPC_ENUMERATION_H_ -#define ANDROID_PDX_RPC_ENUMERATION_H_ - -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Utility for manipulating lists of types. Provides operations to lookup an -// element by type or index. - -namespace detail { - -// Helper type that captures type and index for each element of a type -// enumeration. -template -struct IndexedElement { - using Type = T; - static constexpr std::size_t Index = I; -}; - -// Helper type that captures an IndexSequence and corresponding list of types. -template -struct ElementIndexer; - -// Partial specialization that generates an instantiation of IndexElement -// for each element of a type enumeration using inheritance. Once a type -// enumeration is instantiated this way the compiler is able to deduce either I -// or T from the other using the method below. -template -struct ElementIndexer, Ts...> : IndexedElement... { -}; - -// Helper function that causes the compiler to deduce an IndexedElement -// given T. -template -static IndexedElement SelectElementByType(IndexedElement); - -// Helper function that causes the compiler to deduce an IndexedElement -// given I. -template -static IndexedElement SelectElementByIndex(IndexedElement); - -} // namespace detail - -// Deduces the IndexedElement given T and a type sequence Ts. This may be -// used to determine the index of T within Ts at compile time. -template -using ElementForType = decltype(detail::SelectElementByType( - detail::ElementIndexer::type, Ts...>{})); - -// Deduces the IndexedElement given I and a type sequence Ts. This may be -// used to determine the type of the element at index I within Ts at compile -// time. Tuple operations may also be used to accomplish the same task, however -// this implementation is provided here for symmetry. -template -using ElementForIndex = decltype(detail::SelectElementByIndex( - detail::ElementIndexer::type, Ts...>{})); - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_ENUMERATION_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/find_replace.h b/libs/vr/libpdx/private/pdx/rpc/find_replace.h deleted file mode 100644 index b4b086bd05..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/find_replace.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef ANDROID_PDX_RPC_FIND_REPLACE_H_ -#define ANDROID_PDX_RPC_FIND_REPLACE_H_ - -#include - -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Utility class to capture types to find and replace. -template -struct FindReplace; - -template -using IsSameBaseType = typename std::is_same::type, - typename std::decay::type>; - -// Replaces the type Subject with type Replace if type Subject is the same type -// as type Find, excluding cv-reference qualifiers in the match. -template -using ReplaceType = - typename std::conditional::value, - CopyCVReferenceType, - Subject>::type; - -// Determines whether the type Find (excluding cv-reference qualifiers) is in -// the given parameter pack. -template -struct ContainsType : std::true_type {}; - -template -struct ContainsType - : std::conditional::value, std::true_type, - ContainsType>::type {}; - -template -struct ContainsType : std::false_type {}; - -} // namespace rpc -} // namespace pdx -} // namespace android - -#endif // ANDROID_PDX_RPC_FIND_REPLACE_H_ diff --git a/libs/vr/libpdx/private/pdx/rpc/function_traits.h b/libs/vr/libpdx/private/pdx/rpc/function_traits.h deleted file mode 100644 index 7641b0a7c1..0000000000 --- a/libs/vr/libpdx/private/pdx/rpc/function_traits.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef ANDROID_PDX_RPC_FUNCTION_TRAITS_H_ -#define ANDROID_PDX_RPC_FUNCTION_TRAITS_H_ - -#include - -#include - -namespace android { -namespace pdx { -namespace rpc { - -// Utility type to capture return and argument types of a function signature. -// Examples: -// typedef SignatureType SignatureType; -// using SignatureType = SignatureType; -template -using SignatureType = T; - -// Utility class to extract return and argument types from function types. -// Provides nested types for return value, arguments, and full signature. Also -// provides accessor types for individual arguments, argument-arity, and type -// substitution. -template -struct FunctionTraits; - -template -struct FunctionTraits { - using Return = Return_; - using Args = std::tuple; - using Signature = SignatureType; - - enum : std::size_t { Arity = sizeof...(Args_) }; - - template - using Arg = typename std::tuple_element::type; - - template - using RewriteArgs = - SignatureType...)>; - - template - using RewriteSignature = - SignatureType( - ConditionalRewrite...)>; - - template